Pygame not checking keyevents after another happens - python

I am moving a sprite on the x-axis. It is properly moving left and right. When I press both LEFT and RIGHT at the same time it stop moving properly.
I am trying to make it when a user presses both keys and then lets go of one, for it to continue moving in the direction still pressed.
Weirdly it works while I holding right and letting go of left. It continues moving right.
When I hold left and tap right it stops moving until I press right again.
I commented out some ideas I had to make this work, but they failed me.
I am sure its a simple fix or a logic failure on my part.
I have worked a couple hours on this.
Thanks for responses ahead of time.
import pygame
import time
import random
import sys
import math
pygame.init()
displayWidth = 1200
displayHeight = 800
white = (255,255,255)
black = (0,0,0)
gameDisplay = pygame.display.set_mode((displayWidth, displayHeight))
pygame.display.set_caption('Game 3')
clock = pygame.time.Clock()
class firstSquare:
def __init__(self,player_x,player_y):
self.x = player_x
self.y = player_y
self.width = 100
self.height = 100
def render(self):
pygame.draw.rect(gameDisplay, white,(self.x, self.y, self.width, self.height))
class secondSquare:
def __init__(self,cpu_x,cpu_y):
self.x = cpu_x
self.y = cpu_y
self.width = 100
self.height = 100
def render(self):
pygame.draw.rect(gameDisplay, white,(self.x, self.y, self.width, self.height))
player = firstSquare(300,300)
cpu = secondSquare(100,100)
def gameLoop():
### variables##
player_x = 100
player_y = 100
x = 100
y = 100
movement_x = 0
movement_y = 0
frame_rate = 0
frame_table = 0
inGame = True
while inGame:
for event in pygame.event.get():
if event.type == pygame.QUIT:
inGame = False
pygame.quit()
sys.exit()
keyPressed= pygame.key.get_pressed()
#### this is moving the player on x-axis##
if keyPressed[pygame.K_LEFT]:
movement_x = -5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
movement_x = 0
if keyPressed[pygame.K_RIGHT]:
movement_x = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
movement_x = 0
### two keys at once won't move the player###
if keyPressed[pygame.K_LEFT] and keyPressed[pygame.K_RIGHT]:
movement_x = 0
### pressing one key and letting go the other will continue movement
## if keyPressed[pygame.K_LEFT] and keyPressed[pygame.K_RIGHT]:
## if event.type == pygame.KEYUP:
## if event.key == pygame.K_LEFT:
## movement_x = 5
## print("left dropped")
## if keyPressed[pygame.K_RIGHT] and keyPressed[pygame.K_LEFT]:
## if event.type == pygame.KEYUP:
## if event.key == pygame.K_RIGHT:
## movement_x = -5
## print("Right dropped")
gameDisplay.fill(black)
player.render()
cpu.render()
player.x += movement_x
pygame.display.update()
clock.tick(60)
gameLoop()
pygame.quit()
quit()

I think what you need is this:
if keyPressed[pygame.K_LEFT]:
movement_x = -5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT and movement_x < 0:
movement_x = 0
if keyPressed[pygame.K_RIGHT]:
movement_x = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT and movement_x > 0:
movement_x = 0
And that would be it... Hope it helps.

Try to use the following code in your movement:
if keyPressed[pygame.K_LEFT]:
movement_x = -5
elif keyPressed[pygame.K_RIGHT]:
movement_x = +5
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
movement_x = 0
elif event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
movement_x = 0

Related

Pygame Game Development shoot functionality

