How do I make the paddle move with the arrow keys? - python

I'm trying to make it so that you can move the paddle (making a pong game) with the arrow keys. I already have most of the code but I'm confused as to what I would pass to the function that will move the paddle.
Here is my code (this was base code given to us by our instructor, we just modified parts of it):
import math
import random
import sys, pygame
from pygame.locals import *
import ball
import colors
import paddle
# draw the scene
def draw(screen, ball1, paddle1) :
screen.fill((128, 128, 128))
ball1.draw_ball(screen)
paddle1.draw_paddle(screen)
#function to start up the main drawing
def main():
pygame.init()
width = 600
height = 600
screen = pygame.display.set_mode((width, height))
ball1 = ball.Ball(300, 1, 40, colors.RED)
paddle1 = paddle.Paddle(100, 575, colors.BLUE, 100, 20)
while 1:
for event in pygame.event.get():
if event.type == QUIT: sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
paddle1.update_paddle()
if event.key == pygame.K_LEFT:
paddle1.update_paddle()
draw(screen, ball1, paddle1)
pygame.display.flip()
if __name__ == '__main__':
main()
In the while loop, where it says "paddle1.update_paddle()", I need to pass it some arguments to make the paddle move. But this is where I got confused. (I am just starting to learn python!)
Here is what the update_paddle function looks like:
def update_paddle(self, dx):
self.x += dx
So as you can see, update_paddle just increments the paddle's x position by an input value. But what I'm confused about is, what exactly would I put as the input value?

Maybe you can do something like:
def update_paddle(self, dir, dx):
if dir=='left':
self.x -= dx
elif dir=='right':
self.x += dx
Then you can simply do:
paddle1.update_paddle('left',5)
paddle2.update_paddle('right',3)

Related

Pygame: Is there a way of scrolling the 'coordinate system' of a white-filled display without setting a background image?

I have a game display on which I used the blit-function to display a flight path as well as a drone. The flight path starts from the right side and goes beyond the left side of the display.
The game display is filled white and what I want is to move my drone via pressed keys from right to left along the flight path (which is just a set of contiguous lines connecting random points).
I want the 'coordinate system' of my display to move/scroll so that you can see where the flight path ends. At the same time I want my drone to maintain a static position during that scrolling, e.g. stay in the middle of the screen while it follows the flight path.
Does anybody know a function that allows me to achieve that? All I found in forums and on YouTube seemed rather complex and required one to have set a background image first. I just want the white-filled screen to scroll while I move my drone to the left to follow the red flight path. Below is what I coded so far.
Thank you a lot in advance for any advice!
import pygame
import pygame.gfxdraw
import random
import sys
white = (255,255,255)
display_width = 1200
display_height = 700
game_screen = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('gameScreen')
the_drone = pygame.image.load('drone.png')
X=1000
Y=350
p1=[X, Y]
p2=[X, Y]
p3=[X, Y]
p4=[X, Y]
p5=[X, Y]
pointlist = [p1, p2, p3, p4, p5]
limit1=1000
limit2=850
for i in pointlist:
i[0] = random.randrange(limit2, limit1)
limit1-=300
limit2-=300
for i in pointlist:
if i == 0:
i[1] = random.randrange(200, 600)
else:
range = i[1]-1
i[1] = random.randrange(range-100, range+100)
def flightpath(pointlist):
pygame.draw.lines(game_screen, (255, 0, 0), False, pointlist, 3)
def drone(x,y):
game_screen.blit(the_drone,(X,Y))
def game_loop():
global X, Y
gameExit = False
while not gameExit:
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()
keys = pygame.key.get_pressed() #checking pressed keys
if keys[pygame.K_LEFT]:
X -= 0.5
if keys[pygame.K_DOWN]:
Y -= 0.5
if keys[pygame.K_UP]:
Y +=0.5
game_screen.fill(white)
flightpath(pointlist)
drone(X,Y)
pygame.display.update()
game_loop()
pygame.quit()
sys.exit()
Hi to be hones I don't really understand your Code but I got it working like that:
import pygame
import sys
import random
# init window
def init():
pygame.init()
pygame.display.set_caption("Drone Game")
screen = pygame.display.set_mode((500, 500))
return screen
# make closing the window possible
def escape():
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# draws all objects on screen
def draw(screen, f, y_pos):
screen.fill((50, 50, 50))
for y in range(20):
for x in range(5):
pygame.draw.rect(screen, f[y][x], (x * 100, (y * 100) - y_pos, 100, 100))
pygame.draw.rect(screen, (250, 0, 0), (240, 240, 20, 20)) # drone
pygame.display.update()
# creates background
def field():
f = []
for y in range(20):
f.append([])
for x in range(5):
f[y].append((random.randint(200, 255), random.randint(200, 255), random.randint(200, 255)))
return f
# combines all functions
def main(screen):
f = field()
y_pos = 500
while True:
pygame.time.Clock().tick(30)
escape()
y_pos -= 1
draw(screen, f, y_pos)
# starts program
if __name__ == '__main__':
main(init())
I hope it works for you. :)

