I tried making a mario clone in pygame/python. for some reason my character keeps spawning in the side. no matter what x i give to it

Viewed 55

The problem is, I declared self.rect.x=x, and in Mario function x=300, but when I try to access mario.draw for some reason mario spawns at -35 in x coordinates. Can someone help me with this? My past codes have worked with the method I'm using but now it just doesn't work. The y coordinate doesn't work either. It just spawns at the middle of the screen.

Small note: I had a function named draw that blited the screen self.rect and self.image.

import pygame
from pygame.locals import *
import os
#Starting up the game
pygame.init()
clock=pygame.time.Clock()
#screen
SCREENWIDTH=800
SCREENHEIGHT=int(SCREENWIDTH*0.8)
screen=pygame.display.set_mode((SCREENWIDTH,SCREENHEIGHT))
pygame.display.set_caption("Mario")
#functions and classes
class Mario():
    def __init__(self,x,y,speed):
        """making my variables"""
        self.speed=speed
        self.in_air=False
        self.flip=False
        self.vel_y=0
        self.jump=False
        self.direction=1
        self.animation_list=[]
        self.action=0
        self.index=0
        animation_types=["idle","run"]
        temp_list=[]
        for animation in animation_types:
            temp_list=[]
            num_frames=len(os.listdir(f"Mario/img/{animation}"))
            for x in range(num_frames):
                img=pygame.image.load(f"Mario/img/{animation}/{x}.png").convert_alpha()
                img=pygame.transform.scale(img,(70,70))
                temp_list.append(img)
            self.animation_list.append(temp_list)
        self.image=self.animation_list[self.action][self.index]
        self.rect=self.image.get_rect()
        """ i specifically here say self.rect.x=x"""
        self.rect.x=x
        self.rect.y=y    
    pygame.display.update()
1 Answers

As lain said, when you did:

for x in range(num_frames):

you took the x you got as a variable in the function def __init__(self,x,y,speed) and you changed it, based on the result that range(num_frames) will give you. This is always how for loop works. if there is a variable it will change it, and the change will continue after the loop. if there isn't a variable, it will make a new one.

You can either put these two lines:

self.rect.x=x
self.rect.y=y

before the for loop that changing the x, or you can just use a different variable in the loop, instead of x.

Related