How to flip an img in Pygame, having trouble in my code? - python

I'm having trouble flipping a sprite in pygame (I can get it to go right but I want the img to flip on the left key),
I researched how to flip an image and found the pygame.transform.flip, but as a beginner to pygame, I'm not sure how to use it, and the tutorials aren't making sense to me.
Can anyone help me with the code below (I'm not sure if I even put the self.img1 for the flip in the right place)?
import pygame, sys, glob
from pygame import *
class Player:
def __init__(self):
self.x = 200
self.y = 300
self.ani_speed_init = 6
self.ani_speed = self.ani_speed_init
self.ani = glob.glob("walk\Pinks_w*.png")
self.ani.sort()
self.ani_pos = 0
self.ani_max = len(self.ani)-1
self.img = pygame.image.load(self.ani[0])
self.img1 = pygame.transform.flip(self.ani[0], True, False)
self.update(0)
def update(self, pos):
if pos != 0:
self.ani_speed-=1
self.x+=pos
if self.ani_speed == 0:
self.img = pygame.image.load(self.ani[self.ani_pos])
self.ani_speed = self.ani_speed_init
if self.ani_pos == self.ani_max:
self.ani_pos = 0
else:
self.ani_pos+=1
screen.blit(self.img,(self.x,self.y))
h = 400
w = 800
screen = pygame.display.set_mode((w,h))
clock = pygame.time.Clock()
player1 = Player()
pos = 0
while True:
screen.fill((0,0,0))
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == KEYDOWN and event.key == K_RIGHT:
pos = 1
elif event.type == KEYUP and event.key == K_RIGHT:
pos = 0
elif event.type == KEYDOWN and event.key == K_LEFT:
pos = -1
elif event.type == KEYUP and event.key == K_LEFT:
pos = 0
player1.update(pos)
pygame.display.update()

To flip, you would do:
# input
if event.type == KEYDOWN:
if event.key == K_RIGHT:
flip_x = True
elif event.key == K_LEFT:
flip_x = False
elif event.key == K_UP:
flip_y = True
elif event.key == K_DOWN:
flip_y = False
# then to flip
new_image = pygame.transform.flip(original_image, flip_x, flip_y)

Your Player class is not very well readable. As, your names are not easy to understand.
In my version of your code, all I have changed is the names and I have added a check for the value of pos and applied the flip if needed. So, you may need to change the check (if condition), to get the desired results.
And Yes, you don't have a pygame.Sprite, so, the word sprite is misleading, in this case.
My version of your Player class:
class Player:
def __init__(self):
self.x = 200
self.y = 300
self.speed_init = 6
self.images = [pygame.image.load(img) for img in glob.glob("walk\Pinks_w*.png")]
self.index = 0
self.max_index = len(self.images)-1
self.speed = 0
self.img = self.images[self.index]
def update(self, pos):
if pos != 0:
self.speed -= 1
self.x += pos
if not self.speed:
self.speed = self.speed_init
if self.index < self.max_index:
self.index += 1
else:
self.index = 0
self.img = self.images[self.index]
# change True to False if needed, or change the operator.
if pos > 0:
self.img = pygame.transform.flip(self.img,True,False)
screen.blit(self.img,(self.x,self.y))
Update
There was a small problem with the update function. The problem was that since speed was always constant and not 0, the if not self.speed: did not work. So, change the update function to this:
def update(self, pos):
if pos != 0:
self.speed -= 1
self.x += pos
# no more self.speed checks
if self.index < self.max_index:
self.index += 1
else:
self.index = 0
self.img = self.images[self.index]
# change True to False if needed, or change the operator.
if pos < 0:
self.img = pygame.transform.flip(self.img,True,False)
screen.blit(self.img,(self.x,self.y))
Update 2
It seems that there is some kind of typo in your code,
Here's (my version of) the Code, The whole thing.
import pygame, sys, glob
from pygame import *
class Player:
def __init__(self):
self.x = 200
self.y = 300
self.speed_init = 6
self.images = [pygame.image.load(img) for img in glob.glob("walk\Pinks_w*.png")]
self.index = 0
self.max_index = len(self.images)-1
self.speed = 0
self.img = self.images[self.index]
print self.max_index
def update(self, pos):
if pos != 0:
self.speed -= 1
self.x += pos
print self.index, self.max_index
if self.index < self.max_index:
self.index += 1
else:
self.index = 0
self.img = self.images[self.index]
# change True to False if needed, or change the operator.
if pos < 0:
self.img = pygame.transform.flip(self.img,True,False)
screen.blit(self.img,(self.x,self.y))
h = 400
w = 800
screen = pygame.display.set_mode((w,h))
clock = pygame.time.Clock()
player1 = Player()
pos = 0
while True:
screen.fill((0,0,0))
clock.tick(20)
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == KEYDOWN and event.key == K_RIGHT:
pos = 2
elif event.type == KEYUP and event.key == K_RIGHT:
pos = 0
elif event.type == KEYDOWN and event.key == K_LEFT:
pos = -2
elif event.type == KEYUP and event.key == K_LEFT:
pos = 0
player1.update(pos)
pygame.display.update()

Related

the attack animation is not executing

i tried but i cant find the error pls help how do i execute it?
im new so, it would be a great help if u tell me a clean way of adding attack animation also
import pygame
import os
pygame.init
t = pygame.display.set_mode((1280,720))
pygame.display.set_caption("my first game moce")
clock = pygame.time.Clock()
FPS = 60
RED = (255,0,0)
#game variables
GRAVITY = 0.75
moving_left = False
moving_right = False
#load images
R =[pygame.image.load('img/hero/attack/0.png'),pygame.image.load('img/hero/attack/1.png'),pygame.image.load('img/hero/attack/2.png'),pygame.image.load('img/hero/attack/3.png'),pygame.image.load('img/hero/attack/4.png'),pygame.image.load('img/hero/attack/5.png'),pygame.image.load('img/hero/attack/6.png'),pygame.image.load('img/hero/attack/7.png'),pygame.image.load('img/hero/attack/8.png'),pygame.image.load('img/hero/attack/9.png')]
L =[pygame.image.load('img/hero/attack L/0.png'),pygame.image.load('img/hero/attack L/1.png'),pygame.image.load('img/hero/attack L/2.png'),pygame.image.load('img/hero/attack L/3.png'),pygame.image.load('img/hero/attack L/4.png'),pygame.image.load('img/hero/attack L/5.png'),pygame.image.load('img/hero/attack L/6.png'),pygame.image.load('img/hero/attack L/7.png'),pygame.image.load('img/hero/attack L/8.png'),pygame.image.load('img/hero/attack L/9.png')]
class soldier(pygame.sprite.Sprite):
def __init__(self, char_type,x,y,scale,speed):
pygame.sprite.Sprite.__init__(self)
self.alive = True
self.char_type = char_type
self.speed = speed
self.direction = 1
self.vel_y = 0
self.jump = False
self.in_air = True
self.flip = False
self.attacking = False
self.attack_frame = 0
self.animation_list = []
self.frame_index = 0
self.action = 0
self.update_time = pygame.time.get_ticks()
animation_types = ['idle','jump','run']
for animation in animation_types:
temp_list = []
num_of_frames = len(os.listdir(f'img/{self.char_type}/{animation}'))
for i in range(num_of_frames):
img = (pygame.image.load(f'img/{self.char_type}/{animation}/{i}.png'))
img = pygame.transform.scale(img,(int(img.get_width()*scale),int(img.get_height()*scale)))
temp_list.append(img)
self.animation_list.append(temp_list)
self.img = self.animation_list[self.action][self.frame_index]
self.rect = self.img.get_rect()
self.rect.center = (x,y)
def move(self, moving_left, moving_right):
dx = 0
dy = 0
if moving_left:
dx = -self.speed
self.flip = True
self.direction = -1
if moving_right:
dx = self.speed
self.flip = False
self.direction = 1
if self.jump == True and self.in_air == False:
self.vel_y = -11
self.jump = False
self.in_air = True
#appy gravity
self.vel_y += GRAVITY
if self.vel_y > 10:
self.vel_y
dy += self.vel_y
#check collison with floor
if self.rect.bottom +dy > 300:
dy = 300 - self.rect.bottom
self.in_air = False
self.rect.x += dx
self.rect.y += dy
def update_animation(self):
ANIMATION_COOLDOWN = 100
if pygame.time.get_ticks() - self.update_time > ANIMATION_COOLDOWN:
self.img = self.animation_list[self.action][self.frame_index]
self.update_time = pygame.time.get_ticks()
self.frame_index += 1
#if out of animation
if self.frame_index >= len(self.animation_list[self.action]):
self.frame_index = 0
def update_action(self, new_action):
if new_action != self.action:
self.action = new_action
self.frame_index = 0
self.update_time = pygame.time.get_ticks()
def attack(self):
if self.attack_frame > 10:
self.attack_frame = 0
self.attacking = False
if self.direction == 'RIGHT':
self.image = R[self.attack_frame]
elif self.direction == 'LEFT':
self.correction()
self.image = L[self.attack_frame]
self.attack_frame += 1
def correction(self):
# Function is used to correct an error
# with character position on left attack frames
if self.attack_frame == 1:
self.pos.x -= 20
if self.attack_frame == 10:
self.pos.x += 20
def draw(self):
t.blit(pygame.transform.flip(self.img,self.flip,False),self.rect)
player = soldier("hero",200,200,2,5)
width = 30
height = 60
x = 300
y = 0
jump = False
jump_count = 10
run = True
background_image = pygame.image.load("C:/Users/Owner/Desktop/q1.png").convert()
while run:
t.blit(background_image,(0,0))
clock.tick(FPS)
player.update_animation()
player.draw()
player.move(moving_left, moving_right)
if player.alive:
if player.attacking == True:
player.attack()
if player.in_air:
player.update_action(1)
elif moving_left or moving_right:
player.update_action(2)
else:
player.update_action(0)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
moving_left = True
if event.key == pygame.K_d:
moving_right = True
moving_left = False
if event.key == pygame.K_SPACE and player.alive:
player.jump = True
if event.key == pygame.K_ESCAPE:
run = False
if event.key == pygame.K_LSHIFT:
player.speed = 7
if event.key == pygame.K_e:
if player.attacking == False:
player.attack()
player.attacking = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_a:
moving_left = False
if event.key == pygame.K_d:
moving_right = False
if event.key == pygame.K_SPACE:
player.jump = False
if event.key == pygame.K_LSHIFT:
player.speed = 5
if event.key == pygame.K_e:
if player.attacking == True:
player.attacking = False
pygame.display.update()
pygame.quit()
You have different options depending on the effect you want to achieve.
In your current implementation, an attack is stopped when the e button is released. I recommend to remove that code:
while run:
# [...]
for event in pygame.event.get():
# [...]
if event.type == pygame.KEYUP:
# [...]
# DELETE
# if event.key == pygame.K_e:
# if player.attacking == True:
# player.attacking = False
# self.attack_frame = 0
If you want to stop the attack when the e button is released, you must also reset self.attack_frame
while run:
# [...]
for event in pygame.event.get():
# [...]
if event.type == pygame.KEYUP:
# [...]
if event.key == pygame.K_e:
if player.attacking == True:
player.attacking = False
self.attack_frame = 0
If you want to allow continuous attacks and interrupt an attack, you need to change the implementation in the KEYDOWN event and reset self.attack_frame when e is pressed:
while run:
# [...]
for event in pygame.event.get():
# [...]
if event.type == pygame.KEYDOWN:
# [...]
if event.key == pygame.K_e:
player.attacking = True
self.attack_frame = 0
if event.type == pygame.KEYUP:
# [...]
# DELETE
# if event.key == pygame.K_e:
# if player.attacking == True:
# player.attacking = False
# self.attack_frame = 0

Issue with Collision Detection in Pygame for simple 2D Platformer

This is my first post so please let me know if I should alter anything.
I am attempting to create a simple test 2D platformer, this is the first pygame project I've undertaken without a tutorial. The issue I am encountering is due to this can_jump variable. I am using this variable to stop the player from being able to jump when not on a platform or the bottom of the screen. I had attempted other methods but this is where I have ended up. I feel I've gotten so close.
The issue at the moment appears to be that the variable self.can_jump1 continuously swaps between True and False in the platform loop (at exactly 3 Falses for every True I have noticed) when standing on a platform, I have isolated it to the commented section in collision_check(). I don't know why this happens, and as far as I can tell the rest of the code works as I want it.
I would be happy to provide any extra information/clarification if need be.
Here's my code:
import pygame, sys, random
#---Classes----------------------------------------#
class Block(pygame.sprite.Sprite): #inherited by rest of classes
def __init__(self,path,x_pos,y_pos,size_x,size_y):
super().__init__()
self.image = pygame.transform.scale(pygame.image.load(path).convert_alpha(),(size_x,size_y))
self.rect = self.image.get_rect(center = (x_pos,y_pos))
class PlatformRect(pygame.sprite.Sprite):
def __init__(self,x_pos,y_pos,size_x,size_y,colour,players):
super().__init__()
self.center_x = x_pos
self.center_y = y_pos
self.size_x = size_x
self.size_y = size_y
self.colour = colour
self.players = players
self.can_jump1 = None
self.image = pygame.Surface((self.size_x,self.size_y))
self.image.fill(self.colour)
self.rect = self.image.get_rect(center = (self.center_x,self.center_y))
def collision_check(self):
if pygame.sprite.spritecollide(self,self.players,False):
collision_paddle = pygame.sprite.spritecollide(self,self.players,False)[0].rect
if abs(self.rect.top - collision_paddle.bottom) < 10:
collision_paddle.bottom = self.rect.top
player.movement_y = 0
self.can_jump1 = True
else: #error isolated to here,consistently fluctuates between True and False, not sure why
self.can_jump1 = False
print(self.can_jump1) #if standing on platform should only produce True, everywhere else produce False
def can_jump_check(self):
return self.can_jump1
def update(self):
self.collision_check()
class Player(Block):
def __init__(self,path,x_pos,y_pos,size_x,size_y,speed_x,acceleration_y):
super().__init__(path,x_pos,y_pos,size_x,size_y)
self.size_x = size_x
self.size_y = size_y
self.speed_x = speed_x
self.acceleration_y = acceleration_y
self.movement_x = 0
self.movement_y = 0
def screen_constrain(self):
if self.rect.bottom >= sresy:
self.rect.bottom = sresy
if self.rect.left <= 0:
self.rect.left = 0
if self.rect.right >= sresx:
self.rect.right = sresx
def update(self):
if abs(self.movement_y) <= 9:
self.movement_y += GRAVITY
self.rect.centery += self.movement_y
self.rect.centerx += self.movement_x
self.screen_constrain()
class GameManager:
def __init__(self,player_group,platform_group):
self.player_group = player_group
self.platform_group = platform_group
self.can_jump = True
def run_game(self):
#---drawing---#
self.player_group.draw(screen)
self.platform_group.draw(screen)
#---updating---#
self.player_group.update()
self.platform_group.update()
def game_checking(self):
#---checking---#
for sprite_platform in self.platform_group.sprites():
if not sprite_platform.can_jump_check() == True:
self.can_jump = False
else:
self.can_jump = True
return self.can_jump
#---Setup------------------------------------------#
#---constants-----#
global GRAVITY
GRAVITY = 0.25
#---Gamevariables-----#
can_jump = True
#---colour---#
bg_colour = (50,50,50)
white_colour = (255,255,255)
black_colour = (0,0,0)
#---res---#
resx = 900
resy = 675
sresx = resx - 50
sresy = resy - 50
#---start window-----#
clock = pygame.time.Clock()
screendisplay = pygame.display.set_mode((resx,resy))
screendisplay.fill(bg_colour)
pygame.display.set_caption("PlatformerGame1 started 09/02/2021")
screen = pygame.Surface((sresx,sresy))
screen.fill(white_colour)
#---startgame-----#
player = Player("assets\\pics\\TestPlayerFigure1_256512.png",100,100,32,64,10,30)
player_group = pygame.sprite.GroupSingle()
player_group.add(player)
platform1 = PlatformRect(100,550,100,10,black_colour,player_group)
platform_group = pygame.sprite.Group()
platform_group.add(platform1)
game_manager = GameManager(player_group,platform_group)
#---Loop--------------------------------------------#
while True:
#---events-----#
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
if event.key == pygame.K_SPACE:
if can_jump == True:
player.movement_y = 0
player.movement_y -= player.acceleration_y * GRAVITY
if event.key == pygame.K_a:
player.movement_x -= player.speed_x
if event.key == pygame.K_d:
player.movement_x += player.speed_x
if event.type == pygame.KEYUP:
if event.key == pygame.K_SPACE:
if player.movement_y < 0:
player.movement_y = 0
if event.key == pygame.K_a:
player.movement_x += player.speed_x
if event.key == pygame.K_d:
player.movement_x -= player.speed_x
#---background---#
screendisplay.blit(screen,(25,25))
screen.fill(white_colour)
#---running---#
game_manager.run_game()
if not game_manager.game_checking() == True and player.rect.bottom < sresy:
can_jump = False
else:
can_jump = True
#print(can_jump)
#---updating-----#
pygame.display.update()
clock.tick(60)
When the player is standing on the platform, the player does not collide with the platform and self.can_jump1 is set False. Test if the player is on the platform when the player does not collide with the platform:
self.can_jump1 = False
self.can_jump1 = self.rect.top == self.players.sprites()[0].rect.bottom
Method collision_check:
class PlatformRect(pygame.sprite.Sprite):
# [...]
def collision_check(self):
collide_list = pygame.sprite.spritecollide(self,self.players,False)
if collide_list:
collision_paddle = collide_list[0].rect
if abs(self.rect.top - collision_paddle.bottom) < 10:
collision_paddle.bottom = self.rect.top
player.movement_y = 0
self.can_jump1 = True
else:
self.can_jump1 = self.rect.top == self.players.sprites()[0].rect.bottom
GameManager.game_checking needs to check if the plyer collides with any platform:
class GameManager:
# [...]
def game_checking(self):
#---checking---#
self.can_jump = False
for sprite_platform in self.platform_group.sprites():
if sprite_platform.can_jump_check() == True:
self.can_jump = True
return self.can_jump
This can be simplified with the any function:
class PlatformRect(pygame.sprite.Sprite):
# [...]
def game_checking(self):
#---checking---#
self.can_jump = any(p.can_jump_check() for p in self.platform_group)
return self.can_jump

How to let objects move in different patterns

For my code, I would like the chickens (enemies) to move 4 different ways:
vertical, horizontal, diagonal and following the player (pig).
Each chicken should have its own movement and move independently. Only two chickens can go in diagonal.
I have only programmed their vertical and horizontal movements but there is a problem with them; sometimes, they all move horizontally, sometimes, vertically. Sometimes they don't move at all.
Here is my code:
def game_loop():
x_change = 0
y_change = 0
foodCounter = 0
Score = 0
list = ["Vertical","Vertical","Horizontal","Horizontal","Follow","Diagonal1","Diagonal2"]
baddies = []
item = 0
x = (display_width * 0.45)
y = (display_height * 0.8)
foodx = random.randrange(48, display_width - 48)
foody = random.randrange(54, display_height - 54)
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -8
if event.key == pygame.K_RIGHT:
x_change = 8
if event.key == pygame.K_UP:
y_change = -8
if event.key == pygame.K_DOWN:
y_change = 8
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
y_change = 0
if x > 705:
x_change = 0
x = 705
if x < -10:
x_change = 0
x = -10
if y < -15:
y_change = 0
y = -15
if y > 505:
y_change = 0
y = 505
x += x_change
y += y_change
gameDisplay.fill(white)
gameDisplay.blit(background,(-50,-50))
food = pygame.Rect(foodx, foody,48 , 54)
if foodCounter == 0:
gameDisplay.blit(foodImage, food)
player = pygame.Rect(x, y,108,105)
if player.colliderect(food):
foodCounter += -1
Score += 1
foodx = random.randrange(48, display_width - 48)
foody = random.randrange(54, display_height - 54)
foodCounter += 1
item = random.randint(1, len(list))
print(item)
if item == 1 or item == 2:
newchicken = {'rect':pygame.Rect(random.randint(0,display_width-45),0,45,63),
'surface':pygame.transform.scale(enemyImage,(45,63)),
'vertical': "vertical",
'down': "down"
}
item = 0
baddies.append(newchicken)
if item == 3 or item == 4:
newchicken = {'rect':pygame.Rect(0,random.randint(0,display_height-45),45,63),
'surface': pygame.transform.scale(enemyImage, (45,63)),
'horizontal': "horizontal",
'right': "right"
}
item = 0
baddies.append(newchicken)
if item == 6:
newchicken = {'rect':pygame.Rect(200,0,45,63),
'surface':pygame.transform.scale(enemyImage,(45,63)),
'diagonal1': "diagonal1"
}
if "Diagonal1" in list:
list.remove("Diagonal1")
item = 0
baddies.append(newchicken)
if len(list) == 7:
if item == 7:
newchicken = {'rect':pygame.Rect(100,600,45,63),
'surface':pygame.transform.scale(enemyImage,(45,63)),
'diagonal2': "diagonal2"
}
if "Diagonal2" in list:
list.remove("Diagonal2")
item = 0
baddies.append(newchicken)
if len(list) == 6:
if item == 6:
newchicken = {'rect':pygame.Rect(100,600,45,63),
'surface':pygame.transform.scale(enemyImage,(45,63)),
'diagonal2': "diagonal2"
}
if "Diagonal2" in list:
list.remove("Diagonal2")
item = 0
baddies.append(newchicken)
gameDisplay.blit(pigImage, player)
for b in baddies:
gameDisplay.blit(b['surface'],b['rect'])
for b in baddies:
if "vertical" in newchicken:
if "down" in newchicken:
if not b['rect'].bottom >= 600:
b['rect'].move_ip(0, 2)
if b['rect'].bottom >= 600 :
del newchicken['down']
newchicken["up"] = "up"
if "up" in newchicken:
if not b['rect'].top <= 0:
b['rect'].move_ip(0,-2)
if b['rect'].top <= 0:
del newchicken ['up']
newchicken["down"] = "down"
if "horizontal" in newchicken:
print ("horizontal")
if "right" in newchicken:
if not b['rect'].right >= 800:
b['rect'].move_ip(2,0)
if b['rect'].right >= 800:
del newchicken['right']
newchicken['left'] = "left"
if "left" in newchicken:
if not b['rect'].left <= 0:
b['rect'].move_ip(-2,0)
if b['rect'].left <= 0:
del newchicken ['left']
newchicken['right'] = "right"
pygame.display.update()
clock.tick(60)
game_loop()
Your code does not work because you always check for keys in newchicken when you iterate over baddies, while I guess you should check b instead.
But what you should do instead is to change your code in a way that seperates the different logical concerns of your game. Also, just use a class instead of a dict to group data and behaviour that belongs together.
Let's think a bit:
We have some kind of entity that basically consists of three things: an image, a position, and a behavior. You already know this, because you created these dicts:
newchicken = {'rect':pygame.Rect(100,600,45,63),
'surface':pygame.transform.scale(enemyImage,(45,63)),
'diagonal2': "diagonal2"
}
Let's tweak this a bit and use a Sprite (really, read the docs), which already has these things (more or less). Our class class could look like this (and don't tell me you don't want to use classes. That's stupid IMHO since you already use dozens of classes):
class Animal(pg.sprite.Sprite):
def __init__(self, color, pos, logic, *groups):
super().__init__(*groups)
self.image = pg.surface.Surface((40, 40))
self.image.fill(color)
self.rect = self.image.get_rect(topleft=pos)
self.logic = logic
self.direction = pg.Vector2((0, 0))
def update(self):
self.logic(self)
So, we have an image (which is just a plain rect so we have a working game at the end that everybody can copy/paste and run), a rect that stores the position, a mysterious logic argument that's a function (the "AI" of our animal) which will be called every tick, and a direction, which defines in which direction out animal will walk.
So, let's create the actual logic that will move out animals. We create three functions, one for vertical movement, one for horizontal movement, and one that will always walk towards the mouse cursor:
def move_vertical(animal):
if animal.direction.length() == 0:
animal.direction = pg.Vector2(5, 0)
animal.rect.move_ip(*animal.direction)
if not screen_rect.contains(animal.rect):
animal.direction *= -1
animal.rect.move_ip(animal.direction)
def move_horizontal(animal):
if animal.direction.length() == 0:
animal.direction = pg.Vector2(0, 5)
animal.rect.move_ip(*animal.direction)
if not screen_rect.contains(animal.rect):
animal.direction *= -1
animal.rect.move_ip(animal.direction)
def move_to_mouse(animal):
pos = pg.mouse.get_pos()
v = pg.Vector2(pos) - pg.Vector2(animal.rect.center)
if v.length() > 0:
v.normalize_ip()
v *= 5
animal.rect.move_ip(*v)
If we now want to create an Animal, we simply pass one of those functions to the constructor. No need for massive if/else blocks in your main loop (note how clean and simple it is in the end).
So, here's our final example. Note how we create four animals: two that move vertically, one that moves horizontally, and one that follows the mouse.
import pygame as pg
pg.init()
clock = pg.time.Clock()
running = True
screen = pg.display.set_mode((640, 480))
screen.fill((255, 255, 255))
screen_rect = screen.get_rect()
def move_vertical(animal):
if animal.direction.length() == 0:
animal.direction = pg.Vector2(5, 0)
animal.rect.move_ip(*animal.direction)
if not screen_rect.contains(animal.rect):
animal.direction *= -1
animal.rect.move_ip(animal.direction)
def move_horizontal(animal):
if animal.direction.length() == 0:
animal.direction = pg.Vector2(0, 5)
animal.rect.move_ip(*animal.direction)
if not screen_rect.contains(animal.rect):
animal.direction *= -1
animal.rect.move_ip(animal.direction)
def move_to_mouse(animal):
pos = pg.mouse.get_pos()
v = pg.Vector2(pos) - pg.Vector2(animal.rect.center)
if v.length() > 0:
v.normalize_ip()
v *= 5
animal.rect.move_ip(*v)
class Animal(pg.sprite.Sprite):
def __init__(self, color, pos, logic, *groups):
super().__init__(*groups)
self.image = pg.surface.Surface((40, 40))
self.image.fill(color)
self.rect = self.image.get_rect(topleft=pos)
self.logic = logic
self.direction = pg.Vector2((0, 0))
def update(self):
self.logic(self)
sprites = pg.sprite.Group()
Animal(pg.color.Color('yellow'), ( 10, 10), move_vertical, sprites)
Animal(pg.color.Color('red'), (200, 400), move_vertical, sprites)
Animal(pg.color.Color('orange'), (500, 100), move_horizontal, sprites)
Animal(pg.color.Color('brown'), (100, 200), move_to_mouse, sprites)
while running:
for e in pg.event.get():
if e.type == pg.QUIT:
running = False
sprites.update()
screen.fill((255, 255, 255))
sprites.draw(screen)
pg.display.update()
clock.tick(60)

