How could I optimise this simple python pygame code - python

I've been set a challenge to make a game using pygame ( I am making snake so it should be easy... but I've never used pygame) so using a more efficient language isn't an option.So my question is that I updating the snake grid is too slow and I'm not experienced enough in pygame to fix this, can anyone who is help.Also as a note if I only fill the grid it doesn't clear behind the Snake.
Using python 3.8
import pygame
import time
import random
pygame.init()
display_width = 800
display_height = 600
display = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Snake")
pureblue = (0,0,255)
purered = (255,0,0)
puregreen = (0,255,0)
white = (255,255,255)
black = (1,1,1)
grey = (50,50,50)
darkgrey = (25,25,25)
clock = pygame.time.Clock()
snake_block = 10
snake_speed = 30
font_style = pygame.font.SysFont(None, 50)
def drawGrid():
blockSize = 10
for x in range(display_width):
for y in range(display_height):
rect = pygame.Rect(x*blockSize, y*blockSize,blockSize, blockSize)
pygame.draw.rect(display, darkgrey, rect, 1)
def message(msg, colour):
text = font_style.render(msg, True, colour)
display.blit(text, [display_width/2, display_height/2])
def SnakeGameLoop():
game_over = False
X = display_width/2
Y = display_height/2
X_change = 0
Y_change = 0
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
X_change = -10
Y_change = 0
elif event.key == pygame.K_RIGHT:
X_change = 10
Y_change = 0
elif event.key == pygame.K_UP:
X_change = 0
Y_change = -10
elif event.key == pygame.K_DOWN:
X_change = 0
Y_change = 10
if X >= display_width or X < 0 or Y >= display_height or Y < 0:
game_over = True
X += X_change
Y += Y_change
display.fill(grey)
drawGrid()
pygame.draw.rect(display,puregreen,[X,Y,10,10])
pygame.display.update()
clock.tick(15)
message("You lost", purered)
pygame.display.update()
time.sleep(2)
pygame.quit()
quit()
SnakeGameLoop()

To improve the game's performance, draw the grid on a pygame.Surface object with the size of the screen, before the application loop:
def drawGrid(surf):
surf.fill(grey)
blockSize = 10
for x in range(display_width):
for y in range(display_height):
rect = pygame.Rect(x*blockSize, y*blockSize,blockSize, blockSize)
pygame.draw.rect(surf, darkgrey, rect, 1)
grid_surf = pygame.Surface(display.get_size())
drawGrid(grid_surf)
blit the surface once per frame on the display instead of drawing the grid once per frame, in the application loop:
def SnakeGameLoop():
# [...]
while not game_over:
# [...]
display.blit(grid_surf, (0, 0))
pygame.draw.rect(display,puregreen,[X,Y,10,10])
pygame.display.update()

Related

Pygame - Pressing backspace to change sprite color

