spritecollide() not functioning as expected - python

I am in the process of making a 'main character' which jumps around and can jump onto boxes etc using pygame. I have created the Player class, the Level class and the Box class. The spritecollide function never returns true, and I am unsure where I am going wrong.
I used spritecollideany and groupcollide to see if that helps (it didn't)
I have checked as best I can, and as far as I can tell the boxes are making their way into Level.box_list as a sprite Group, and both the boxes and the players are Sprites.
I have thoroughly read the documentation and feel as though there must be some key concept I am missing or misusing.
I greatly appreciate any help that you are able to offer. Thanks!
movementprototype.py
import random, pygame, sys
import math
from pygame.locals import *
from levelprototype import *
FPS = 60 # frames per second, the general speed of the program
WINDOWWIDTH = 640 # size of window's width in pixels
WINDOWHEIGHT = 480 # size of windows' height in pixels
# R G B
GRAY = (100, 100, 100)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = ( 0, 255, 0)
BLUE = ( 0, 0, 255)
YELLOW = (255, 255, 0)
ORANGE = (255, 128, 0)
BLACK = ( 0, 0, 0)
BGCOLOR = WHITE
def main():
#set up all relevant variables
global FPSCLOCK, DISPLAYSURF, player, box_list
pygame.init()
FPSCLOCK = pygame.time.Clock()
#the length, in ms, of one frame
tick = 1000/FPS
#create window
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
mousex = 0 # used to store x coordinate of mouse event
mousey = 0 # used to store y coordinate of mouse event
pygame.display.set_caption('Movement test environment')
#create the player object using Player() class, add to all_sprites group.
all_sprites = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
#create the level object
level = Level()
while True: #main game loop
#fill with background colour
DISPLAYSURF.fill(BGCOLOR)
# Update items in the level
level.update()
level.draw(DISPLAYSURF)
#call the sprite update and draw methods.
all_sprites.update()
#check if the player has clicked the X or pressed escape.
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
[irrelevant code]
#update the screen
pygame.display.update()
FPSCLOCK.tick(FPS)
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
#.draw() called in main() requires that each Sprite have a Surface.image
#and a Surface.rect.
self.image = pygame.Surface((20,50))
self.image.fill(GREEN)
self.rect = self.image.get_rect()
#attributes
self.velX = 0
self.velY = 0
self.x = 0
self.y = 0
self.gravity = 0.6
self.maxVelocity = 5
self.xResistance = 0.5
self.isJump = 0
self.isDash = 0
def update(self):
#check which keys are pressed and add velocity.
keys = pygame.key.get_pressed()
if (keys[K_d]) and self.velX < self.maxVelocity:
self.velX += 2.5
if (keys[K_a]) and self.velX > -self.maxVelocity:
self.velX -= 2.5
if (keys[K_w]) and self.isJump == 0:
self.velY -= 10
self.isJump = 1
if (keys[K_SPACE]) and self.isDash == 0:
#at the moment, can only dash once. add timer reset.
self.isDash = 1
if self.velX > 0:
self.x += 20
else:
self.x -= 20
#add gravity
self.velY += self.gravity
#add X resistance
if self.velX > 0.05:
self.velX -= self.xResistance
elif self.velX < -0.05:
self.velX += self.xResistance
#if velocity is really close to 0, make it 0, to stop xResistance moving it the other way.
if self.velX < 0.15 and self.velX > -0.15:
self.velX = 0
self.checkCollision()
#update position with calculated velocity
self.x += self.velX
self.y += self.velY
#call the draw function, below, to blit the sprite onto screen.
self.draw(DISPLAYSURF)
def checkCollision(self):
level = Level().box_list
for collide in pygame.sprite.spritecollide(self, level, False):
print("Collision")
#no matter what I put here, a collision never seems to be identified!!
def draw(self, DISPLAYSURF):
DISPLAYSURF.blit(self.image, (self.x, self.y))
if __name__ == '__main__':
main()
levelprototype.py
import pygame, sys
from pygame.locals import*
GREEN = ( 0, 255, 0)
BLUE = ( 0, 0, 255)
BLACK = ( 0, 0, 0)
class Box(pygame.sprite.Sprite):
""" Box the user can jump on """
def __init__(self, width, height):
super().__init__()
self.image = pygame.Surface([width, height])
self.image.fill(BLACK)
self.rect = self.image.get_rect()
class Level():
#create the box_list as a Class attribute that exists for all instances.
box_list = pygame.sprite.Group()
def __init__(self):
# Background image
self.background = None
# Array with width, height, x, and y of platform
level = [[210, 70, 500, 100],
[210, 70, 200, 400],
[210, 70, 600, 300],
]
# Go through the array above and add platforms
if len(Level.box_list) < 3:
for platform in level:
block = Box(platform[0], platform[1])
block.rect.x = platform[2]
block.rect.y = platform[3]
Level.box_list.add(block)
# Update everything on this level
def update(self):
""" Update everything in this level."""
# Level.box_list.update()
def draw(self, DISPLAYSURF):
""" Draw everything on this level. """
# Draw all the sprite lists that we have
Level.box_list.draw(DISPLAYSURF)

When checking for collisions, pygame.sprite.spritecollide will check whether the Sprite's rects are intersecting. You're not updating the player's rect attribute, so its position will be at (0, 0). Make sure they are synchronized:
# update position with calculated velocity
self.x += self.velX
self.y += self.velY
self.rect.x = self.x
self.rect.y = self.y

Related

How to move a surface in pygame

I'm making a game in pygame and I'm trying to move the self.jetRect, which is the rectangular area of the Surface (jetSurface), but when I try updating the coordinates of the rectangle, I get a TypeError: 'tuple' object is not callable. I think this is related to the fact that a tuple is immutable, but I don't know how to fix this.
import pygame
pygame.init()
clock = pygame.time.Clock()
# Screen setup
screen_width = 600
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Jet Fighter Game")
# Colors
black = (0, 0, 0)
white = (255, 255, 255)
grey = (100, 100, 100)
# Classes
class PLAYER1:
def __init__(self):
self.jetSurface = pygame.image.load("player1 - blackJet.png")
self.x = 100
self.y = 100
self.speed = 5
self.jetRect = self.jetSurface.get_rect(center = (self.x, self.y))
self.angle = 0
self.rotatedJet = self.jetSurface
def rotateJet(self, surface, angle):
key = pygame.key.get_pressed()
if key[pygame.K_a]:
self.angle += 10
self.rotatedJet = pygame.transform.rotozoom(surface, angle, 1)
self.jetRect = self.rotatedJet.get_rect(center=(self.x, self.y))
if key[pygame.K_d]:
self.angle -= 10
self.rotatedJet = pygame.transform.rotozoom(surface, angle, 1)
self.jetRect = self.rotatedJet.get_rect(center=(self.x, self.y))
if self.angle >= 360:
self.angle = 0
screen.blit(self.rotatedJet, self.jetRect)
def moveJet(self):
key = pygame.key.get_pressed()
if key[pygame.K_w]:
self.y -= self.speed
self.jetRect.center(self.x, self.y)
class PLAYER2:
pass
class BULLET:
pass
class MAIN:
def __init__(self):
self.player1 = PLAYER1()
def rotateJets(self):
self.player1.rotateJet(self.player1.jetSurface, self.player1.angle)
def moveJets(self):
self.player1.moveJet()
main = MAIN()
# Main loop
run = True
while run:
# Checking for events
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# Drawing on screen
screen.fill(grey)
# Movement and Collisions
main.rotateJets()
main.moveJets()
pygame.display.flip()
clock.tick(60)
pygame.quit()
Its a typo. self.jetRect.center is a tuple of (self.x, self.y), so when you do
self.jetRect.center(self.x, self.y), you are doing (self.x, self.y)(self.x, self.y), hence the error message of calling a tuple.
I think you meant to assign the tuple like self.jetRect.center = (self.x, self.y)

Get a specific sprite from a group in Pygame

I am trying to find a certain sprite in a collision group. In this case, My code checks every platform to see if the player is touching it. If the player is touching the platform, I want the player's bottom y to become the platform's (that the player is touching) top y. I do not know how to grab a certain platform, and edit the attributes of that one. How would I edit my code to make this work?
import pygame
import random
WIDTH = 500
HEIGHT = 400
FPS = 30
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
playerImage = "blockBandit/BlockBandit.png"
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((50, 50))
self.image = pygame.image.load(playerImage).convert()
self.rect = self.image.get_rect()
self.rect.center = (WIDTH / 2, HEIGHT / 2)
self.vx = 0
self.vy = 0
class Platform(pygame.sprite.Sprite):
def __init__(self, x, y, w, h):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((w, h))
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Block Bandit")
clock = pygame.time.Clock()
allPlatforms = pygame.sprite.Group()
all_sprites = pygame.sprite.Group()
player = Player()
p1 = Platform(0, HEIGHT - 40, WIDTH, 40)
all_sprites.add(p1)
allPlatforms.add(p1)
all_sprites.add(player)
def moveCharacter(object):
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
object.vx += -2
if keys[pygame.K_RIGHT]:
object.vx += 2
if keys[pygame.K_UP]:
object.vy -= 12
pygame.quit()
object.vx = object.vx * 0.9
if abs(object.vx) < 1:
object.vx = 0
if abs(object.vx) > 10:
if object.vx < 0:
object.vx = -10
else:
object.vx = 10
object.vy = object.vy + 1
object.rect.x += object.vx
object.rect.y += object.vy
hits = pygame.sprite.spritecollide(object, allPlatforms, False)
if hits:
# object.rect.y = hits[0].rect.midbottom
object.rect.y -= 1
object.vy = 0
if object.rect.bottom < allPlatforms.top:
object.rect.y = allPlatforms.top
print(object.rect.midbottom)
running = True
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
moveCharacter(player)
# Update State
all_sprites.update()
# Render
screen.fill(BLACK)
all_sprites.draw(screen)
# screen.blit(player.icon, (20, 40))
pygame.display.flip()
pygame.quit()
hits is a list of the colliding platform sprites, so you can iterate over it with a for loop and set the object.rect.bottom to the platform.rect.top.
hits = pygame.sprite.spritecollide(object, allPlatforms, False)
for platform in hits:
object.vy = 0
object.rect.bottom = platform.rect.top

Appending a csv file in python

So I am making a space invaders game in python, the game will take the score the player has achieved and will add it to a csv file. My code for the csv file is:
col = pygame.sprite.spritecollideany(player, mobs)
if col:
with open("rec_Scores.csv", "a", newline" ") as f:
w = csv.writer(f, dilimiter = ",")
for i in range(len(score)):
w.writerow(name[i], score[i]])
crashed = True
However, I get the error:
File "C:\Users\Harry\Desktop\Desktop\Computing Project\Galaxian.py", line 162
with open("rec_Scores.csv", "a", newline" ") as f:
^
SyntaxError: invalid syntax
I am really stuck with this problem and I have no idea how to solve it. Any help would be much appreciated. Here is my code because I am probably going about this in a completely idiotic way:
import pygame
import random
import sys
import csv
# --- constants --- (UPPER_CASE names)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
ORANGE = (255, 255, 0)
YELLOW = (0, 255, 255)
DISPLAY_WIDTH = 720
DISPLAY_HEIGHT = 720 # sets res for the screen
FPS = 60
# --- classes --- (CamelCase names)
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("images\\user1.gif").convert()
self.image = pygame.transform.scale(self.image, (50, 50))
self.rect = self.image.get_rect()
self.speed_x = 0
def update(self):
self.speed_x = 0
keystate = pygame.key.get_pressed()
if keystate[pygame.K_LEFT]:
self.speed_x = -10
if keystate[pygame.K_RIGHT]:
self.speed_x = 10
self.rect.x += self.speed_x
if self.rect.right > DISPLAY_WIDTH:
self.rect.right = DISPLAY_WIDTH
if self.rect.left < 0:
self.rect.left = 0
def shoot(self):
bullet = Bullet(self.rect.centerx, self.rect.top)
all_sprites.add(bullet)
bullet_group.add(bullet)
class Mob(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.speed_y = random.randrange(5, 11)
self.image = pygame.image.load("images\\enemy1.gif").convert()
self.image = pygame.transform.scale(self.image, (50, 50))
self.rect = self.image.get_rect()
self.speed_x = 0
self.rect.x = random.randrange(0, DISPLAY_WIDTH - self.rect.width)
self.rect.y = random.randrange(-500, -40)
self.speedy = random.randrange(5, 11)
def update(self):
self.rect.y += self.speedy
if self.rect.top > DISPLAY_HEIGHT + 10:
self.rect.x = random.randrange(0, DISPLAY_WIDTH - self.rect.width)
self.rect.y = random.randrange(-500, -40)
class Bullet(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("images\\laser1.gif").convert() # sets the laser to be the image laser1.gif
self.image = pygame.transform.scale(self.image, (15, 25)) # trasforms the size to fit the screen
self.rect = self.image.get_rect() # sets hit box up, will fit around the image
self.rect.bottom = y
self.rect.centerx = x
self.speed_y = -30
def update(self):
self.rect.y += self.speed_y
if self.rect.bottom < 0:
self.kill()
# --- functions --- (lower_case names)
# --- main --- (lower_case names)
score =0
name = raw_input("Enter your name: ")
# - init -
pygame.init()
pygame.mixer.init()
display = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))
display_rect = display.get_rect()
# - objects and groups -
all_sprites = pygame.sprite.Group() # creates class that all sprites will be in
mobs = pygame.sprite.Group() # creates class that all mobs will be stored in
bullet_group = pygame.sprite.Group() # creates class that all bullets will be stored in
player = Player() # assigns the player variable to the player class
player.rect.center = ((DISPLAY_WIDTH / 2), DISPLAY_HEIGHT / 1.2) # sets the player to spawn at the bottom and in the middle of the screen
all_sprites.add(player) # adds player to the all_sprites group
for z in range(12): # spawns 13 enemies
mob = Mob()
mobs.add(mob)
all_sprites.add(mob)
# - other -
pygame.mixer.music.load("audio\\soundtrack.mp3")
pygame.mixer.music.play(-1) # sets music to play in an infinite loop
pygame.mixer.music.set_volume(0.2)
# - mainloop -
crashed = False
clock = pygame.time.Clock()
while not crashed:
# - events -
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LCTRL:
player.shoot()
print(event)
# - updates (without draws) -
all_sprites.update() # updates sprite positions without drawing them onto the screen
# - draws (without updates) -
background = pygame.image.load("images\\background.jpg") # assigns the picture to a variable called background
background = pygame.transform.scale(background, (DISPLAY_WIDTH, DISPLAY_HEIGHT)) # streches the picture to fit the screen
display.blit(background, (0, 0)) # displays the background image
all_sprites.draw(display) # draws all sprites onto the screen
font = pygame.font.SysFont("monospace", 15)
text = font.render("Score: " + str(score), True, BLACK)
display.blit(text, (0, 0))
pygame.display.update() # updates display
# - Checks for a hit -
col = pygame.sprite.groupcollide(mobs, bullet_group, True, True)
if col: # if col = true then
mob = Mob() # spawns new mob
mobs.add(mob)
all_sprites.add(mob)
score += 10
# - checks for a collision -
col = pygame.sprite.spritecollideany(player, mobs)
if col:
with open("rec_Scores.csv", "a", newline" ") as f:
w = csv.writer(f, dilimiter = ",")
for i in range(len(score)):
w.writerow(name[i], score[i]])
crashed = True
# - FPS -
clock.tick(FPS) # built in function to make the program stay below specified frame per second
# - end -
pygame.quit()
Thank you in advance for any help.
with open("rec_Scores.csv", "a", newline" ") as f:
Should be:
with open("rec_Scores.csv", "a") as f:
delimiter is misspelled as dilimiter but is unneeded anyway.
The f.writerow arguments are not quite what you want here.
Next time try making a working reproducer that has all bits of code needed to work including import statements.
Actual working version:
import csv
name=['foo','bar']
score=[12345,54321]
with open("rec_Scores.csv", "a") as f:
w = csv.writer(f)
for i in range(len(score)):
w.writerow([str(name[i]),str(score[i])])