Animation using PyGame, Pyganim and classes [duplicate]

This question already has answers here:
Why is my PyGame application not running at all?
(2 answers)
Why is nothing drawn in PyGame at all?
(2 answers)
How to run multiple while loops at a time in Pygame
(1 answer)
Pygame window freezes when it opens
(1 answer)
Faster version of 'pygame.event.get()'. Why are events being missed and why are the events delayed?
(1 answer)
Closed 2 years ago.
so my issue is with my player class, I'm still trying to understand classes.
So, basically, I'm using this player movement code from one of Pyganim's examples but I can't seem to implement it into this player class of mine, probably because I don't really understand classes.
For starters. My player never gets displayed now, every thing worked before I tried to add classes. I've probably just over complicated things trying to use this movement. My code is:
import pygame, sys, random, pyganim
from pygame.locals import *
class Scene(object):
screen = pygame.display.set_mode((800, 600))
class Intro(Scene):
def __init__(self):
self.c = (32, 32, 100)
def draw(self):
Scene.screen.fill(self.c)
def update(self):
# since scenes are classes, they have a state that we can modify
r,g,b = self.c
r += 1
g += 1
b += 2
if r > 255: r = 0
if g > 255: g = 0
if b > 255: b = 0
self.c = r, g, b
def handle(self, event):
# move to Menu-scene when space is pressed
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_m:
# returning a scene from handle or update changes the current scene
return Menu()
class Menu(Scene):
def draw(self):
# draw menu
Scene.screen.fill((200, 200, 100))
def update(self):
pass
# do something
def handle(self, event):
# handle menu input
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
return Game()
if event.key == pygame.K_b:
return Intro()
class Game(Scene):
def draw(self):
Scene.screen.fill((0,0,0))
bg = pygame.image.load('C:\\Users\\PAx\\Desktop\\stuff\\fort.png')
Scene.screen.blit(pygame.transform.scale(bg,(400,300)),(0,0))
def update(self):
pass
def handle(self, event):
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_m:
return meun()
class Player(pygame.sprite.Sprite):
def __init__(self):
self.UP = 'up'
self.DOWN = 'down'
self.LEFT = 'left'
self.RIGHT = 'right'
self.direction = DOWN # player starts off facing down (front)
# load the "standing" sprites (these are single images, not animations)
self.playerWidth, playerHeight = front_standing.get_size()
# creating the PygAnimation objects for walking/running in all directions
self.animTypes = 'back_run back_walk front_run front_walk left_run left_walk'.split()
self.animObjs = {}
for animType in animTypes:
self.imagesAndDurations = [('C:\\Users\PAx\\Desktop\\stuff\\gameimages\\crono_%s.%s.gif' % (animType, str(num).rjust(3, '0')), 1) for num in range(6)]
self.animObjs[animType] = pyganim.PygAnimation(imagesAndDurations)
# create the right-facing sprites by copying and flipping the left-facing sprites
self.animObjs['right_walk'] = animObjs['left_walk'].getCopy()
self.animObjs['right_walk'].flip(True, False)
self.animObjs['right_walk'].makeTransformsPermanent()
self.animObjs['right_run'] = animObjs['left_run'].getCopy()
self.animObjs['right_run'].flip(True, False)
self.animObjs['right_run'].makeTransformsPermanent()
# have the animation objects managed by a conductor.
# With the conductor, we can call play() and stop() on all the animtion
# objects at the same time, so that way they'll always be in sync with each
# other.
self.moveConductor = pyganim.PygConductor(animObjs)
self.x = 100
self.y = 100
self.WALKRATE = 10
self.RUNRATE = 18
self.pygame.sprite.Sprite.__init__(self) #init the Pygame sprite
#load all images
#load the player image
self.front_standing = pygame.image.load('C:\\Users\PAx\\Desktop\\stuff\\gameimages\\crono_front.gif')
self.back_standing = pygame.image.load('C:\\Users\PAx\\Desktop\\stuff\\gameimages\\crono_back.gif')
self.left_standing = pygame.image.load('C:\\Users\PAx\\Desktop\\stuff\\gameimages\\crono_left.gif')
self.right_standing = pygame.transform.flip(left_standing, True, False)
self.running = moveUp = moveDown = moveLeft = moveRight = False
def update(self):
for event in pygame.event.get():
if event.key == KEYDOWN:
if event.key in (K_LSHIFT, K_RSHIFT):
# player has started running
running = True
if event.key == K_UP:
moveUp = True
moveDown = False
if not moveLeft and not moveRight:
# only change the direction to up if the player wasn't moving left/right
direction = UP
elif event.key == K_DOWN:
moveDown = True
moveUp = False
if not moveLeft and not moveRight:
direction = DOWN
elif event.key == K_LEFT:
moveLeft = True
moveRight = False
if not moveUp and not moveDown:
direction = LEFT
elif event.key == K_RIGHT:
moveRight = True
moveLeft = False
if not moveUp and not moveDown:
direction = RIGHT
elif event.type == KEYUP:
if event.key in (K_LSHIFT, K_RSHIFT):
# player has stopped running
running = False
if event.key == K_UP:
moveUp = False
# if the player was moving in a sideways direction before, change the direction the player is facing.
if moveLeft:
direction = LEFT
if moveRight:
direction = RIGHT
elif event.key == K_DOWN:
moveDown = False
if moveLeft:
direction = LEFT
if moveRight:
direction = RIGHT
elif event.key == K_LEFT:
moveLeft = False
if moveUp:
direction = UP
if moveDown:
direction = DOWN
elif event.key == K_RIGHT:
moveRight = False
if moveUp:
direction = UP
if moveDown:
direction = DOWN
if moveUp or moveDown or moveLeft or moveRight:
# draw the correct walking/running sprite from the animation object
moveConductor.play() # calling play() while the animation objects are already playing is okay; in that case play() is a no-op
if running:
if direction == UP:
animObjs['back_run'].blit(screen, (x, y))
elif direction == DOWN:
animObjs['front_run'].blit(screen, (x, y))
elif direction == LEFT:
animObjs['left_run'].blit(screen, (x, y))
elif direction == RIGHT:
animObjs['right_run'].blit(screen, (x, y))
else:
# walking
if direction == UP:
animObjs['back_walk'].blit(screen, (x, y))
elif direction == DOWN:
animObjs['front_walk'].blit(screen, (x, y))
elif direction == LEFT:
animObjs['left_walk'].blit(screen, (x, y))
elif direction == RIGHT:
animObjs['right_walk'].blit(screen, (x, y))
# actually move the position of the player
if running:
rate = RUNRATE
else:
rate = WALKRATE
if moveUp:
y -= rate
if moveDown:
y += rate
if moveLeft:
x -= rate
if moveRight:
x += rate
else:
# standing still
moveConductor.stop() # calling stop() while the animation objects are already stopped is okay; in that case stop() is a no-op
if direction == UP:
Scene.screen.blit(back_standing, ((x, y)))
elif direction == DOWN:
Scene.screen.blit(front_standing, ((x, y)))
elif direction == LEFT:
screen.blit(left_standing, ((x, y)))
elif direction == RIGHT:
screen.blit(right_standing, (x, y))
# make sure the player does move off the screen
if x < 0:
x = 0
if x > WINDOWWIDTH - playerWidth:
x = WINDOWWIDTH - playerWidth
if y < 0:
y = 0
if y > WINDOWHEIGHT - playerHeight:
y = WINDOWHEIGHT - playerHeight
pygame.init()
clock = pygame.time.Clock()
Scene.screen = pygame.display.set_mode((800, 600))
scene = Intro()
while True:
if pygame.event.get(pygame.QUIT): break
for e in pygame.event.get():
scene = scene.handle(e) or scene
scene = scene.update() or scene
scene.draw()
Player.update(scene)
pygame.display.flip()
clock.tick(20)
This is the new and working code.
I changed handle and update and added a lot of self where needed. Wasn't sure how to add in draw() this could probably be cleaned up and written better but at least it works.
import pygame, sys, random, pyganim
from pygame.locals import *
class Scene(object):
screen = pygame.display.set_mode((800, 600))
class Intro(Scene):
def __init__(self):
self.c = (32, 32, 100)
def draw(self):
Scene.screen.fill(self.c)
def update(self):
# since scenes are classes, they have a state that we can modify
r,g,b = self.c
r += 1
g += 1
b += 2
if r > 255: r = 0
if g > 255: g = 0
if b > 255: b = 0
self.c = r, g, b
def handle(self, event):
# move to Menu-scene when space is pressed
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_m:
# returning a scene from handle or update changes the current scene
return Menu()
class Menu(Scene):
def draw(self):
# draw menu
Scene.screen.fill((200, 200, 100))
def update(self):
pass
# do something
def handle(self, event):
# handle menu input
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
return Game()
if event.key == pygame.K_b:
return Intro()
class Game(Scene):
def draw(self):
Scene.screen.fill((0,0,0))
bg = pygame.image.load('C:\\Users\\PAx\\Desktop\\stuff\\fort.png')
Scene.screen.blit(pygame.transform.scale(bg,(400,300)),(0,0))
def update(self):
pass
def handle(self, event):
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_m:
return Menu()
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.UP = 'up'
self.DOWN = 'down'
self.LEFT = 'left'
self.RIGHT = 'right'
self.front_standing = pygame.image.load('C:\\Users\PAx\\Desktop\\stuff\\gameimages\\crono_front.gif')
self.back_standing = pygame.image.load('C:\\Users\PAx\\Desktop\\stuff\\gameimages\\crono_back.gif')
self.left_standing = pygame.image.load('C:\\Users\PAx\\Desktop\\stuff\\gameimages\\crono_left.gif')
self.right_standing = pygame.transform.flip(self.left_standing, True, False)
self.running = self.moveUp = self.moveDown = self.moveLeft = self.moveRight = False
self.direction = self.DOWN # player starts off facing down (front)
# load the "standing" sprites (these are single images, not animations)
self.playerWidth, self.playerHeight = self.front_standing.get_size()
# creating the PygAnimation objects for walking/running in all directions
self.animTypes = 'back_run back_walk front_run front_walk left_run left_walk'.split()
self.animObjs = {}
for self.animType in self.animTypes:
self.imagesAndDurations = [('C:\\Users\PAx\\Desktop\\stuff\\gameimages\\crono_%s.%s.gif' % (self.animType, str(num).rjust(3, '0')), 1) for num in range(6)]
self.animObjs[self.animType] = pyganim.PygAnimation(self.imagesAndDurations)
# create the right-facing sprites by copying and flipping the left-facing sprites
self.animObjs['right_walk'] = self.animObjs['left_walk'].getCopy()
self.animObjs['right_walk'].flip(True, False)
self.animObjs['right_walk'].makeTransformsPermanent()
self.animObjs['right_run'] = self.animObjs['left_run'].getCopy()
self.animObjs['right_run'].flip(True, False)
self.animObjs['right_run'].makeTransformsPermanent()
# have the animation objects managed by a conductor.
# With the conductor, we can call play() and stop() on all the animtion
# objects at the same time, so that way they'll always be in sync with each
# other.
self.moveConductor = pyganim.PygConductor(self.animObjs)
self.x = 100
self.y = 100
self.WALKRATE = 10
self.RUNRATE = 18
self.WINDOWWIDTH = 640
self.WINDOWHEIGHT = 480
#load all images
#load the player image
def update(self, scene):
if self.moveUp or self.moveDown or self.moveLeft or self.moveRight:
# draw the correct walking/running sprite from the animation object
self.moveConductor.play() # calling play() while the animation objects are already playing is okay; in that case play() is a no-op
if self.running:
if self.direction == self.UP:
self.animObjs['back_run'].blit(Scene.screen, (self.x, self.y))
elif self.direction == self.DOWN:
self.animObjs['front_run'].blit(Scene.screen, (self.x, self.y))
elif self.direction == self.LEFT:
self.animObjs['left_run'].blit(Scene.screen, (self.x, self.y))
elif self.direction == self.RIGHT:
self.animObjs['right_run'].blit(Scene.screen, (self.x, self.y))
else:
# walking
if self.direction == self.UP:
self.animObjs['back_walk'].blit(Scene.screen, (self.x, self.y))
elif self.direction == self.DOWN:
self.animObjs['front_walk'].blit(Scene.screen, (self.x, self.y))
elif self.direction == self.LEFT:
self.animObjs['left_walk'].blit(Scene.screen, (self.x, self.y))
elif self.direction == self.RIGHT:
self.animObjs['right_walk'].blit(Scene.screen, (self.x, self.y))
# actually move the position of the player
if self.running:
rate = self.RUNRATE
else:
rate = self.WALKRATE
if self.moveUp:
self.y -= rate
if self.moveDown:
self.y += rate
if self.moveLeft:
self.x -= rate
if self.moveRight:
self.x += rate
else:
# standing still
self.moveConductor.stop() # calling stop() while the animation objects are already stopped is okay; in that case stop() is a no-op
if self.direction == self.UP:
Scene.screen.blit(self.back_standing, ((self.x, self.y)))
elif self.direction == self.DOWN:
Scene.screen.blit(self.front_standing, ((self.x, self.y)))
elif self.direction == self.LEFT:
Scene.screen.blit(self.left_standing, ((self.x, self.y)))
elif self.direction == self.RIGHT:
Scene.screen.blit(self.right_standing, (self.x, self.y))
# make sure the player does move off the screen
if self.x < 0:
self.x = 0
if self.x > self.WINDOWWIDTH - self.playerWidth:
self.x = self.WINDOWWIDTH - self.playerWidth
if self.y < 0:
self.y = 0
if self.y > self.WINDOWHEIGHT - self.playerHeight:
self.y = self.WINDOWHEIGHT - self.playerHeight
def handle(self, event):
if event.type == KEYDOWN:
if event.key in (K_LSHIFT, K_RSHIFT):
# player has started running
running = True
if event.key == K_UP:
self.moveUp = True
self.moveDown = False
if not self.moveLeft and not self.moveRight:
# only change the direction to up if the player wasn't moving left/right
self.direction = self.UP
elif event.key == K_DOWN:
self.moveDown = True
self.moveUp = False
if not self.moveLeft and not self.moveRight:
self.direction = self.DOWN
elif event.key == K_LEFT:
self.moveLeft = True
self.moveRight = False
if not self.moveUp and not self.moveDown:
self.direction = self.LEFT
elif event.key == K_RIGHT:
self.moveRight = True
self.moveLeft = False
if not self.moveUp and not self.moveDown:
self.direction = self.RIGHT
elif event.type == KEYUP:
if event.key in (K_LSHIFT, K_RSHIFT):
# player has stopped running
self.running = False
if event.key == K_UP:
self.moveUp = False
# if the player was moving in a sideways direction before, change the direction the player is facing.
if self.moveLeft:
self.direction = self.LEFT
if self.moveRight:
self.direction = self.RIGHT
elif event.key == K_DOWN:
self.moveDown = False
if self.moveLeft:
self.direction = self.LEFT
if self.moveRight:
self.direction = self.RIGHT
elif event.key == K_LEFT:
self.moveLeft = False
if self.moveUp:
self.direction = self.UP
if self.moveDown:
self.direction = self.DOWN
elif event.key == K_RIGHT:
self.moveRight = False
if self.moveUp:
self.direction = self.UP
if self.moveDown:
self.direction = self.DOWN
pygame.init()
clock = pygame.time.Clock()
Scene.screen = pygame.display.set_mode((800, 600))
player = Player()
scene = Intro()
while True:
if pygame.event.get(pygame.QUIT): break
for e in pygame.event.get():
scene = scene.handle(e) or scene
player.handle(e) or scene
scene = scene.update() or scene
scene.draw()
player.update(scene)
pygame.display.flip()
clock.tick(20)

