I have a problem with Python and pygame: I have no idea how to make a simple paddle move left and right. Basically I am working on a pong type game for my first project.
After reading a few articles online I thought of a way of how to do this. The code I have so far is:
PADDLE_WIDTH = 50
PADDLE_HEIGHT = 10
paddleSpeedX = 0
p1Paddle = pygame.Rect(10, 430, PADDLE_WIDTH, PADDLE_HEIGHT)
PADDLE_COLOR = pygame.color.Color("red")
while True:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_LEFT:
p1Paddle.right = p1Paddle.left + paddleSpeedX - 10
if event.key == K_RIGHT:
p1Paddle.left = p1Paddle.left + paddleSpeedX + 10
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
pygame.display.update()
After entering this code the game runs but I still cannot move the paddle left and right.
How can I do this?
Pygame raises a KEYDOWN event only once, when you first hit a key.
Unfortunately, it won't continue to raise a KEYDOWN event, so what's happening is that your paddle is jerking over only once, and won't move again unless you keep spamming the left or right key.
Instead, what you could do is set a velocity when you recieve a KEYDOWN event, and set it back to zero when you get KEYUP, like so:
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
p1Paddle.x_velocity = -10
elif event.key == pygame.K_RIGHT:
p1Paddle.x_velocity = 10
if event.type == pygame.KEYUP:
if event.key in [pygame.K_LEFT, pygame.K_RIGHT]:
# if either the left or right arrow keys are released
p1Paddle.x_velocity = 0
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
p1Paddle.x_distance += p1Paddle.x_velocity
# other stuff here
# drawing code here
pygame.display.update()
(I also changed some of your variable names, since I couldn't figure out what p1Paddle.left and p1Paddle.right were -- I hope you don't mind).
I have made some additions and modifications to make your code work.
In each frame (iteration of loop) you must erase the screen and redraw the paddle. This is to make sure the paddle is redrawn with new coordinates when the LEFT/RIGHT arrows are pressed.
Notice that I change p1Paddle.left instead of p1Paddle.right when LEFT is pressed.
import pygame, sys
from pygame import *
pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Paddle Movement')
PADDLE_WIDTH = 50
PADDLE_HEIGHT = 10
paddleSpeedX = 0
p1Paddle = pygame.Rect(10, 430, PADDLE_WIDTH, PADDLE_HEIGHT)
PADDLE_COLOR = pygame.color.Color("red")
while True:
# clear screen with black color
screen.fill( (0,0,0) )
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_LEFT:
p1Paddle.left = p1Paddle.left + paddleSpeedX - 10
if event.key == K_RIGHT:
p1Paddle.left = p1Paddle.left + paddleSpeedX + 10
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
# draw the paddle
screen.fill( PADDLE_COLOR, p1Paddle );
pygame.display.update()
A more elegant solution would be the one below
import pygame, sys
from pygame import *
pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Paddle Movement')
PADDLE_WIDTH = 50
PADDLE_HEIGHT = 10
paddleSpeedX = 0
p1Paddle = pygame.Rect(10, 430, PADDLE_WIDTH, PADDLE_HEIGHT)
PADDLE_COLOR = pygame.color.Color("red")
# clock object that will be used to make the game
# have the same speed on all machines regardless
# of the actual machine speed.
clock = pygame.time.Clock()
while True:
# limit the demo to 50 frames per second
clock.tick( 50 );
# clear screen with black color
screen.fill( (0,0,0) )
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
keys = pygame.key.get_pressed()
if keys[K_LEFT]:
p1Paddle.left = p1Paddle.left + paddleSpeedX - 5
if keys[K_RIGHT]:
p1Paddle.left = p1Paddle.left + paddleSpeedX + 5
# draw the paddle
screen.fill( PADDLE_COLOR, p1Paddle );
pygame.display.update()
Notice that I check the key press using pygame.key.get_pressed(). It allows to make a smooth movement as we check the key state and don't wait for an event to occur.
I added a clock object to limit the frame rate to 50 FPS (frames per second).
Please try both approaches.
Related
I am trying to make a ship on the surface move continuously on screen but it only accepts one key press at a time. I have tried all solutions online and they aren't working.
import pygame
#initialize the pygame module
pygame.init()
#set the window size
screen = pygame.display.set_mode((1280, 720))
#change the title of the window
pygame.display.set_caption("Space Invaders")
#change the icon of the window
icon = pygame.image.load("alien.png")
pygame.display.set_icon(icon)
#add the ship to the window
shipx = 608
shipy = 620
def ship(x, y):
ship = pygame.image.load("spaceship.png").convert()
screen.blit(ship, (x,y))
running = True
while running:
#background screen color
screen.fill((0, 0, 0))
#render the ship on the window
ship(shipx,shipy)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
shipx -= 30
if keys[pygame.K_RIGHT]:
shipx += 30
pygame.display.update()
I'm still new to Pygame. How can I fix this?
Its a matter of Indentation. pygame.key.get_pressed() has to be done in the application loop rather than the event loop. Note, the event loop is only executed when
event occurs, but the application loop is executed in every frame:
running = True
while running:
# [...]
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
#<--| INDENTATION
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
shipx -= 30
if keys[pygame.K_RIGHT]:
shipx += 30
# [...]
The problem that I found is that your application is replying only on one key pressed, not on a continuous movement. When you set the pygame.key.set_repeat function like in the example below, everything should be running smoothly.
import sys
import pygame
#initialize the pygame module
pygame.init()
#set the window size
screen = pygame.display.set_mode((1280, 720))
# Images
ship_img = pygame.image.load("spaceship.png")
ship_rect = ship_img.get_rect()
def draw():
screen.blit(ship_img, ship_rect)
pygame.key.set_repeat(10)
while True:
#background screen color
screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
ship_rect = ship_rect.move((-30, 0))
if keys[pygame.K_RIGHT]:
ship_rect = ship_rect.move((30, 0))
#render the ship on the window
draw()
pygame.display.update()
For me, if I need to move an object in Pygame continuously, a velocity variable can be assigned to control the speed.
Here is part of the code for my robot movement program inside of the game_on loop:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Detect keyboard input on your computer check if it is the direction keys
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
print("Left arrow is pressed")
robotX_speed = -60
if event.key == pygame.K_RIGHT:
print("Right arrow is pressed")
robotX_speed = 60
if event.key == pygame.K_UP:
print("Up arrow is pressed")
robotY_speed = -60
if event.key == pygame.K_DOWN:
print("Down arrow is pressed")
robotY_speed = 60
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
print("Keystoke L/R has been released")
robotX_speed = 0
if event.type == pygame.K_DOWN or event.key == pygame.K_UP:
print("Keystoke Up/Down has been released")
robotY_speed = 0
# update the coordinates in the while loop
robotX += robotX_speed
robotY += robotY_speed
Hope these codes can help you!
So, I got stuck again, but I use this as a last resort when nothing's working after extensive research. Please don't roast me for this, I am a newbie. So, basically I am trying to make my sprite move (yoyo), but the frames keep replicating as the yoyo moves up and down. So, I don't know how to fix that. If the yoyo touches the borders of the game window, it collides and it's supposed to display a text and then the game starts over again. However, when the yoyo collides with the window border, it restarts, but the yoyo that got stuck is still being displayed and a new yoyo appears. The text is displayed but doesn't go away after 2 seconds.
import pygame
import time
pygame.init()
width = 900
height = 900
red = (255,0,0)
text = "game over"
screem = pygame.display.set_mode((width,height))
pygame.display.set_caption("yoyo")
clock = pygame.time.Clock()
background = pygame.image.load("room.png").convert()
win.blit(background, [0,0])
yoyo= pygame.image.load("yoyo.png").convert()
def Yoyo (x,y):
win.blit(yoyo, [x,y])
def mainloop():
x = 87
y = 90
yc = 0
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
Exit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
Yoyo(x,y)
y += yc
if y > 23 or y < -90:
pygame.display.update()
clock.tick(60)
mainloop()
pygame.quit()
quit()
Redraw the entire scene in every frame. This means you've to draw the background in every frame, too.
Draw (blit) the background in the main loop, before anything else is drawn:
while not Exit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
Exit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
y_change = -5
elif event.key == pygame. K_DOWN:
y_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
y_change = 0
y += y_change
if y > 405 or y < -200:
collision()
GameLoop()
win.blit(bg, [0,0]) # <----- draw background
Bee(x,y) # <----- draw the bee on the background
# [...] all further drawing has to be done here
pygame.display.update()
clock.tick(60)
I am making a Pong game in Python. To do this, I am using pygame. I am trying to make an image move continuously on a keypress. I have tried multiple methods, but none have worked. here is my code for the movement:
import pygame, sys
from pygame.locals import *
import time
try: #try this code
pygame.init()
FPS = 120 #fps setting
fpsClock = pygame.time.Clock()
#window
DISPLAYSURF = pygame.display.set_mode((1000, 900), 0, 32)
pygame.display.set_caption('Movement with Keys')
WHITE = (255, 255, 255)
wheatImg = pygame.image.load('gem4.png')
wheatx = 10
wheaty = 10
direction = 'right'
pygame.mixer.music.load('overworld 8-bit.WAV')
pygame.mixer.music.play(-1, 0.0)
#time.sleep(5)
#soundObj.stop()
while True: #main game loop
DISPLAYSURF.fill(WHITE)
bign = pygame.event.get()
for event in bign:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_d:
pygame.mixer.music.stop()
keys_pressed = key.get_pressed()
if keys_pressed[K_d]:
wheatx += 20
#events = pygame.event.get()
#for event in events:
# if event.type == pygame.KEYDOWN:
# if event.key == pygame.K_p:
# pygame.mixer.music.stop()
# time.sleep(1)
# pygame.mixer.music.load('secondscreen.wav')
# pygame.mixer.music.play()
DISPLAYSURF.blit(wheatImg, (wheatx, wheaty))
pygame.display.update()
fpsClock.tick(FPS)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
Indentation is normal, I am new to stackoverflow! I have an except, which is why the try is there. Thanks for the help!
This code will move the image down upon the down arrow key being pressed and up if the up arrow key is pressed (should you not be changing the Y-axis and wheaty if the user presses the down key rather than altering wheatx ?). Do similar for the other arrow keys.
while True:
DISPLAYSURF.fill(WHITE)
bign = pygame.event.get()
for event in bign:
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
pygame.mixer.music.stop()
if event.key == pygame.K_DOWN:
wheaty +=20
elif event.key == pygame.K_UP:
wheaty -= 20
DISPLAYSURF.blit(wheatImg, (wheatx, wheaty))
pygame.display.update()
fpsClock.tick(FPS)
I am making a spaceship invaders game in python 3 with pygame. I am currently having troubles with the spaceship sticking making me double tap a left or right arrow key for it to take effect. Here is my code:
import pygame
pygame.init()
display_width = 800
display_height = 600
black = (0, 0, 0)
white = (255, 255, 255)
#Window Size
gameDisplay = pygame.display.set_mode((display_width, display_height))
#Title Of Window
pygame.display.set_caption('A Bit Racey')
#FPS
clock = pygame.time.Clock()
spaceshipImg = pygame.image.load('SpaceShipSmall.png')
def spaceship(x,y):
gameDisplay.blit(spaceshipImg, (x,y))
x = (display_width * 0.45)
y = (display_height * 0.8)
x_change = 0
crashed = False
while not crashed:
# this will listen for any event every fps
for event in pygame.event.get():
if event.type == pygame.QUIT:
#change later
crashed = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
elif 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
x += x_change
gameDisplay.fill(white)
spaceship(x,y)
pygame.display.update()
clock.tick(60)
pygame.quit()
quit()
Every time a pygame.KEYUP event is detected for the left or right arrow key you reset x_change. Even when you hold down e.g. your right arrow key a single left arrow key press stops the movement of your spaceship.
To solve this problem you could use the pygame.key.get_pressed() method to get the state of all keyboard buttons. This function returns a sequence of boolean values indexed by pygames key constant values representing the state of every key on the keyboard.
Because you donĀ“t need to call pygame.key.get_pressed() every time an event happens, the updated main loop should look like this:
while not crashed:
# this will listen for any event every fps
for event in pygame.event.get():
if event.type == pygame.QUIT:
#change later
crashed = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
#get the state of all keyboard buttons
pressedKeys = pygame.key.get_pressed()
#change position if pygame.K_LEFT or pygame.K_RIGHT is pressed
if pressedKeys[pygame.K_LEFT]:
x += -5
elif pressedKeys[pygame.K_RIGHT]:
x += 5
gameDisplay.fill(white)
spaceship(x,y)
pygame.display.update()
clock.tick(60)
Notice that a pygame.K_LEFT event has a higher priority than a pygame.K_RIGHT event. You could change this behavior by using two separate if blocks. Many thanks to #sloth for pointing this out!:
#change position if either pygame.K_LEFT or pygame.K_RIGHT is pressed
if pressedKeys[pygame.K_LEFT]:
x += -5
if pressedKeys[pygame.K_RIGHT]:
x += 5
I hope this helps you :)
add the following statement before x += x_change:
print (event.type, event.key, x)
this will print the event data and x position to the console.
try your script again, try holding down the left key for 3 seconds, then release, and repeat for the right key. See if you see multiple keydown events while holding down the keys. I think you should only see one keyup event upon release.
I am attempting to make a game where the 'player' (who spawns as the moon furthest to the right) can move around using the 'WASD' keys and enemies fall from the top of the screen in order to hit the player and end the game. I am currently doing this for an assignment and i have set up a test to see whether it is possible for me to do this and so far i have been able to create a 'player' object that is controllable by the 'WASD' keys and make a screen which requires players to press 'SPACE' to play the game. I am having trouble though with being able to have the enemies fall on the 'Y' axis down the screen smoothly. The picture moves down the screen only when the user presses or releases a key, this creates a jagged movement or when the user moves the mouse over the pygame screen, creating a very smooth movement.
#import necessary modules and pygame.
import pygame, sys, random
from pygame.locals import *
#set global variables
pygame.init()
WINDOWWIDTH = 800
WINDOWHEIGHT = 800
BACKGROUNDCOLOUR = (255,255,255)
TEXTCOLOUR = (0,0,0)
FPS = 30
ENEMYMINSIZE = 10
BOMBSAWAY = -1
ENEMYMAXSIZE = 40
ENEMYMINSPEED = 1
ENEMYMAXSPEED = 10
ADDNEWENEMYRATE = 5
PLAYERMOVERATE = 5
FSIZE = 48
BLUE = (0,0,255)
global PLAY
PLAY = False
global fpsClock
fpsClock = pygame.time.Clock()
# set up pygame and GUI
MainClock = pygame.time.Clock()
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
windowSurface.fill(BACKGROUNDCOLOUR)
pygame.display.set_caption('Bubble Dash')
enemy = pygame.image.load('player.jpg')
char = pygame.image.load('player.jpg')
# set up fonts
basicFont = pygame.font.SysFont(None, 48)
# set up the text
text = basicFont.render('Press any key to play!', True, (255,255,0))
textRect = text.get_rect()
textRect.centerx = windowSurface.get_rect().centerx
textRect.centery = windowSurface.get_rect().centery
# draw the text onto the surface
# set up x and y coordinates
# music
windowSurface.blit(text, textRect)
def playgame(PLAY):
x,y = 0,0
movex,movey = 0,0
charx=300
chary=200
direction = 'down'
enemyx= 10
enemyy=10
while PLAY:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == ord('m'):
pygame.mixer.music.stop()
if event.key == ord('n'):
pygame.mixer.music.play()
if event.key == ord('a'):
movex = -0.5
if event.key == ord('d'):
movex = 0.5
if event.key == ord('w'):
movey = -0.5
if event.key == ord('s'):
movey = 0.5
if event.type ==KEYUP:
if event.key == ord('a'):
movex = 0
if event.key == ord('d'):
movex = 0
if event.key == ord('w'):
movey = 0
if event.key == ord('s'):
movey = 0
if direction == 'down':
enemyy += 7
windowSurface.fill(BLUE)
windowSurface.blit(char, (charx, chary))
windowSurface.blit(enemy, (enemyx, enemyy))
pygame.display.update()
charx+=movex
chary+=movey
def playertopresskey(PLAY):
while True: # main game loop
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_SPACE:
PLAY = True
if PLAY == True:
playgame(PLAY)
pygame.display.update()
playertopresskey(PLAY)
I would like for the 'enemy' object to be able to fall from the top without the user either needing to keypress or to key up or to have to move the mouse on the screen, rather the 'enemy' would just fall from the top as soon as the subroutine is called.
You may need to tweak it a bit because it is set up for me at the moment but i deleted a few things that would give you bother. Hopefully someone can help me. Thanks.
The below is link to a picture similar to mine which you can download and replace in the code for both the 'char' and the 'enemy' variables to view this yourself for i cannot access the courses at the present time.
http://www.roleplaygateway.com/roleplay/the-five-elements/characters/miss-joy/image
I found your error, you would have caught it yourself if you would have divided your code into some functions. Here is the problem:
for event in pygame.event.get():
if event.type == QUIT:
...
if event.type == KEYDOWN:
...
if event.type == KEYUP:
...
if direction == 'down':
enemyy += 7
your code moving the enemy is called only when an event is waiting in the queue. Move it out of the loop, and you will be good to go.
You have to change indention for:
if direction == 'down':
enemyy += 7
Now it is inside for event in pygame.event.get():