Pygame: Collision of two images

I'm working on my school project for which im designing a 2D game.
I have 3 images, one is the player and the other 2 are instances (coffee and computer). What i want to do is, when the player image collides with one of the 2 instances i want the program to print something.
I'm unsure if image collision is possible. But i know rect collision is possible. However, after several failed attempts, i can't manage to make my images rects. Somebody please help me. Here is my source code:
import pygame
import os
black=(0,0,0)
white=(255,255,255)
blue=(0,0,255)
class Player(object):
def __init__(self):
self.image = pygame.image.load("player1.png")
self.image2 = pygame.transform.flip(self.image, True, False)
self.coffee=pygame.image.load("coffee.png")
self.computer=pygame.image.load("computer.png")
self.flipped = False
self.x = 0
self.y = 0
def handle_keys(self):
""" Movement keys """
key = pygame.key.get_pressed()
dist = 5
if key[pygame.K_DOWN]:
self.y += dist
elif key[pygame.K_UP]:
self.y -= dist
if key[pygame.K_RIGHT]:
self.x += dist
self.flipped = False
elif key[pygame.K_LEFT]:
self.x -= dist
self.flipped = True
def draw(self, surface):
if self.flipped:
image = self.image2
else:
im = self.image
for x in range(0, 810, 10):
pygame.draw.rect(screen, black, [x, 0, 10, 10])
pygame.draw.rect(screen, black, [x, 610, 10, 10])
for x in range(0, 610, 10):
pygame.draw.rect(screen, black, [0, x, 10, 10])
pygame.draw.rect(screen, black, [810, x, 10, 10])
surface.blit(self.coffee, (725,500))
surface.blit(self.computer,(15,500))
surface.blit(im, (self.x, self.y))
pygame.init()
screen = pygame.display.set_mode((800, 600))#creates the screen
player = Player()
clock = pygame.time.Clock()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit() # quit the screen
running = False
player.handle_keys() # movement keys
screen.fill((255,255,255)) # fill the screen with white
player.draw(screen) # draw the player to the screen
pygame.display.update() # update the screen
clock.tick(60) # Limits Frames Per Second to 60 or less
Use pygame.Rect() to keep image size and position.
Image (or rather pygame.Surface()) has function get_rect() which returns pygame.Rect() with image size (and position).
self.rect = self.image.get_rect()
Now you can set start position ie. (0, 0)
self.rect.x = 0
self.rect.y = 0
# or
self.rect.topleft = (0, 0)
# or
self.rect = self.image.get_rect(x=0, y=0)
(Rect use left top corner as (x,y)).
Use it to change position
self.rect.x += dist
and to draw image
surface.blit(self.image, self.rect)
and then you can test collision
if self.rect.colliderect(self.rect_coffe):
BTW: and now class Player looks almost like pygame.sprite.Sprite :)