I'm trying to make a game, and I want to make the user be able to change color of their sprite when pressing backspace. As of now, nothing that I draw appears on screen, I have no idea why. Any detailed answer, explaining how and why you change the color of your sprite would be welcome:
This is my code:
import pygame
pygame.init()
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
width = 800
height = 600
FPS = 100
font = pygame.font.SysFont(None, 25)
gameDisplay = pygame.display.set_mode((width, height))
pygame.display.set_caption("Second snake game.")
clock = pygame.time.Clock()
def message_to_screen(msg, color):
screen_text = font.render(msg, True, color)
gameDisplay.blit(screen_text, [width/2, height/2])
def gameloop():
exitGame = False
lead_x = width/2
lead_y = height/2
lead_x_change = 0
lead_y_change = 0
block_size = 10
velocity = 0.1
rectangle = pygame.draw.rect(gameDisplay, black, [lead_x, lead_y, block_size, block_size])
while not exitGame:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exitGame = True
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
lead_y_change += -velocity
lead_x_change = 0
if event.key == pygame.K_s:
lead_y_change += velocity
lead_x_change = 0
if event.key == pygame.K_a:
lead_x_change += -velocity
lead_y_change = 0
if event.key == pygame.K_d:
lead_x_change += velocity
lead_y_change = 0
if event.key == pygame.K_BACKSPACE:
rectangle.rect(gameDisplay, black, [lead_x, lead_y, block_size, block_size])
if event.type == pygame.KEYUP:
if event.key == pygame.K_a or event.key == pygame.K_d:
lead_x_change = 0
if event.key == pygame.K_w or event.key == pygame.K_s:
lead_y_change = 0
lead_x += lead_x_change
lead_y += lead_y_change
gameDisplay.fill(white)
pygame.display.update()
clock.tick(FPS)
gameloop()
First, put the rendering functions in an appropriate order and put them in your while loop:
gameDisplay.fill(white) # Display fill comes first
pygame.draw.rect(gameDisplay, black, rectangle) # Then draw your objects
pygame.display.flip() # Update the screen
Then, define the pygame.Rect object properly
rectangle = pygame.Rect(lead_x, lead_y, block_size, block_size)
This is what you are probably trying to find (with my few fixes):
import pygame
pygame.init()
# Constants
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
WIDTH = 800
HEIGHT = 600
FPS = 100
FONT = pygame.font.SysFont(None, 25)
BLOCK_SIZE = 10
VELOCITY = 10
gameDisplay = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Second snake game.")
clock = pygame.time.Clock()
def message_to_screen(msg, color):
screen_text = font.render(msg, True, color)
gameDisplay.blit(screen_text, [width/2, height/2])
def gameloop():
exitGame = False
x = WIDTH / 2
y = HEIGHT / 2
rectangle = pygame.Rect(x, y, BLOCK_SIZE, BLOCK_SIZE)
rectangle_color = BLACK
while not exitGame:
clock.tick(FPS)
# Pygame events
for event in pygame.event.get():
if event.type == pygame.QUIT:
exitGame = True
pygame.quit()
quit()
if event.type == pygame.KEYUP:
if event.key == pygame.K_w:
y -= VELOCITY
if event.key == pygame.K_s:
y += VELOCITY
if event.key == pygame.K_a:
x -= VELOCITY
if event.key == pygame.K_d:
x += VELOCITY
if event.key == pygame.K_BACKSPACE:
rectangle_color = RED if rectangle_color == BLACK else BLACK
# Update rect coords
rectangle = pygame.Rect(x, y, BLOCK_SIZE, BLOCK_SIZE)
# Render everything
gameDisplay.fill(WHITE)
pygame.draw.rect(gameDisplay, rectangle_color, rectangle)
pygame.display.flip()
gameloop()

When running a script, two objects that are very far apart recognise as colliding