My question is how can I better my shooting functionality in my game. I am trying to make it to where the player can shoot in the direction it is moving (ex.shoot up,down,left,right) as well as shoot while moving and shoot while idle.
The player and missile are both rectangular using pygame shapes to make it easier for me to understand the logic behind game development.
def player(px,py):
pygame.draw.rect(gameWindow,black,[px,py,30,30])
def missile(mx,my):
pygame.draw.rect(gameWindow,black,[mx,my,10,10])
Here is the code of the game to help better understand what I'm talking about. The small section I have commented out is what I have tried. I only have it currently set to move in the x direction going left from its initial starting point.
import pygame #####IMPORTING PYGAME MODULE###########################
pygame.init() #####INITIALIZING PYGAME##################################
gameWindow = pygame.display.set_mode((800,600)) ###Screen Width and Height###
clock = pygame.time.Clock() ## FRAMES PER SECOND ##
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
def player(px,py):
pygame.draw.rect(gameWindow,black,[px,py,30,30])
def missile(mx,my):
pygame.draw.rect(gameWindow,black,[mx,my,10,10])
def enemies():
return
def gameloop():
px = 700
py = 300
mx = 700
my = 300
px_change = 0
py_change = 0
mx_change = 0
my_change = 0
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
mx_change = -10
if event.key == pygame.K_RIGHT:
mx_change = 10
if event.key == pygame.K_UP:
my_change = -10
if event.key == pygame.K_DOWN:
my_change = 10
if event.key == pygame.K_SPACE:
mx_change = -6
#if event.key == pygame.K_SPACE and pygame.K_RIGHT:
#mx_change = 6
if event.key == pygame.K_LEFT:
px_change = -10
if event.key == pygame.K_RIGHT:
px_change = 10
if event.key == pygame.K_UP:
py_change = -10
if event.key == pygame.K_DOWN:
py_change = 10
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
px_change = 0
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
py_change = 0
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
mx_change = 0
mx = px
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
my_change = 0
my = py
if event.key == pygame.K_SPACE:
mx_change = 0
my_change = 0
mx = px
my = py
px += px_change
py += py_change
mx += mx_change
my += my_change
gameWindow.fill(white)
player(px,py)
missile(mx,my)
pygame.display.update()
clock.tick(100)
pygame.quit()
quit()
gameloop()
I would suggest using different objects for your player and missile. The way you have things set up right now, there can only be 1 player and 1 missile. Only having 1 player might be fine but 1 missile makes for a dull game. I suggest using a class, such as this simple example:
class Projectile():
def init(self,x,y,vx,vy):
self.x = x
self.y = y
self.vx = vx
self.vy = vy
def update(self):
self.x += self.vx
self.y += self.vy
Now that you have a class you can start doing great things! Want to have spacebar fire a new missile instead of moving the one missile on screen? ezpz! All you need is a list of your missile objects to keep track of, say my_missile_list:
if event.key == pygame.K_SPACE:
my_missile_list.append(Projectile(px,py,missile_x_velocity,missile_y_velocity))
This creates an entirely new instance of the class Projectile based on the input position and speeds.
Finally, we need to have all these missiles move! This is where the class definition makes our life easier! Once per frame we just have to update the bullets:
for b in my_missile_list:
b.update()
There are more advantages to using classes here but this is a start. If you read through this and make a few changes your game will work much more like what you are looking for.
You should set missille only when you KEYDOWN space, and not use other keys to change it. Player may have variable direction so you will know in which direction it is looking when it stay and you will know in which direction move misille.
import pygame
# --- constants --- (UPPER_CASE_NAMES)
WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)
# --- classes --- (CamelCaseNames)
# empty
# --- functions ---- (lower_case_names_
def player(screen, x, y):
pygame.draw.rect(screen, BLACK, (x, y, 30, 30))
def missile(screen, x, y):
pygame.draw.rect(screen, RED, (x, y, 10, 10))
def enemies():
pass
def gameloop(screen):
px = 700
py = 300
mx = 700
my = 300
px_change = 0
py_change = 0
p_direction = 'left'
mx_change = 0
my_change = 0
#m_direction = 'left'
game_exit = False
clock = pygame.time.Clock() ## FRAMES PER SECOND ##
while not game_exit:
# --- events ---
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_exit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
px_change = -10
p_direction = 'left'
if event.key == pygame.K_RIGHT:
px_change = 10
p_direction = 'right'
if event.key == pygame.K_UP:
py_change = -10
p_direction = 'top'
if event.key == pygame.K_DOWN:
py_change = 10
p_direction = 'down'
if event.key == pygame.K_SPACE:
mx = px
my = py
if p_direction == 'left':
mx_change = -16
my_change = 0
elif p_direction == 'right':
mx_change = 16
my_change = 0
elif p_direction == 'top':
mx_change = 0
my_change = -16
elif p_direction == 'down':
mx_change = 0
my_change = 16
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
px_change = 0
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
py_change = 0
# --- changes/updates ---
px += px_change
py += py_change
mx += mx_change
my += my_change
# --- draws ----
screen.fill(WHITE)
player(screen, px, py)
missile(screen, mx, my)
pygame.display.update()
# --- FPS ---
clock.tick(30)
# --- main ---
pygame.init()
screen = pygame.display.set_mode((800,600))
gameloop(screen)
pygame.quit()
#quit()
Instead of px, py and mx,my you should use pygame.Rect() - it can be used to draw() and blit() and it has methods to check collisions.

Pygame sprite crossing s creen