Pygame Sprite can jump but can't walk

I've been working through this online tutorial on Pygame (Python Version 3.3.1), and have come to a point where my sprite can jump, but can walk only a few pixels in either direction. I'd really like to move forward with this code as I like how it is structured (not a lot of code in the Main method). Can anyone spot what might be causing my sprite to get stuck?
import pygame
# Define some colors
black = ( 0, 0, 0)
white = ( 255, 255, 255)
green = ( 0, 255, 0)
red = ( 255, 0, 0)
class Player(pygame.sprite.Sprite):
def __init__(self, *groups):
super(Player, self).__init__(groups)
self.image = pygame.image.load('Images\player1.png')
self.rect = pygame.rect.Rect((50, 650), self.image.get_size())
self.resting = False
self.dy = 0 #dy represents change in y velocity
def update(self, dt, game):
last = self.rect.copy()
key = pygame.key.get_pressed()
if key[pygame.K_LEFT]:
self.rect.x -= 300 * dt
if key[pygame.K_RIGHT]:
self.rect.x += 300 * dt
#if key[pygame.K_UP]:
# self.rect.y -= 300 * dt
#if key[pygame.K_DOWN]:
# self.rect.y += 300 * dt
if self.resting and key[pygame.K_SPACE]:
self.dy = -500 #If space bar is pressed, increase velocity.
self.dy = min(400, self.dy + 40) #Speed capped at 400. Gravity set at 40.
self.rect.y += self.dy * dt
new = self.rect
self.resting = False
for cell in pygame.sprite.spritecollide(self, game.walls, False):
#self.rect = last
cell = cell.rect
if last.right <= cell.left and new.right > cell.left:
new.right = cell.left
if last.left >= cell.right and new.left < cell.right:
new.left = cell.right
if last.bottom <= cell.top and new.bottom > cell.top:
#if you hit something while jumping, stop.
self.resting = True
new.bottom = cell.top
self.dy = 0
if last.top >= cell.bottom and new.top < cell.bottom:
new.top = cell.bottom
self.dy = 0 #If you hit the floor while jumping, stop
class Game(object):
def main(self, screen):
clock = pygame.time.Clock()
dt = clock.tick(30)
#image = pygame.image.load('Images\player1.gif')
background = pygame.image.load('Images\_rec_bg.png')
sprites = pygame.sprite.Group()
self.player = Player(sprites)
self.walls = pygame.sprite.Group()
block = pygame.image.load('Images\dia_tile.png')
for x in range(0, 800, 20):
for y in range(0, 800, 20):
if x in (0, 800-20) or y in (0, 800-20):
wall = pygame.sprite.Sprite(self.walls)
wall.image = block
wall.rect = pygame.rect.Rect((x, y), block.get_size())
sprites.add(self.walls)
running = True
while running:
clock.tick(30) #run no more than 30 time per second
dt - clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT or \
(event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE):
running = False
#sprites.update()
#sprites.update(dt / 1000.)
#screen.fill(black)
sprites.update(dt / 1000., self)
#screen.blit(image, (320, 240)) #Transfer to video RAM
screen.blit(background, (0,0))
sprites.draw(screen)
pygame.display.flip() #Dispaly to Screen
if __name__ == '__main__':
pygame.init()
screen = pygame.display.set_mode((800, 800))
Game().main(screen)
Im not sure but it looks like you're only letting the player move from side to side if the player is in the air (jumping)
If i'm right you need to enable youre player to move side to side even when self.resting = True
what happens if you do something like this:
if key[pygame.K_LEFT]:
self.rect.x -= 75
if key[pygame.K_RIGHT]:
self.rect.x += 75
the thing about that is the player will move from side to sdie but when you jump and press right or left the player will fly all over instead of going into a steady jump and fall
so you need to figure out how to include the *dt to regulate the players movement in air but at the same time have the player be able to move while on the ground to
try having two sets of if statments:
if key[pygame.K_LEFT]:
self.rect.x -= 300 * dt
if key[pygame.K_RIGHT]:
self.rect.x += 300 *dt
if key[pygame.K_LEFT]and self.resting:
self.rect.x -= 50
if key[pygame.K_RIGHT]and self.resting:
self.rect.x += 50
the first one is for in the air the second is for when the player is on the ground
try that and tell me if it works
i tried it on my computer and it worked but i probably used differnt art that could also be the problem becuase it might be blitting behind something so check everything
Good Luck!!

Categories

Resources