Timing the blit of an enemy list in Pygame

Outside of my game loop, I have created a function that creates a list of 200 enemies with random coordinates. These enemies are suppose to start at the top of the screen and then drop down at random speeds. Inside the loop, I use a "for" loop to blit the enemies on screen. It works, but all 200 hundred are spawned and fall at the same time, albeit, at different speeds. So I know I need a timer and herein lies the problem; nothing I do works. Ive tried clock.tick(), pygame.delay(), import time and do the time.time() method. Everything either strobes or the system just crashes. What's causing the problem?
[Code]
import pygame
import sys
import random
import time
pygame.init()
#MAIN GAME
game_screen = pygame.display.set_mode((600, 600))
pygame.display.set_caption("Beer Goggles")
bg = pygame.image.load("bg.png")
bg_image = pygame.transform.scale(bg, (600, 600))
class Object:
def __init__(self, image_path, width, height, x, y):
self.image_path = image_path
self.width = width
self.height = height
self.x = x
self.y = y
player = pygame.image.load(image_path)
self.player_main = pygame.transform.scale(player, (width,height))
def draw(self, background):
background.blit(self.player_main, (self.x, self.y))
#enemies
def enemy():
enemy_list = []
for e in range(200):
x_cor = random.randint(25, 361)
e = Object("enemy.png", 70, 70, x_cor, 25)
enemy_list.append(e)
return enemy_list
#Main Objects
player1 = Object("crate.png", 70, 70, 25, 500)
list1 = enemy()
#ladies
fat_lady = Object("fat_lady.png", 300, 300, 360, 180)
# Main Loop
direction = 0
game_on = True
while game_on:
clock = pygame.time.Clock()
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_on = False
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
direction = 1
elif event.key == pygame.K_LEFT:
direction = -1
elif event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT or event.key == pygame.K_LEFT:
direction = 0
game_screen.fill((0,0,0))
game_screen.blit(bg_image, (0,0))
#title.draw(game_screen)
player1.draw(game_screen)
fat_lady.draw(game_screen)
#move
if direction > 0:
player1.x = player1.x + 10
elif direction < 0:
player1.x = player1.x - 10
#boundaries
if player1.x <= 25:
player1.x = 25
elif player1.x >= 360:
player1.x = 360
#for enemy in list1:
for enemy in list1:
a = random.randint(1, 30)
enemy.draw(game_screen)
enemy.y += a
#collisions
#scoring
pygame.display.update()
quit()
In the code where you create the enemy list you could add a drop start time. Just like you create a random x co-ordinate you could create a time to start dropping it. Then later when you start changing the y position for them (dropping them), you would not start it dropping until after that time had passed.
By the way You have a method enemy() and later you have a loop iterator enemy which will override hide the method by that name. After that point if you tried to call the method enemy() it would fail and you would access the loop iterator instead. It does not affect your code here because you do not try to access the method after creating the loop iterator variable, but it is not a great idea and could cause problems if you later changed the code and did try to access that method. You should be careful about name choices.

How to execute two events in pygame at same time?