I've been having trouble with this code in Pygame recently, and I am not able to find my error. The script is at the moment just a controllable sprite, (which I understand is not showing as things are drawn over it) but when I run my code it thinks the small white square, (player) is colliding with the larger, (blocks.trees). The code is as such:
import pygame
from pygame.locals import*
#initialise pygame
pygame.init()
WHITE = (255,255,255)
#counts which sprite you should be on when running
#create screen
screen_width = 160
screen_height = 144
screen_multiplier = 4
screen = pygame.display.set_mode(((screen_width*screen_multiplier), (screen_height*screen_multiplier)))
pygame.display.set_caption('Pokemon Blood Red')
#Sprite stuff
sprite = pygame.image.load('player_east_still.png')
#Reform the sprite
sprite = pygame.transform.scale(sprite, (10*screen_multiplier, 14*screen_multiplier))
sprite.set_colorkey(WHITE)
#############################################################################
class Player(pygame.sprite.Sprite):
def __init__(self):
super(Player, self).__init__()
self.player_sprite = pygame.Surface((10*screen_multiplier, 14*screen_multiplier))
self.player_sprite.fill(WHITE)
self.rect = self.player_sprite.get_rect()
class Blocks(pygame.sprite.Sprite):
def __init__(self):
super(Blocks, self).__init__()
self.trees = pygame.Surface((20*screen_multiplier, 40*screen_multiplier))
self.trees.fill(WHITE)
self.rect = self.trees.get_rect()
player = Player()
blocks = Blocks()
#############################################################################
#Random variables for later use
amount_caught = 0
place = 1
catch1 = {'pokemon':'none',
'hp':0,
'attack':0,
'defence':0,
'sp_attack':0,
'sp_defence':0,}
background = 1
def area_load():
global background
if background == 1:
background = pygame.image.load('neuory_town.png').convert()
background = pygame.transform.scale(background, (160*screen_multiplier, 144*screen_multiplier))
area_load()
(x) = 160*0.45
(y) = 144*0.45
def caught():
if amount_caught == 0:
pass
#Mainloop
crashed = False
while not crashed:
pressed_keys = pygame.key.get_pressed()
player.update(pressed_keys)
x_change = 0
y_change = 0
#Different buttons
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
pygame.quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = 5*screen_multiplier
sprite = pygame.image.load('player_west_still.png')
elif event.key == pygame.K_RIGHT:
x_change = -5*screen_multiplier
sprite = pygame.image.load('player_east_still.png')
elif event.key == pygame.K_UP:
y_change = -5*screen_multiplier
sprite = pygame.image.load('player_north_still.png')
elif event.key == pygame.K_DOWN:
y_change = 5*screen_multiplier
sprite = pygame.image.load('player_south_still.png')
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
x_change = 0
elif event.key == pygame.K_RIGHT:
x_change = 0
elif event.key == pygame.K_UP:
y_change = 0
elif event.key == pygame.K_DOWN:
y_change = 0
x += x_change
y += y_change
blockades = pygame.sprite.Group()
blockades.add(blocks)
#Check for collisions
hits = pygame.sprite.spritecollide(player, blockades, True)
if hits:
print ('Collision!')
#Draw everything
sprite = pygame.transform.scale(sprite, (10*screen_multiplier, 14*screen_multiplier))
sprite.set_colorkey(WHITE)
screen.blit(background,(0,0))
screen.blit(sprite,(x,y))
screen.blit(player.player_sprite, (x, y))
screen.blit(blocks.trees, (200, 200))
pygame.display.flip()
pygame.quit()
Thanks for the help!
pygame.sprite.spritecollide checks if the rects of the sprites overlap. You never move the rects to a new position after the instantiation, so both the player and the blocks are still positioned at (0, 0) (try to print(blocks.rect, player.rect)). To move them you can for example change the x and y coords, the topleft, center or the other attributes of the rect:
blocks.rect.center = (400, 500)
player.rect.topleft = (20, 40)
player.rect.x += 50
player.rect.y += 100
In your original example you're not moving the sprites, but only change the variables x and y which you use as the blit position for the image.
# This doesn't change the position of the rect, so there won't be collisions.
x += x_change
y += y_change
You should instead move the rect and then use the rect as the blit position:
player.rect.x += x_change
player.rect.y += y_change
screen.blit(player.player_sprite, player.rect) # Blits the image at rect's topleft coords.
Also, the image attribute of a pygame.sprite.Sprite should be called image not player_sprite. Then you can put all your sprites into one pygame.sprite.Group and to update and draw all sprites you only need two lines of code:
# Before the while loop define the sprite group.
all_sprites = pygame.sprite.Group()
# Add all sprites.
all_sprites.add(player) # And other sprites.
# In the while loop update the sprites.
all_sprites.update()
# And in the draw phase.
all_sprites.draw(screen)

Python 3.5.2: Pygame Snake Apple location [duplicate]

