I am a beginner of pygame. Recently I code a Pong game.
However, I cannot make paddles move when I press the certain keys in keyboard. Can someone helps me check the code. I think maybe I have some problems in giving paddles' new position. But I cannot fix it. And hopefully give me some hints about that.
Thanks!
Code below:
import pygame, sys, time,math
from pygame.locals import *
# User-defined functions
def main():
# Initialize pygame
pygame.init()
# Set window size and title, and frame delay
surfaceSize = (500, 400) # window size
windowTitle = 'Pong' #window title
frameDelay = 0.005 # smaller is faster game
# Create the window
pygame.key.set_repeat(20, 20)
surface = pygame.display.set_mode(surfaceSize, 0, 0)
pygame.display.set_caption(windowTitle)
# create and initialize red dot and blue dot
gameOver = False
color1=pygame.Color('white')
center1 = [250, 200]
radius1=10
score=[0, 0]
speed1=[4,1]
location1=[50, 150]
location2=[450, 150]
size=(5, 100)
position1=(0,0)
position2=(350,0)
rect1=pygame.Rect(location1,size)
rect2=pygame.Rect(location2,size)
# Draw objects
pygame.draw.circle(surface, color1, center1, radius1, 0)
# Refresh the display
pygame.display.update()
# Loop forever
while True:
# Handle events
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
# Handle additional events
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
location1[1] =+ 1
if event.key == pygame.K_p:
location2[1] =+ 1
if event.key == pygame.K_a:
location1[1] =- 1
if event.key == pygame.K_i:
location2[1] =- 1
if event.type == pygame.KEYUP:
if event.key == pygame.K_q:
location1[1] =+ 0
if event.key == pygame.K_p:
location2[1] =+ 0
if event.key == pygame.K_a:
location1[1] =- 0
if event.key == pygame.K_i:
location2[1] =- 0
# Handle additional events
# Update and draw objects for the next frame
gameOver = update(surface,color1,center1,radius1,speed1,rect1,rect2,score,position1,position2)
# Refresh the display
pygame.display.update()
# Set the frame speed by pausing between frames
time.sleep(frameDelay)
def update(surface,color1,center1,radius1,speed1,rect1,rect2,score,position1,position2):
# Check if the game is over. If so, end the game and
# returnTrue. Otherwise, erase the window, move the dots and
# draw the dots return False.
# - surface is the pygame.Surface object for the window
eraseColor=pygame.Color('Black')
surface.fill(eraseColor)
moveDot(surface,center1,radius1,speed1,score,position1,position2)
pygame.draw.circle(surface,color1,center1,radius1,0)
r1=pygame.draw.rect(surface, color1, rect1)
r2=pygame.draw.rect(surface, color1, rect2)
if r1.collidepoint(center1) and speed1[0]<0:
speed1[0]=-speed1[0]
if r2.collidepoint(center1) and speed1[0]>0:
speed1[0]=-speed1[0]
def moveDot(surface,center,radius,speed,score,position1,position2):
#Moves the ball by changing the center of the ball by its speed
#If dots hits left edge, top edge, right edge or bottom edge
#of the window, the then the ball bounces
size=surface.get_size()
for coord in range(0,2):
center[coord]=center[coord]+speed[coord]
if center[coord]<radius:
speed[coord]=-speed[coord]
if center[coord]+radius>size[coord]:
speed[coord]=-speed[coord]
if center[0]<radius:
score[0]=score[0]+1
drawScore(center,surface,score,position2,0)
if center[0]+radius>size[0]:
score[1]=score[1]+1
drawScore(center,surface,score,position1,1)
def drawScore(center1,surface,score,position,whichscore):
FontSize=30
FontColor=pygame.Color('White')
String='Score : '
font=pygame.font.SysFont(None, FontSize, True)
surface1=font.render(String+str(score[whichscore]), True, FontColor,0)
surface.blit(surface1,position)
main()
You always use the rects rect1 and rect2 to draw your paddles. But to update their position, you try to change values in the lists location1 and location2.
Stop it. Just alter the rects. The easiest way is to use move_ip to change the rects in place.
Also, if you want to keep your paddles moving while the players keep the movement keys pressed, use pygame.key.get_pressed to get a list of all pressed keys (since pressing a key only generates a single KEYDOWN event, unless you mess with pygame.key.set_repeat, which you shouldn't).
So your code should look like this:
...
while True:
# Handle events
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
pressed = pygame.key.get_pressed()
if pressed[pygame.K_q]: rect1.move_ip(0, -1)
if pressed[pygame.K_a]: rect1.move_ip(0, 1)
if pressed[pygame.K_p]: rect2.move_ip(0, -1)
if pressed[pygame.K_i]: rect2.move_ip(0, 1)
gameOver = ...
...
Related
I am trying to make code to move a rectangle by pressing a key. In my code I made a while loop to keep drawing a rectangle that moves to the right in steps of 10 pixels but my progrem only shows the drawing execution of the end of the while loop.
Does anybody knows what I am doing wrong or how to fix it.
See my code below:
x=10
pygame.draw.rect(DISPLAYSURF, GREEN, (0, 10, 10,10))
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
while x<=380:
pygame.time.wait(100)
x = x + 20
print(x)
DISPLAYSURF.fill(BLACK)
pygame.draw.rect(DISPLAYSURF, GREEN, (x, 10, 10,10))
pygame.display.update()
See Pygame window not responding after a few seconds.
Note, the display is updated when pygame.display.update(), but to make the timing and display update proper work, you've to handle the events between the updates of the display by either pygame.event.get() or pygame.event.pump(). Avoid loops which do some drawing inside the game loop. Use the game loop to perform the animations.
You don't need the inner while loop at all. You've a game loop. Add a state move and initialize it by False.
move = False
When the key is pressed then change the state to True:
if event.key == pygame.K_RIGHT:
move = True
If move is stated and as long x <= 380 increment x:
while True:
# [...]
if move and x <= 380:
x += 20
The game loop should look like this:
x = 0
move = False
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
move = True
if move and x <= 380:
x += 20
pygame.time.wait(100)
DISPLAYSURF.fill(BLACK)
pygame.draw.rect(DISPLAYSURF, GREEN, (x, 10, 10,10))
pygame.display.update()
You need to do do pygame.display.update() every time you draw. Move that line to be called inside your while loop after pygame.draw.rect
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 struggling with pygame. I want my player to move and face right or left when I press the right or left key respectively. Instead it just flips. I don't know how to make it point to the left, or right and then walk.
run = True
while run:
for event in pg.event.get():
if event.type == pg.QUIT:
run = False
if event.type == pg.KEYDOWN:
if event.key == pg.K_RIGHT:
swordsman = pg.transform.flip(swordsman, True, False)
x += speed
if event.key == pg.K_LEFT:
swordsman = pg.transform.flip(swordsman, True, False)
x -= speed
You can either check the state of the keys with pg.key.get_pressed() to see if ← or → are pressed (as in the example below) or alternatively, change the speed variable to another value in the event loop and then change the x position (x += speed) each frame in the while loop not in the event loop (reset speed to 0 when the key is released).
With regard to the image flipping, keep a reference to the original image and assign it to the swordsman variable. When the player wants to move in the other direction, flip the original image and assign it (just assign the original image if they move in the original direction).
import pygame as pg
pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
# This is the original swordsman image/surface (just a
# rectangular surface with a dark topleft corner).
SWORDSMAN_ORIGINAL = pg.Surface((30, 50))
SWORDSMAN_ORIGINAL.fill((50, 140, 200))
pg.draw.rect(SWORDSMAN_ORIGINAL, (10, 50, 90), (0, 0, 13, 13))
# Assign the current swordsman surface to another variable.
swordsman = SWORDSMAN_ORIGINAL
x, y = 300, 200
speed = 4
run = True
while run:
for event in pg.event.get():
if event.type == pg.QUIT:
run = False
elif event.type == pg.KEYDOWN:
if event.key == pg.K_RIGHT:
# When the player presses right, flip the original
# and assign it to the current swordsman variable.
swordsman = pg.transform.flip(SWORDSMAN_ORIGINAL, True, False)
elif event.key == pg.K_LEFT:
# Here you can just assign the original.
swordsman = SWORDSMAN_ORIGINAL
# Check the state of the keys each frame.
keys = pg.key.get_pressed()
# Move if the left or right keys are held.
if keys[pg.K_LEFT]:
x -= speed
elif keys[pg.K_RIGHT]:
x += speed
screen.fill(BG_COLOR)
screen.blit(swordsman, (x, y))
pg.display.flip()
clock.tick(60)
pg.quit()
Is a swordsman a pygame.Sprite object? If it is, it should contain a pygame.Rect object in itself. Variable x is just a single variable, and its change has no effect on your swordsman. Try swordsman.rect.x = x
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():
I am new to pygame and I am trying to make pong in order to learn it. I am trying to make smooth controls so that holding down an arrow will work, but it is not working right now.
import sys, pygame
pygame.init()
size = (500, 350)
screen = pygame.display.set_mode(size)
x = 1
xwid = 75
yhei = 5
pygame.key.set_repeat(0, 500)
while True:
vector = 0
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
vector = 4
elif event.key == pygame.K_LEFT:
vector = -4
pygame.draw.rect(screen,(255,255,255),(x,size[1] - yhei,xwid,yhei),0)
pygame.display.update()
screen.fill((0,0,0))
x += vector
if x <= 0:
x = 0
elif x >= size[0] - xwid:
x = size[0] - xwid
why does this not work for holding down the left or right arrows?
pygame.key.set_repeat(0, 500)
If you set the delay parameter to 0, key repeat will be disabled. The documentation isn't quite clear about that:
pygame.key.set_repeat()
control how held keys are repeated
set_repeat() -> None
set_repeat(delay, interval) -> None
When the keyboard repeat is enabled, keys that are held down will generate
multiple pygame.KEYDOWN events. The delay is the number of
milliseconds before the first repeated pygame.KEYDOWN will be sent.
After that another pygame.KEYDOWN will be sent every interval
milliseconds. If no arguments are passed the key repeat is disabled.
When pygame is initialized the key repeat is disabled.
Emphasis mine.
You could set the delay to 1, and it would work as expected:
pygame.key.set_repeat(1, 10) # use 10 as interval to speed things up.
But note that you should not use set_repeat and the pygame.KEYDOWN event to implement movement. If you do, you won't be able to observe real single key strokes, since if the player presses a key, a whole bunch of pygame.KEYDOWN events would be created.
Better use pygame.key.get_pressed(). Have a look at his minimal example:
import pygame
pygame.init()
screen = pygame.display.set_mode((680, 460))
clock = pygame.time.Clock()
# use a rect since it will greatly
# simplify movement and drawing
paddle = pygame.Rect((0, 0, 20, 80))
while True:
if pygame.event.get(pygame.QUIT): break
pygame.event.pump()
# move up/down by checking for pressed keys
# and moving the paddle rect in-place
keys = pygame.key.get_pressed()
if keys[pygame.K_UP]: paddle.move_ip(0, -7)
if keys[pygame.K_DOWN]: paddle.move_ip(0, 7)
# ensure the paddle rect does not go out of screen
paddle.clamp_ip(screen.get_rect())
screen.fill((0,0,0))
pygame.draw.rect(screen, (255,255,255), paddle)
pygame.display.flip()
clock.tick(60)
try it !
pygame.key.set_repeat(1,500)
I know what do you mean. Try this:
import sys, pygame
from pygame.locals import *
pygame.init()
size = (500, 350)
screen = pygame.display.set_mode(size)
x = 1
xwid = 75
yhei = 5
clock = pygame.time.Clock()
while True:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
key_pressed = pygame.key.get_pressed()
if key_pressed[K_LEFT]:
x -= 4
if x <= 0:
x = 0
if key_pressed[K_RIGHT]:
x += 4
if x >= size[0] - xwid:
x = size[0] - xwid
pygame.draw.rect(screen,(255,255,255),(x,size[1] - yhei,xwid,yhei),0)
pygame.display.update()
screen.fill((0,0,0))