I'm trying to make a game where the player can move the main sprite (gran) left right in 3 columns avoiding falling thunderclouds from the sky. Both components work but won't at the same time, so I can either move the player or the thundercloud falls from the top. Please can someone help so both of these events can occur at the same time
Heres my code...
import pygame, sys
import random
import time
from pygame.locals import *
#sets colours for transparency
BLACK = ( 0, 0, 0)
#Sets gran sprite
class Sprite_maker(pygame.sprite.Sprite): # This class represents gran it derives from the "Sprite" class in Pygame
def __init__(self, filename):
super().__init__() # Call the parent class (Sprite) constructor
self.image = pygame.image.load(filename).convert()# Create an image loaded from the disk
self.image.set_colorkey(BLACK)#sets transparrency
self.rect = self.image.get_rect()# Fetchs the object that has the dimensions of the image
#Initilizes pygame game
pygame.init()
pygame.display.set_caption("2nd try")
#sets background
swidth = 360
sheight = 640
sky = pygame.image.load("sky.png")
screen = pygame.display.set_mode([swidth,sheight])
#This is a list of every sprite
all_sprites_list = pygame.sprite.Group()
#Sets thunder list and creates a new thunder cloud and postions it
tcloud_speed = 10
tc_repeat = 0
thunder_list = [0, 120, 240]
for i in range(1):
tx = random.choice(thunder_list)
tcloud = Sprite_maker("thundercloud.png")
tcloud.rect.x = tx
tcloud.rect.y = 0
all_sprites_list.add(tcloud)
#Creates the gran sprite
gran = Sprite_maker("gran.png")
all_sprites_list.add(gran)
gran.rect.x = 120
gran.rect.y = 430
#Movement of gran sprite when left/right pressed
def gran_movement(movex):
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and gran.rect.x == 0:
gran.rect.x = 0
elif event.key == pygame.K_RIGHT and gran.rect.x == 240:
gran.rect.x = 240
elif event.key == pygame.K_LEFT:#left key pressed player moves left 1
gran.rect.x -= 120
elif event.key == pygame.K_RIGHT:#right key pressed player moves left 1
gran.rect.x += 120
return movex
#Main program loop
game_start = True
while game_start == True:
for event in pygame.event.get():
tcloud.rect.y += tcloud_speed
if event.type == pygame.QUIT: #If user clicked close
game_start = False #Exits loop
#Clear the screen and sets background
screen.blit(sky, [0, 0])
#Displays all the sprites
all_sprites_list.draw(screen)
pygame.display.flip()
#Moves gran by accessing gran
gran_movement(gran.rect.x)
#Moves cloud down screen
if tc_repeat == 0:
tcloud.rect.y = 0
time.sleep(0.25)
tc_repeat = 1
else:
tcloud.rect.y += tcloud_speed
pygame.quit()
I'd actually create some pygame.sprite.Sprite subclasses and sprite groups, but since you're not familiar with them, I'll just use pygame.Rects and pygame.Surfaces.
So, create a rect for the player and a list of rects for the clouds. The rects are used as the blit positions (images/surfaces get blitted at the rect.topleft coordinates) and also for the collision detection (colliderect).
To move the clouds, you have to iterate over the cloud_list with a for loop and increment the y coordinate of each rect. That will happen once per frame (iteration of the while loop) and the game will run with 30 frames per second (because of clock.tick(30)).
The player movement (in the event loop) will seemingly take place at the same time as the cloud movement.
import random
import pygame
pygame.init()
# Some replacement images/surfaces.
PLAYER_IMG = pygame.Surface((38, 68))
PLAYER_IMG.fill(pygame.Color('dodgerblue1'))
CLOUD_IMG = pygame.Surface((38, 38))
CLOUD_IMG.fill(pygame.Color('gray70'))
def main():
screen = pygame.display.set_mode((360, 640))
clock = pygame.time.Clock()
# You can create a rect with the `pygame.Surface.get_rect` method
# and pass the desired coordinates directly as an argument.
player_rect = PLAYER_IMG.get_rect(topleft=(120, 430))
# Alternatively create pygame.Rect instances in this way.
cloud_rect = pygame.Rect(120, 0, 38, 38)
# The clouds are just pygame.Rects in a list.
cloud_list = [cloud_rect]
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_d:
player_rect.x += 120
elif event.key == pygame.K_a:
player_rect.x -= 120
remaining_clouds = []
for cloud_rect in cloud_list:
# Move the cloud downwards.
cloud_rect.y += 5
# Collision detection with the player.
if player_rect.colliderect(cloud_rect):
print('Collision!')
# To remove cloud rects that have left the
# game area, append only the rects above 600 px
# to the remaining_clouds list.
if cloud_rect.top < 600:
remaining_clouds.append(cloud_rect)
else:
# I append a new rect to the list when an old one
# disappears.
new_rect = pygame.Rect(random.choice((0, 120, 240)), 0, 38, 38)
remaining_clouds.append(new_rect)
# Assign the filtered list to the cloud_list variable.
cloud_list = remaining_clouds
screen.fill((30, 30, 30))
# Blit the cloud image at the cloud rects.
for cloud_rect in cloud_list:
screen.blit(CLOUD_IMG, cloud_rect)
screen.blit(PLAYER_IMG, player_rect)
pygame.display.flip()
clock.tick(30)
if __name__ == '__main__':
main()
pygame.quit()