The issue is when i press the left or right key while i press it, the sprite crosses the left and right boundaries of the screen. But when i tap it, it will not cross only when i hold the key continuosly
this is the class for the humanship
class Human:
y = display_height * 0.8
x = display_width * 0.45
width = 120
image = pygame.image.load('yasin/alien1.png')
def run(self):
gameDisplay.blit(Human.image, (Human.x, Human.y))
This is the main loop which iterates throughout the game
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
if human.x > 0:
x_change = -8
else:
x_change = 0
elif event.key == pygame.K_RIGHT:
if human.x < display_width - human.width:
x_change = 8
else:
x_change = 0
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
human.x += x_change
human.run()
Move the if human.x > 0: and if human.x < display_width - human.width: out of the event loop because they'll only be executed once per event in the event queue. Rather check in the main while loop if the player is still inside of the game area, otherwise stop it.
I've also changed a few more things: The attributes should be defined in the __init__ method to make them instance attributes instead of class attributes. Use self.x instead of Human.x in the class. The x_change and y_change variables belong to the human object, so they should be attributes as well. Then you can add an update method to the Human in which you do the bounds checking and the movement.
import pygame
display_width, display_height = 640, 480
class Human:
def __init__(self):
self.image = pygame.image.load('yasin/alien1.png')
self.y = display_height * 0.8
self.x = display_width * 0.45
self.x_change = 0
self.y_change = 0
self.width = 120
def run(self, gameDisplay):
gameDisplay.blit(self.image, (self.x, self.y))
def update(self):
self.x += self.x_change
# Check if the human is outside of the game area.
if self.x < 0:
self.x_change = 0 # Stop it.
self.x = 0 # Reset the position, so that we can move again.
elif self.x > display_width - self.width:
self.x_change = 0
self.x = display_width - self.width
def main():
pygame.init()
gameDisplay = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()
human = Human()
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
human.x_change = -8
elif event.key == pygame.K_RIGHT:
human.x_change = 8
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
human.x_change = 0
human.update()
gameDisplay.fill((30, 30, 30))
human.run(gameDisplay)
pygame.display.flip()
clock.tick(30)
if __name__ == '__main__':
main()
pygame.quit()

Can't figure out why my image wont move in pygame

I'm just messing around with Pygame and I can't see what I'm doing incorrectly to make the red circle move with the arrow keys. I can't tell if it's in my main loop. I also haven't been able to find very many tutorials on sprite or looping animations with Pygame. If I for example wanted to make a square oscillate for example like a moving platform how would I do that?
import pygame
import time
## event handling varibles
player_x = 0
player_y = 0
x = 250
y = 250
## screen display
display_width = 500
display_height = 500
pygame.init()
game_screen = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("test")
# player
def player():
pygame.draw.circle(game_screen,red,(x,y),15)
# colors
white = (255,255,255)
red = (255,0,0)
black = (0,0,0)
### main loop
dead = False
while dead != True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
dead = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player_x = -1
elif event.key == pygame.K_RIGHT:
player_x = +1
if event.key == pygame.K_UP:
player_y = +1
elif event.key == pygame.K_DOWN:
player_y = -1
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or pygame.K_RIGHT:
player_x = 0
if event.key == pygame.K_UP or pygame.K_DOWN:
player_y = 0
game_screen.fill(black)
player()
pygame.display.update()
x -= player_x
y -= player_y
pygame.quit()
quit()
Your indendation is all messed up.
Your code won't do anything unless the event is QUIT... which then makes it quit.
Your boolean logic is wrong.
This is not proper syntax event.key == pygame.K_UP or pygame.K_DOWN. The order of precedence here is as follows (event.key == pygame.K_UP) or (K_DOWN). Since K_DOWN is truthy, it is always true and thus this entire statement is always true.
I think you mean: event.key == pygame.K_UP or event.key == pygame.K_DOWN
Lastly, it wont' keep moving as you say you want.
It will only move when there is an event in the queue. You can make it keep moving by generating events. Perhaps with an event timer.
Here is a fixed version, hope this helps:
import pygame
import time
## event handling varibles
player_x = 0
player_y = 0
x = 250
y = 250
## screen display
display_width = 500
display_height = 500
pygame.init()
game_screen = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("test")
# player
def player(game_screen, red, point): # Use parameters not globals
pygame.draw.circle(game_screen, red, point, 15)
# colors
white = (255,255,255)
red = (255,0,0)
black = (0,0,0)
### main loop
pygame.time.set_timer(pygame.USEREVENT, 1) # 1 per second
dead = False
while not dead:
for event in pygame.event.get():
if event.type == pygame.QUIT:
dead = True
elif event.type == pygame.USEREVENT:
pygame.time.set_timer(pygame.USEREVENT, 1) # Set another timer for another 1 second
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player_x = +10
elif event.key == pygame.K_RIGHT:
player_x = -10
elif event.key == pygame.K_UP:
player_y = +10
elif event.key == pygame.K_DOWN:
player_y = -10
elif event.type == pygame.KEYUP:
if event.key in [pygame.K_LEFT, pygame.K_RIGHT]:
player_x = 0
elif event.key in [pygame.K_UP, pygame.K_DOWN]:
player_y = 0
game_screen.fill(black)
player(game_screen,red,(x,y))
pygame.display.update()
x -= player_x
y -= player_y
pygame.quit()