Increasing Pygame Image size after collision?

So I'm just learning how to work with classes and getting them to work between each different class. I'm trying to design a game where the user moves around and picks up food and each time the user picks up a piece of food the size of the character increases. I've done something similar before but now that there are classes involved I seem to have a hard time finding which class this should be part of. I added within the sprite update method that if it collides with a cherry then the size of the player should increase by 5 pixels each time. using the code :
self.Player.surface = pygame.transform.scale(self.Player.surface, (pwidth+5, pheight+5))
self.rect = self.Player.surface.get_rect()
Each time the game runs the player size doesn't change and for some reason the game no longer ends after the player has eaten a certain amount of cherries so I was just wondering if I was using a wrong method of changing the size of the player perhaps there may be an easier way to do so? Heres the rest of the code incase it helps at all.
import pygame, glob, random, time
from pygame.locals import *
from LabelClass import *
# CONSTANTS
WIDTH = 400 # Window width
HEIGHT = 400 # Window height
BLACK = (0,0,0) # Colors
WHITE = (255,255,255)
BACKGR = BLACK # Background Color
FOREGR = WHITE # Foreground Color
FPS = 40 # Frames per second
pwidth = 40
pheight = 40
class Food:
def __init__(self,screen,centerx,centery):
self.screen = screen
self.surface = pygame.image.load('cherry.png')
self.rect = self.surface.get_rect()
self.rect.centerx = centerx
self.rect.centery = centery
def draw(self):
self.screen.blit(self.surface,self.rect)
#pygame.display.update([self.rect])
class Player:
def __init__(self, screen, centerx,
centery, speed, backcolor):
self.surface = pygame.image.load('player.png')
self.rect = self.surface.get_rect()
self.rect.centerx = centerx
self.rect.centery = centery
self.speed = speed
self.screen = screen
self.backcolor = backcolor
self.dir = ''
def draw(self):
self.screen.blit(self.surface,self.rect)
#pygame.display.update([self.rect])
def move(self):
if self.dir != '':
if self.dir == 'd' and self.rect.bottom < HEIGHT:
self.rect.top += self.speed
if self.dir == 'u' and self.rect.top > 0:
self.rect.top -= self.speed
if self.dir == 'l' and self.rect.left > 0:
self.rect.left -= self.speed
if self.dir == 'r' and self.rect.right < WIDTH:
self.rect.right += self.speed
def jump(self,top,left):
self.rect.top = top
self.rect.left = left
class SpritesGame:
def __init__(self,screen):
self.screen = screen
screen.fill(BLACK)
pygame.display.update()
music_file = getRandomMusic()
pygame.mixer.music.load(music_file)
pygame.mixer.music.play(-1,0.0)
self.music = True
self.Foods = [ ]
self.Eaten = 0
for i in range(20):
self.Foods.append(
Food(self.screen,
WIDTH*random.randint(1,9)//10,
HEIGHT*random.randint(1,9)//10))
for f in self.Foods:
f.draw()
self.Player = Player(screen,WIDTH//2,HEIGHT//2,6,BLACK)
self.PickUpSound = pygame.mixer.Sound('pickup.wav')
self.PlaySound = True
self.startTime = time.clock()
self.endTime = -1
self.Won = False
def update(self):
self.screen.fill(BLACK)
pickedUp = False
for f in self.Foods[:]:
if self.Player.rect.colliderect(f.rect):
self.Foods.remove(f)
self.Foods.append(Food(self.screen,WIDTH*random.randint(1,9)//10,HEIGHT*random.randint(1,9)//10))
pickedUp = True
self.Eaten += 1
self.Player.surface = pygame.transform.scale(self.Player.surface, (pwidth+5, pheight+5))
self.rect = self.Player.surface.get_rect()
#self.rect.center = center
print self.Eaten
if pickedUp and self.PlaySound:
self.PickUpSound.play()
for f in self.Foods:
f.draw()
if self.Eaten == 40:
self.Won = True
self.endTime = time.clock()
self.Player.move()
self.Player.draw()
pygame.display.update()
def toggleMusic(self):
self.music = not self.music
if self.music:
pygame.mixer.music.play(-1,0.0)
else:
pygame.mixer.music.stop()
def run(self):
stop = False
while not stop:
for event in pygame.event.get():
if event.type == QUIT:
stop = True
if event.type == KEYDOWN: # Keeps moving as long as key down
if event.key == K_LEFT or event.key == ord('a'):
self.Player.dir = 'l'
if event.key == K_RIGHT or event.key == ord('d'):
self.Player.dir = 'r'
if event.key == K_UP or event.key == ord('w'):
self.Player.dir = 'u'
if event.key == K_DOWN or event.key == ord('s'):
self.Player.dir = 'd'
if event.type == KEYUP:
if event.key == ord('q'):
stop = True
if event.key == K_ESCAPE:
stop = True
if event.key == K_LEFT or event.key == ord('a'): # End repetition.
self.Player.dir = ''
if event.key == K_RIGHT or event.key == ord('d'):
self.Player.dir = ''
if event.key == K_UP or event.key == ord('w'):
self.Player.dir = ''
if event.key == K_DOWN or event.key == ord('s'):
self.Player.dir = ''
if event.key == ord('x'):
top = random.randint(0,
HEIGHT - self.Player.rect.height)
left = random.randint(0,
WIDTH - self.Player.rect.width)
self.Player.jump(top,left)
if event.key == ord('m'):
self.toggleMusic()
if event.key == ord('p'):
self.PlaySound = not self.PlaySound
mainClock.tick(FPS)
self.update()
if self.Won:
stop = True # END OF WHILE
if self.Won:
self.screen.fill(BLACK)
pygame.display.update()
msg = (str((int(self.endTime)
-int(self.startTime)))
+" seconds to finish. Hit Q.")
L2 = Label(display,WIDTH//2,HEIGHT*7//8,26,msg,WHITE,BLACK)
L2.draw()
stop = False
while not stop:
for event in pygame.event.get():
if event.type == KEYUP:
if event.key == ord('q'):
stop = True
pygame.event.get()
pygame.mixer.music.stop()
def getRandomMusic():
mfiles = glob.glob("*.wav")
mfiles.append(glob.glob("*.mid"))
r = random.randint(0,len(mfiles)-1)
return mfiles[r]
def OpeningScreen(screen):
screen.fill(BLACK)
pygame.display.update()
L1 = Label(display,WIDTH//2,HEIGHT*7//8,26,"Hit Q to Quit, P to Play.",WHITE, BLACK)
L1.draw()
# Properly initiate pygame
pygame.init()
# pygame.key.set_repeat(INT,INT)
# Set the clock up
mainClock = pygame.time.Clock()
# Initialize Display
display = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption('Sprites and Sounds V06')
OpeningScreen(display)
stop = False
while not stop:
for event in pygame.event.get():
if event.type == QUIT:
stop = True
if event.type == KEYUP:
if event.key == ord('p'):
game = SpritesGame(display)
game.run()
OpeningScreen(display)
if event.key == ord('q'):
stop = True
pygame.quit()
Surface.get_rect() will always return a rect starting at (0,0), and you also are modifying SpritesGame.rect. I think you should change
self.rect = self.Player.surface.get_rect()
to
self.Player.rect.inflate_ip(5, 5)

Categories

Resources