cannot convert without pygame.display initialized error in pygame

I'm working on making a game for a project at my university using pygame. All I'm trying to get done right now is create a ball that can be controlled to go back and forth on the screen when the user presses the left and right arrow keys. Honestly I don't really know what I'm doing, so I'm using the code in the pygame documentation that was used for pong as the base for my game. My code is below, and if someone knows why I'm getting the error that's in the title, please let me know.
try:
import sys
import random
import math
import os
import getopt
import pygame
from socket import *
from pygame.locals import *
except ImportError, err:
print "couldn't load module. %s" % (err)
sys.exit(2)
def load_png(name):
""" Load image and return image object"""
fullname = name
try:
image = pygame.image.load(fullname)
if image.get_alpha() is None:
image = image.convert()
else:
image = image.convert_alpha()
except pygame.error, message:
print 'Cannot load image:', fullname
raise SystemExit, message
return image, image.get_rect()
class Ball(pygame.sprite.Sprite):
def __init__(self, (xy)):
pygame.sprite.Sprite.__init__(self)
self.image, self.rect = load_png('ball.png')
screen = pygame.display.get_surface()
self.area = screen.get_rect()
self.hit = 0
self.speed = 10
self.state = "still"
def reinit(self):
self.state = "still"
self.movepos = [0,0]
if self.side == "left":
self.rect.midleft = self.area.midleft
def update(self):
newpos = self.rect.move(self.movepos)
if self.area.contains(newpos):
self.rect = newpos
pygame.event.pump()
def moveleft(self):
self.movepos[1] = self.movepos[1] - (self.speed)
self.state = "moveleft"
def moveright(self):
self.movepos[1] = self.movepos[1] + (self.speed)
self.state = "moveright"
def main():
running = True
pygame.init()
(width, height) = (800, 600)
screen = pygame.display.set_mode((width, height))
# Fill background
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((0, 0, 0))
screen.blit(background, (0, 0))
pygame.display.flip()
global player
player = Ball("left")
playersprite = pygame.sprite.RenderPlain(player)
playersprite.draw(screen)
player.update()
while running:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_q:
running = False
if event.key == K_LEFT:
player.moveleft()
if event.key == K_RIGHT:
player.moveright()
elif event.type == KEYUP:
if event.key == K_UP or event.key == K_DOWN:
player.movepos = [0,0]
player.state = "still"
#screen.blit(background, ball.rect, ball.rect)
screen.blit(background, player.rect, player.rect)
#screen.blit(background, player2.rect, player2.rect)
#ballsprite.update()
playersprite.update()
#ballsprite.draw(screen)
playersprite.draw(screen)
if __name__ == '__main__': main()
All I'm trying to get done right now is create a ball that can be
controlled to go back and forth on the screen when the user presses
the left and right arrow keys.
You are massively over complicating this, you don't need 102 lines to move a ball around. I wrote and commented a simple example that I think could help you a lot. All you really need to do is detect key presses and then update an x and y variable then draw the image using the x and y variables.
import pygame
screen_width = 1280
screen_height = 720
pygame.init()
screen = pygame.display.set_mode((screen_width,screen_height))
BLACK = (0,0,0)
ballImg = pygame.image.load("ball.jpg")
ballPosition = [0,0]
speed = 1
def game_loop():
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
exit()
#get all the keys being pressed
keys = pygame.key.get_pressed()
#depending on what key the user presses, update ball x and y position accordingly
if keys[pygame.K_UP]:
ballPosition[1] -= speed
if keys[pygame.K_DOWN]:
ballPosition[1] += speed
if keys[pygame.K_LEFT]:
ballPosition[0] -= speed
if keys[pygame.K_RIGHT]:
ballPosition[0] += speed
screen.fill(BLACK) #fill the screen with black
screen.blit(ballImg, ballPosition) #draw the ball
pygame.display.update() #update the screen
game_loop()
What versions of python/pygame are you running as when I tested your code with python 3.4, I first got syntax errors with your try: except statements, but this may be due to different syntax over different versions. After fixing that I ran into the issue of movepos not being defined when pressing left or right. Adding self.movepos = [0, 0] to the __init__() of the Ball class fixed this.
I never ran into the error you described, however the game did give a constant black screen no matter what I do.
What I'm trying to say is that errors can sometimes be caused by other mistakes earlier on in the code that don't get picked up. One of the answers here sums it up nicely: error: video system not initialized; Is there a solution?
Also, what variables store the balls x and y position? I couldn't seem to make out how you were controlling that?