I am making a game in which the player has to use a bowl to catch falling items. I have some images of items in a list and an image of a bowl that is used to catch the items. The items keep on falling and reset to the top of the screen if they reach the boundary (bottom edge). I got this logic done which allows the items to fall but I do not know how to detect when there is a collision between the bowl and item.
My code:
import math
import pygame
import random
pygame.init()
display_width = 800
display_height = 600
game_display = pygame.display.set_mode((display_width, display_height))
clock = pygame.time.Clock()
pygame.display.set_caption("Catch the Ball")
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
blue = (0, 255, 0)
player_img = pygame.image.load("Images/soup.png")
thing_imgs = [pygame.image.load('Images/muffin.png'), pygame.image.load('Images/dessert.png'),
pygame.image.load('Images/cheese.png'), pygame.image.load('Images/fruit.png')]
def player(x, y):
game_display.blit(player_img, (x, y))
def things(x, y, img):
game_display.blit(img, (x, y))
def game_loop():
running = True
x = display_width * 0.45
y = display_height * 0.8
x_change = 0
player_width = 64
player_height = 64
things_cor = [[random.randint(0, display_width), 32]]
things_added = [random.choice(thing_imgs)]
thing_height = 32
thing_width = 32
y_change = 5
caught = 0
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
if event.key == pygame.K_RIGHT:
x_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
game_display.fill(white)
player(x, y)
x += x_change
for i in range(len(things_cor)):
thing_x, thing_y = things_cor[i]
things(thing_x, thing_y, things_added[i])
for i in range(len(things_cor)):
things_cor[i][1] += y_change
if things_cor[i][1] > display_height:
things_cor[i][1] = random.randint(-2000, -1000)
things_cor[i][0] = random.randint(0, display_width)
things_added[i] = random.choice(thing_imgs)
things_added.append(random.choice(thing_imgs))
if len(things_added) < 6:
things_cor.append(
[random.randint(0, display_width), -10])
if x < 0:
x = 0
elif x > display_width - player_width:
x = display_width - player_width
clock.tick(60)
pygame.display.update()
game_loop()
Use pygame.Rect objects and colliderect() to detect the collision between the bounding rectangles of 2 objects or 2 images:
rect1 = pygame.Rect(x1, y1, w1, h1)
rect2 = pygame.Rect(x2, y2, w2, h2)
if rect1.colliderect(rect2):
# [...]
If you have to images (pygame.Surface objects), the bounding rectangle of can be get by get_rect(), where the location of the Surface has to be set by an keyword argument, since the returned rectangle always starts at (0, 0):
(see Why is my collision test not working and why is the position of the rectangle of the image always wrong (0, 0)?)
def game_loop():
# [...]
while running:
# [...]
player_rect = player_img.get_rect(topleft = (x, y))
for i in range(len(things_cor)):
thing_rect = things_added[i].get_rect(topleft = things_cor[i])
if player_rect.colliderect(thing_rect):
print("hit")
player(x, y)
x += x_change
for i in range(len(things_cor)):
thing_x, thing_y = things_cor[i]
things(thing_x, thing_y, things_added[i])
Use pygame.time.get_ticks() to delay the start of the game for a certain time. pygame.time.get_ticks() return the number of milliseconds since pygame.init() was called. For instance:
def game_loop():
# [...]
while running:
passed_time = pygame.time.get_ticks() # passed time in milliseconds
start_time = 100 * 1000 # start time in milliseconds (100 seconds)
# [...]
# move player
if passed_time >= start_time:
x += x_change
if x < 0:
x = 0
elif x > display_width - player_width:
x = display_width - player_width
# move things
if passed_time >= start_time:
for i in range(len(things_cor)):
things_cor[i][1] += y_change
if things_cor[i][1] > display_height:
things_cor[i][1] = random.randint(-2000, -1000)
things_cor[i][0] = random.randint(0, display_width)
things_added[i] = random.choice(thing_imgs)
things_added.append(random.choice(thing_imgs))
if len(things_added) < 6:
things_cor.append(
[random.randint(0, display_width), -10])
# draw scene and update dispaly
game_display.fill(white)
player(x, y)
for i in range(len(things_cor)):
thing_x, thing_y = things_cor[i]
things(thing_x, thing_y, things_added[i])
pygame.display.update()
clock.tick(60)

How do I know when a cube collide with another moving cube?