How to create a border in Pygame

I would like to know how to create a border in Pygame to stop the user controlled object from exiting the screen. Right now, I only have it so python prints some text when the user controlled object has come near one of the 4 sides.
Here is my code so far.
import pygame
from pygame.locals import *
pygame.init()
#Display Stuff
screenx = 1000
screeny = 900
screen = pygame.display.set_mode((screenx,screeny))
pygame.display.set_caption('Block Runner')
clock = pygame.time.Clock()
image = pygame.image.load('square.png')
#Color Stuff
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
white = (255,255,255)
black = (0,0,0)
#Variables
x_blocky = 50
y_blocky = 750
blocky_y_move = 0
blocky_x_move = 0
#Animations
def Blocky(x_blocky, y_blocky, image):
screen.blit(image,(x_blocky,y_blocky))
#Game Loop
game_over = False
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
blocky_y_move = -3
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
blocky_y_move = 0
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_DOWN:
blocky_y_move = 3
if event.type == pygame.KEYUP:
if event.key == pygame.K_DOWN:
blocky_y_move = 0
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
blocky_x_move = 3
if event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
blocky_x_move = 0
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
blocky_x_move = -3
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
blocky_x_move = 0
if x_blocky > 870 or x_blocky < 0:
print(' X Border')
if y_blocky > 750 or y_blocky < 2:
print(' Y Border')
y_blocky += blocky_y_move
x_blocky += blocky_x_move
screen.fill(white)
Blocky(x_blocky, y_blocky, image)
pygame.display.update()
clock.tick(60)
Don't use integers to store your position. Use a Rect.
So instead of
x_blocky = 50
y_blocky = 750
use
blocky_pos = pygame.rect.Rect(50, 750)
Now you can simply use
blocky_pos.move_ip(blocky_x_move, blocky_y_move)
to move your object.
After moving, you can simply call clamp/clamp_ip to ensure the blocky_pos Rect is always inside the screen.
blocky_pos.clamp_ip(screen.get_rect())
Also, you don't need to define basic colors yourself, you could simply use pygame.color.Color('Red') for example.
I also suggest you use pygame.key.get_pressed() to get all pressed keys to see how to move your object instead of creating 1000 lines of event handling code.
Well, simply don't increase your move variable any further, if you detect that the user object is near or at the border. Or reverse the move direction, depending on your general intent.
if x_blocky > 870 or x_blocky < 0:
print(' X Border')
blocky_x_move = 0
if y_blocky > 750 or y_blocky < 2:
print(' Y Border')
blocky_y_move = 0
Also, you have some redundant code with your keyboard movement. Instead of writing
if event.type == KEYDOWN:
over and over again, group the KEYUP if statements and KEYDOWN if statements.
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
blocky_y_move = -3
elif event.key == pygame.K_DOWN:
blocky_y_move = +3
etc, and:
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
blocky_y_move = 0
elif event.type == pygame.K_DOWN:
blocky_y_move = 0
etc
You can set the boundaries using the min and max functions.
Here is the concept:
We have a pygame object that moves in all four directions; lets say the user holds down the LEFT arrow key, so that the object reaches the top of the screen. The y-coordinate of the top of the screen will always be 0, so we want the object to come to a stop at y-coordinate 0.
This may seem as simple as:
if char.rect.y > 0:
char.rect.y -= char.speed
But this will result in a bug ig char.speed is greater than 1. Like when the object is at y-coordinate 5,
and its speed is 10; the condition still allows for one more step for the object, resulting in the object
coming 5 pixels out of the pygame window. What we want to do is more like:
if char.rect.y > 0:
char.rect.y -= char.speed
if char.rect.y < 0:
char.rect.y = 0
to push the object back into the boundaries. The above block of code can be simplified with the max function:
self.rect.y = max([self.rect.y - self.speed, 0])
For the object moving down:
if char.rect.y < HEIGHT - char.height:
char.rect.y += char.speed
if char.rect.y > HEIGHT - char.height:
char.rect.y = HEIGHT - char.height
or, the more efficient and clean method:
self.rect.y = min([self.rect.y + self.speed, HEIGHT - self.height])
For going left and right, simply replace the ys and height (and HEIGHT) from two lines above with xs and widths (and WIDTH).
All together:
import pygame
pygame.init()
WIDTH = 600
HEIGHT = 600
wn = pygame.display.set_mode((WIDTH, HEIGHT))
class Player:
def __init__(self):
self.speed = 1
self.width = 20
self.height = 20
self.color = (255, 255, 0)
self.rect = pygame.Rect((WIDTH - self.width) / 2, (HEIGHT - self.height) / 2, 20, 20)
def up(self):
self.rect.y = max([self.rect.y - self.speed, 0])
def down(self):
self.rect.y = min([self.rect.y + self.speed, HEIGHT - self.height])
def left(self):
self.rect.x = max([self.rect.x - self.speed, 0])
def right(self):
self.rect.x = min([self.rect.x + self.speed, WIDTH - self.width])
def draw(self):
pygame.draw.rect(wn, self.color, self.rect)
char = Player()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]:
char.up()
if keys[pygame.K_DOWN]:
char.down()
if keys[pygame.K_LEFT]:
char.left()
if keys[pygame.K_RIGHT]:
char.right()
wn.fill((0, 0, 0))
char.draw()
pygame.display.update()
Good luck!