Continuous movement of a box in pygame

I have written the following code that creates a simple game where when you click an arrow on the keyboard a box moves a unit over in the game.
I am trying to make it so that if i push any of the arrow buttons the box will continue to move in that direction until another arrow is pushed. So if i push the right arrow once instead of scooting +50 pixels it will move continuously across the screen untill a different arrow is clicked and then it will go that way
import pygame #importing the pygame library
# some initializations
pygame.init() # this line initializes pygame
window = pygame.display.set_mode( (800,600) ) # Create a window with width=800 and height=600
pygame.display.set_caption( 'Rectangle move' ) # Change the window's name we create to "Rectangle move"
clock = pygame.time.Clock() # Clocks are used to track and control the frame-rate of a game (how fast and how slow the pace of the game)
# This line creates and initializes a clock.
# color definitions, using RBG color model.
black = (0,0,0)
white = (255,255,255)
# initial center position for the square (bob)
x,y = 0,0
lastKey=0
game_loop=True
while game_loop:
for event in pygame.event.get(): # loop through all events
if event.type == pygame.QUIT:
game_loop = False # change the game_loop boolean to False to quit.
if event.type == pygame.KEYDOWN:
lastKey = event.key
#check last entered key
#lastKey equals "LEFT", "RIGHT", "UP", "DOWN" --> do the required stuff!
#set x coordinate minus 50 if left was pressed
if lastKey == pygame.K_LEFT:
x -= 50
if lastKey == pygame.K_RIGHT:
x += 50
if lastKey == pygame.K_UP:
y += 50
if lastKey == pygame.K_DOWN:
y -= 50
if event.key == pygame.K_LEFT:
x -= 50
if event.key == pygame.K_RIGHT:
x += 50
if event.key == pygame.K_UP:
y += 50
if event.key == pygame.K_DOWN:
y -= 50
# draw and update screen
window.fill( black ) # fill the screen with black overwriting even bob.
pygame.draw.rect( window, white, (x, y, 50, 50) ) # draw bob on the screen with new coordinates after its movement.
# the parameters are as follows: window: is the window object you want to draw on. white: the object color used to fill the rectangle
# (x,y,50,50) x is the x position of the left side of the rectangle. y is the y position of the upper side of the rectangle.
# In other words (x,y) is the coordinate of the top left point of the rectangle.
# 50 is the width, and 50 is the height
pygame.display.update() #updates the screen with the new drawing of the rectangle.
#fps stuff:
clock.tick(10) # this controls the speed of the game. low values makes the game slower, and large values makes the game faster.
pygame.quit()
any help would be much appreciated.
Try to save the entered key into a variable and check it after your Event-Loop.
Like this:
#...
lastKey = None
while game_loop:
for event in pygame.event.get(): # loop through all events
if event.type == pygame.QUIT:
game_loop = False # change the game_loop boolean to False to quit.
if event.type == pygame.KEYDOWN:
lastKey = event.key
#check last entered key
#lastKey equals "LEFT", "RIGHT", "UP", "DOWN" --> do the required stuff!
#set x coordinate minus 50 if left was pressed
if lastKey == pygame.K_LEFT
x -= 50
#<add the other statements here>
#(...)
I would recommend to not use that many if-statements. It could get a bit confusing after some time.
Check the following question out to keep your code brief:
Replacements for switch statement in Python?
You want to change the state of your application when you press a key. So you need a variable to keep track of that state (the state is: What direction should the box move?).
Here's a complete, minimal example that does what you're looking for. Note the comments.
import pygame, sys
pygame.init()
screen = pygame.display.set_mode((640, 480))
screen_r = screen.get_rect()
clock = pygame.time.Clock()
rect = pygame.rect.Rect(0, 0, 50, 50)
# let's start at the center of the screen
rect.center = screen_r.center
# a dict to map keys to a direction
movement = {pygame.K_UP: ( 0, -1),
pygame.K_DOWN: ( 0, 1),
pygame.K_LEFT: (-1, 0),
pygame.K_RIGHT: ( 1, 0)}
move = (0, 0)
# a simple helper function to apply some "speed" to your movement
def mul10(x):
return x * 10
while True:
for e in pygame.event.get():
if e.type == pygame.QUIT:
sys.exit()
# try getting a direction from our dict
# if the key is not found, we don't change 'move'
if e.type == pygame.KEYDOWN:
move = movement.get(e.key, move)
# move the rect by using the 'move_ip' function
# but first, we multiply each value in 'move' with 10
rect.move_ip(map(mul10, move))
# ensure that 'rect' is always inside the screen
rect.clamp_ip(screen_r)
screen.fill(pygame.color.Color('Black'))
pygame.draw.rect(screen, pygame.color.Color('White'), rect)
pygame.display.update()
clock.tick(60)
I use a Rect instead of keeping track of two coordinates x and y, since that allows to make use of the move_ip and clamp_ip functions to easily move the rect inside the screen.
Here are two versions, the first demonstrates how to utilize an event loop to get continuous movement (similar to Sloth's solution, but a bit simpler for beginners who don't know dictionaries yet), the second one shows how to achieve this with pygame.key.get_pressed().
Solution 1: Check which key was pressed in the event loop and change the x and y velocities to the desired values. Then add the velocities to the rect.x and rect.y positions in the while loop.
I'd actually recommend using vectors instead of the velocity_x and velocity_y variables and another one for the actual position of your sprite. pygame.Rects can't have floats as their coordinates and so a vector or separate variables for the position would be more accurate.
import pygame as pg
def main():
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
rect = pg.Rect(100, 200, 40, 60)
velocity_x = 0
velocity_y = 0
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
elif event.type == pg.KEYDOWN:
if event.key == pg.K_d:
velocity_x = 4
elif event.key == pg.K_a:
velocity_x = -4
elif event.type == pg.KEYUP:
if event.key == pg.K_d and velocity_x > 0:
velocity_x = 0
elif event.key == pg.K_a and velocity_x < 0:
velocity_x = 0
rect.x += velocity_x
rect.y += velocity_y
screen.fill((40, 40, 40))
pg.draw.rect(screen, (150, 200, 20), rect)
pg.display.flip()
clock.tick(30)
if __name__ == '__main__':
pg.init()
main()
pg.quit()
Solution 2: Call pygame.key.get_pressed to check which key is currently being held down. Check if the left, right, up or down keys are held and then adjust the position of the sprite each frame.
pygame.key.get_pressed has the disadvantage that you can't know the order of the key presses, but the code looks a bit simpler.
import pygame as pg
def main():
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
rect = pg.Rect(100, 200, 40, 60)
velocity = (0, 0)
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
keys = pg.key.get_pressed()
if keys[pg.K_d]:
rect.x += 4
if keys[pg.K_a]:
rect.x -= 4
screen.fill((40, 40, 40))
pg.draw.rect(screen, (150, 200, 20), rect)
pg.display.flip()
clock.tick(30)
if __name__ == '__main__':
pg.init()
main()
pg.quit()

Categories