I'm trying to create a little game as a training, but I'm blocked because I don't know how I can collide 2 moving cubes.
The game is simple, there is a red box that you can move and if this box touches a green cube, then you lost. (the green cubes are always moving)
I tried to read some documentations but it's not really easy to understand as a beginner.
Here is the code:
import pygame
import random
from threading import Timer
pygame.init()
screenWidth = 1100
screenHeight = 600
white = (255,255,255)
red = (255, 0, 0)
yellow = (50, 250, 20)
FPS = 60
gameDisplay = pygame.display.set_mode((screenWidth, screenHeight))
pygame.display.set_caption('Tekken')
pygame.display.update()
clock = pygame.time.Clock()
font = pygame.font.SysFont(None, 28)
class Players:
def __init__(self, playerName, playerAttribute, cubeheight, cubewidth, missilesHeight, missilesWidth):
self.playerName = playerName
self.playerAttribute = playerAttribute
self.playerLife = 100
self.droite_x = 300
self.droite_y = 600
self.cubeheight = cubeheight
self.cubewidth = cubewidth
self.missiles = True
self.missilesHeight = missilesHeight
self.missilesWidth = missilesWidth
self.missiles_droite_x = 0
self.missiles_droite_y = round(random.randrange(50, screenHeight-50))
self.missiles_droite_x_inverse = screenWidth-50
self.missiles_droite_y_inverse = round(random.randrange(50, screenHeight-50))
self.vitesse_missiles = 10
print(self.playerName, self.playerAttribute, self.playerLife)
def environment_un(self):
gameExit = False
gameOver = False
droite_x_change = 0
droite_y_change = 0
missiles_droite_x_change = 0
missiles_droite_x_change_inverse = 0
while not gameExit:
while gameOver:
gameDisplay.fill(red)
screen_text = font.render("Game Over, do you want to play again? [Q] to quit", True, white)
gameDisplay.blit(screen_text, [100, 300])
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
gameOver = False
gameExit = True
break
if event.type == pygame.QUIT:
gameOver = False
gameExit = True
break
for event in pygame.event.get(): #va chercher les events
if event.type == pygame.QUIT: #Si j'appuie sur X
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
droite_x_change = -3
if event.key == pygame.K_RIGHT:
droite_x_change = +3
if event.key == pygame.K_UP:
droite_y_change = -3
if event.key == pygame.K_DOWN:
droite_y_change = +3
if event.key == pygame.K_SPACE:
missiles_droite_x_change = self.vitesse_missiles
missiles_droite_x_change_inverse = -self.vitesse_missiles
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
droite_x_change = 0
if event.key == pygame.K_RIGHT:
droite_x_change = 0
if event.key == pygame.K_UP:
droite_y_change = 0
if event.key == pygame.K_DOWN:
droite_y_change = 0
self.missiles_droite_x_inverse += missiles_droite_x_change_inverse
self.missiles_droite_x += missiles_droite_x_change
self.droite_x += droite_x_change
self.droite_y += droite_y_change
if self.droite_y + self.cubeheight <= 0:
self.droite_y = 0
elif self.droite_y + self.cubeheight >= screenHeight:
self.droite_y = screenHeight-self.cubeheight
elif self.droite_x + self.cubewidth <= 0:
self.droite_x = 0
elif self.droite_x + self.cubewidth >= screenWidth:
self.droite_x = screenWidth-self.cubewidth
gameDisplay.fill(white)
gameDisplay.fill(red, rect=[self.droite_x, self.droite_y, self.cubewidth, self.cubeheight])
gameDisplay.fill(yellow, rect=[self.missiles_droite_x, self.missiles_droite_y, self.missilesWidth, self.missilesHeight])
gameDisplay.fill(yellow, rect=[self.missiles_droite_x_inverse, self.missiles_droite_y_inverse, self.missilesWidth, self.missilesHeight])
pygame.display.update()
if self.missiles_droite_x + self.missilesWidth >= screenWidth:
missiles_droite_x_change = 0
if missiles_droite_x_change == 0:
self.missiles_droite_x = 0
self.missiles_droite_y = round(random.randrange(50, screenHeight-50))
missiles_droite_x_change = self.vitesse_missiles
if self.missiles_droite_x_inverse <= 0:
missiles_droite_x_change_inverse = 0
if missiles_droite_x_change >= 0:
self.missiles_droite_x_inverse = screenWidth-50
self.missiles_droite_y_inverse = round(random.randrange(50, screenHeight-50))
missiles_droite_x_change_inverse = -12
clock.tick(FPS)
pygame.quit()
Player_1 = Players('John', 'sometext', 50, 50, 100, 100)
Player_1.environment_un()
What should do I in order to detect the collision?
I can not run your code at the moment as I dont have pygame installed. However, you can use the pygame.sprite.collide_rect() if you declare your objects to have in their class an pygame.sprite.Sprite-object or inherit from that class (as suggested below). The code below may note work as I can not test it but it should be close to a functioning code snippet. In the case you would like to test collision of a sprite against multiple other sprites - consider looking at pygame.sprite.Group(). I believe that something like this should work:
class SpriteObject(pygame.sprite.Sprite):
def __init__(self,pos_x, pos_y):
pygame.sprite.Sprite.__init__(self)
self.rect = self.original.get_rect()
self.rect.center = (pos_x, pos_y)
class Players:
def __init__(self, playerName, playerAttribute, cubeheight, cubewidth, missilesHeight, missilesWidth):
sprite1 = SpriteObject(1,2)
sprite2 = SpriteObject(1,2)
sprite1.rect.collide_rect(sprite2)
If you are looking for a conceptual answer:
Since you are considering just cubes and if they are of the same size, two cubes will occupy the same space 'if and only if' a corner of one cube is between (inclusive) two parallel planes of another. There are many ways to do this in practice.
I would check if between by evaluating an inward normal vector of cube 1 dotted with a vector to a corner (of cube 2) from any corner (of cube 1) . Do so for both parallel sides. If both are positive, its inside.
It's slightly more complicated for different shapes and varying sizes.
Use pygame.Rect() to keep cube position and size - and then you can use pygame.Rect.colliderect() to check collision between two cubes.
cube1 = pygame.Rect((x1, y1), (width, height))
cube2 = pygame.Rect((x2, y2), (width, height))
if cube1.colliderect(cube2):
print("Collision !")
PyGame has other usefull classes - pygame.sprite.Sprite and pygame.sprite.Group - which use Rect and collision detection functions.