How do I make a certain sprite move in pygame?

I need to make the player move continuously when I press a certain key.The problem that I have is that the image of the player is moving once (when I press one of the defined keys) and then it stops.
enter code here
import pygame
import sys
import os
import random
import time
from pygame.locals import *
pygame.init()
white = ( 255, 255, 255 )
black = ( 0, 0, 0 )
screenw = 800
screenh = 600
screen = pygame.display.set_mode( ( screenw, screenh ) )
pygame.display.set_caption( "Game" ) # Here I create a display.
clock = pygame.time.Clock()
class Car(pygame.sprite.Sprite): # Here I create a class.
def __init__( self, color = black, width = 100, height = 100 ):
pygame.sprite.Sprite.__init__( self )
self.image = pygame.Surface( ( width, height ) )
self.image.fill( color )
self.rect = self.image.get_rect()
def set_pos(self, x, y):
self.rect.x = x
self.rect.y = y
def set_img( self, filename = None):
if filename != None:
self.image = pygame.image.load( filename )
self.rect = self.image.get_rect()
def main():*I create a game loop
x_change = 0
y_change = 0
x = 0
y = 0
car_group = pygame.sprite.Group() # Make a group
player = Car()
player.set_img( "images.jpg" )
car_group.add( player )
exit = False
FPS = 60
while not exit:
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 = -10
elif event.key == pygame.K_RIGHT:
x_change = 10
elif event.key == pygame.K_UP:
y_change = -10
elif event.key == pygame.K_DOWN:
y_change = 10
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == pygame.K_UP or event.type == pygame.K_DOWN:
x_change = 0
y_change = 0
x += x_change
y += y_change
screen.fill( white )
player.set_pos( x, y ) # Blit the player to the screen
car_group.draw( screen )
clock.tick( FPS )
pygame.display.update()
main()
pygame.quit()
quit()
Well the problem is that you are only allowing the sprite to move once. For example, take this piece of your code:
if event.key == pygame.K_LEFT:
x_change = -10
This will allow the x position to be smaller by 10. Then it stops. You maybe want to make a update function. A variable will also be made to allow the function to be used or not to be used. Another one will be used to control the direction it goes. Here is the update function. Feel free to change it to be able to fit your needs:
def update():
global direction
if direction == 'LEFT':
x -= 10
elif direction == 'RIGHT':
x += 10
elif direction == 'UP'
y -= 10
elif direction == 'DOWN':
y += 10
Now we will need the variable to control whether the function will run or not. Add these two lines for our new two variables:
run = 0
direction = 'NONE'
They should be before the code for the class. You absolutely change the lines from your event.key lines, it should be (in proper indention):
if event.key == pygame.K_LEFT:
direction = 'LEFT'
run = 1
elif event.key == pygame.K_RIGHT:
direction = 'RIGHT'
run = 1
elif event.key == pygame.K_UP:
direction = 'UP'
run = 1
elif event.key == pygame.K_DOWN:
direction = 'DOWN'
run = 1
Of course, there must be something to stop the car from repeatedly moving infinitely right? Add these lines with the lines above:
elif event.key == pygame.K_SPACE:
direction = 'NONE'
run = 0
Now put these two lines in the while loop but before you for loop:
if run == 1:
Car.update()
else:
pass
This should work because as long run is equal to 1, the car will continue its movement in the given direction until stopped by pressing the spacebar. I hope this helps you!

Categories