pygame/python sprite not moving? What have i done wrong? (no errors)

Alright, so here's my code, I get no errors but my sprite (player) is not moving
import pygame,sys
import random
import time
#Colors
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
class Block(pygame.sprite.Sprite):
def __init__(self, color = blue, width = 50, height = 50):
super(Block, self).__init__()
self.image = pygame.Surface((width, height))
self.image.fill(color)
self.rect = self.image.get_rect()
def set_position(self, x , y):
self.rect.x = x
self.rect.y = y
def set_image(self, filename = None):
if(filename != None):
self.image = pygame.image.load(filename)
self.rect = self.image.get_rect()
if (__name__ == "__main__"):
pygame.init()
window_size = window_width, window_height = 640,480
window = pygame.display.set_mode(window_size)
pygame.display.set_caption('Test')
window.fill(white)
clock = pygame.time.Clock()
#important variables
pos_x = 300
pos_y = 200
pos_x_change = 0
pos_y_change = 0
block_group = pygame.sprite.Group()
player = Block()
player.set_image('player.png')
player.set_position(pos_x,pos_y) #Player variable for pos
another_block = Block(red)
another_block.set_position(100,100)
block_group.add(player, another_block)
block_group.draw(window)
pygame.display.update()
running = True
while(running):
for event in pygame.event.get():
if (event.type == pygame.QUIT):
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
pos_x_change = -10
if event.key == pygame.K_RIGHT:
pos_x_change = 10
if event.key == pygame.K_UP:
pos_y_change -10
if event.key == pygame.K_DOWN:
pos_y_change = 10
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
pos_x_change = 0
if event.key == pygame.K_RIGHT:
pos_x_change = 0
if event.key == pygame.K_UP:
pos_y_change == 0
if event.key == pygame.K_DOWN:
pos_y_change == 0
pos_x += pos_x_change
pos_y += pos_y_change
clock.tick(60)
pygame.quit
quit()
As you can see, I clearly added the pos_x and pos_y
and set it to pos_x += pos_x_change
and pos_y += pos_y_change
but the sprite is still not moving.
I'm guessing it's a misplacement of code because python heavily relies on indentation? Please explain to me what i have done wrong, It would be greatly appreciated.
It looks like you're updating the variables that contain the players x and y coordinates, but you're not updating the display. That's why it looks like the position isn't changing. I believe calling player.set_position(pos_x,pos_y) just above the clock.tick(60) statement will fix the problem.

Categories