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
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm making Mario with pygame for my class assessment this school term and am sorta new to pygame, i can't find anywhere how to properly implement gravity into my game, so when mario jumps, he comes back down. My second problem is trying to make a running animation, i want Mario to flick through pictures as he moves left and right in the order; 1, 2, 3, 2 (and over and over). If someone could help it would be great!
import pygame
import time
import random
pygame.init()
display_width = 800
display_height = 600
mario_width = 55
blue = (77, 240, 255)
green = (0, 186, 43)
ground_colour = (186, 150, 97)
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Super Italiano Bros")
direction = 'right'
clock = pygame.time.Clock()
cloudImg = pygame.image.load('Cloud.png')
rightMarioImg = pygame.image.load('MarioRight.png')
rightMarioImg2 = pygame.image.load("MarioRight2.png")
rightMarioImg3 = pygame.image.load("MarioRight3.png")
leftMarioImg = pygame.image.load('MarioLeft.png')
leftMarioImg2 = pygame.image.load('MarioLeft2.png')
leftMarioImg3 = pygame.image.load('MarioLeft3.png')
def marioRight(x,y):
gameDisplay.blit(rightMarioImg, (x,y))
def marioLeft(x,y):
gameDisplay.blit(leftMarioImg, (x,y))
def cloud(x_cloud,y_cloud):
gameDisplay.blit(cloudImg, (x_cloud,y_cloud))
def cloud_two(x_cloud_two,y_cloud_two):
gameDisplay.blit(cloudImg, (x_cloud_two,y_cloud_two))
def game_loop():
global direction
x = (320)
y = (360)
x_cloud = (-200)
y_cloud = (-220)
x_cloud_two = (200)
y_cloud_two = (-170)
x_change = (0)
y_change = (0)
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
print(event)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
direction = 'left'
if event.key == pygame.K_RIGHT:
x_change = 5
direction = 'right'
if event.key == pygame.K_UP:
y_change = -60
if event.key == pygame.K_ESCAPE:
gameExit = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == pygame.K_UP:
x_change = 0
y_change = 60
x += x_change
y += y_change
if x <= 0:
x = 0
if y <= 300:
y = 300
if y >= 360:
y = 360
gameDisplay.fill(blue)
pygame.draw.rect(gameDisplay, ground_colour, (0,500,800,500))
pygame.draw.rect(gameDisplay, green, (0, 470, 800, 30))
cloud(x_cloud,y_cloud)
cloud_two(x_cloud_two,y_cloud_two)
if direction == 'right':
marioRight(x,y)
else:
marioLeft(x,y)
pygame.display.update()
clock.tick(60)
game_loop()
pygame.quit()
quit()
Fixed some issues and did a lot of code styling. When you press the up key he jumps a fixed amount and when you release it he goes back to the ground level. Now it animates itself. The image is changed every loop, which is probably super fast, so you will probably only want to increase the state every a certain amount of frames.
Summary of what I changed:
Imports are usually grouped in three different blocks (divided by a single blank line) and ordered alphabetically:
The first block contains all standard library imports
The second block contains third party libraries
The third block contains local imports to other files in this project
A file should have 0 not used imports
Function and variable names in python follow snake case notation: my_variable and my_function. "Constants" are written in snake upper case: MY_CONSTANT. Classes use camel case: MyClass.
dicts and lists allow you to store data in a more organized way. For example, we can have a MARIO_IMGS dict of lists that store all the mario images so they can be accessed like MARIO_IMGS['right'][0] (the first image is index 0 as lists start counting by 0).
Try to avoid global variables, I moved the variables that were only needed inside the loop to the game_loop function and the remaining top level statements that were not definitions isnide a if __name__ == '__main__': block that runs whenever this script is launched but not when this scrip is imported.
Functions are meant to be reused, having cloudand cloud_two functions that do exactly the same makes no sense. Call cloud(x_cloud, y_cloud) and then cloud(x_cloud_two, y_cloud_two).
Do not use unneeded brackets if they do not provide clarity, for example: x = (320) should be x = 320
You had a indentation error where you process events outside the event loop, so only the last event would be processed (except for exiting, that part was inside the loop so every event would be checked against pygame.QUIT)
Lines should be 80 chars or lower.
quit() at the end of a python file is not needed. quit() is mostly used to close the python interpreter from a terminal window.
import pygame
# Window width and height in px
DISPLAY_SIZE = (800, 600)
# Window title
TITLE = "Super Italiano Bros"
# Predefined colors
BLUE = (77, 240, 255)
GREEN = (0, 186, 43)
GROUND_COLOR = (186, 150, 97)
# Images
MARIO_IMGS = {
'right': [
pygame.image.load('MarioRight.png'),
pygame.image.load("MarioRight2.png"),
pygame.image.load("MarioRight3.png"),
pygame.image.load("MarioRight2.png"),
],
'left': [
pygame.image.load('MarioLeft.png'),
pygame.image.load('MarioLeft2.png'),
pygame.image.load('MarioLeft3.png'),
pygame.image.load('MarioLeft2.png'),
]
}
CLOUD_IMG = pygame.image.load('Cloud.png')
MAX_STATES = min(map(len, MARIO_IMGS.values())) # 3
def draw_mario(x, y, direction='right', state=0):
screen.blit(MARIO_IMGS[direction][state], (x, y))
def draw_cloud(x_cloud, y_cloud):
screen.blit(CLOUD_IMG, (x_cloud, y_cloud))
def game_loop():
# Mario position
x = 320
y = 360
x_change = 0
state = 0
direction = 'right'
# Cloud positions
x_cloud = -200
y_cloud = -220
x_cloud_two = 200
y_cloud_two = -170
# Clock used to limit the FPS
clock = pygame.time.Clock()
game_exit = False
while not game_exit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_exit = True
print(event)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
direction = 'left'
if event.key == pygame.K_RIGHT:
x_change = 5
direction = 'right'
if event.key == pygame.K_UP:
y = 300
if event.key == pygame.K_ESCAPE:
game_exit = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
elif event.key == pygame.K_UP:
y = 360
x += x_change
if x < 0:
x = 0
elif x > DISPLAY_SIZE[0]:
x = DISPLAY_SIZE[0]
screen.fill(BLUE)
pygame.draw.rect(screen, GROUND_COLOR, (0, 500, 800, 500))
pygame.draw.rect(screen, GREEN, (0, 470, 800, 30))
draw_cloud(x_cloud, y_cloud)
draw_cloud(x_cloud_two, y_cloud_two)
draw_mario(x, y, direction, state)
# Increase the state to animate Mario
state += 1
state %= MAX_STATES # Start back from 0 if we have reached the end
pygame.display.update()
clock.tick(60)
if __name__ == '__main__':
pygame.init()
screen = pygame.display.set_mode(DISPLAY_SIZE)
pygame.display.set_caption(TITLE)
game_loop()
pygame.quit()
You should probably change your mario and cloud to Sprites. An Sprite is a class that has a rect and an image attributes that define how they are drawn, and then instead of using screen.blit(IMAGE, POSITION) you just tell pygame to draw the sprite and he will use those two attributes to draw the desired image at the position of the rect.
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 = ...
...
I have my image moving correctly when I put in the inputs, but since I need the image to quit moving when I let go of the key, I naturally used pygame.KEYUP to make all movement stop. However, this leads to choppy gameplay because if you even hit a button a fraction of a second before you let off the one you were holding, your character stops all together, and sometimes it feels like it happens even when I do let off the button in time, though I suppose that could just be on me. Is there another way I can code the movement so that this isn't a problem?
I use:
if event.type == KEYDOWN:
if event.key == ord('d'):
Right = True
if event.type == KEYUP:
if event.key == ord('d'):
Right = False
(Somewhere else in the code...)
if Right == True:
PlayerX += 10
(Then)
screen.blit(PlayerImage,(PlayerX,PlayerY))
Just stop using events for movement.
Simply use pygame.key.get_pressed() to check which keys are pressed, then alter the position of your game object accordingly.
Here's a minimal example of a moving monkey:
import base64, pygame, math
from pygame.locals import *
def magnitude(v):
return math.sqrt(sum(v[i]*v[i] for i in range(len(v))))
def add(u, v):
return [ u[i]+v[i] for i in range(len(u)) ]
def normalize(v):
vmag = magnitude(v)
return [ v[i]/vmag for i in range(len(v)) ]
pygame.init()
size = width, height = 640, 480
screen = pygame.display.set_mode(size)
img = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAgFRg8JRdZOyQYVj4lGSkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAArKysGPCMWiTwkFTg9JBfsPCQX4DwkFT07JBe9OiQWIwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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AAAAlHFTfv7QnvTswJL8p4RkbgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALONaZbU0J7TTtCeTTnMmTUifl1HAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPCQXAF9EMABnTDYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKqFZQD1yJgAAAAAAAAAAAAAAAAAsItniT7QnvTU0J7T98qZT6uFY3cAAAAAAAAAAAAAAAAAAAAAAAAAALiSba3U0J7TTtCeTT7QnvU6k2UxAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAlHFTAP7QngDswJIAp4RkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAALONaQDU0J4AAAAAAAAAAAAAAAAAqINhYf7QnvTU0J7TTtCeT7yWcLgAAAAAAAAAAAAAAAAAAAAAAAAAALSMaJX8zp3T7cCSTLmSbqukgFsOAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAsItnAP7QngDU0J4A98qZAKuFYwAAAAAAAAAAAAAAAAAAAAAAAAAAALiSbQDU0J4AAAAAAAAAAAAAAAAApoVZFTbJmfT0yJfUwp12zQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACZc1kUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAqINhAP7QngDU0J4ATtCeALyWcAAAAAAAAAAAAAAAAAAAAAAAAAAAALSMaAD8zp0AAAAAAAAAAAAAAAAAAAAAAKOAX06ogF4mAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAApoVZAPbJmQD0yJcAwp12AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACZc1kA'
player = pygame.image.fromstring(base64.b64decode(img, 'UTF-8'), (36, 56), 'RGBA')
player_rect = player.get_rect()
# define which keys move the monkey in which direction
move_map = {pygame.K_w: ( 0, -1),
pygame.K_s: ( 0, 1),
pygame.K_a: (-1, 0),
pygame.K_d: ( 1, 0)}
def main():
running = True
clock = pygame.time.Clock()
while running:
screen.fill(pygame.Color("darkgreen"))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# get all pressed keys
pressed = pygame.key.get_pressed()
# get all directions the monkey should move
move = [move_map[key] for key in move_map if pressed[key]]
# add all directions together to get the final direction
reduced = reduce(add, move, (0, 0))
if reduced != (0, 0):
# normalize the target direction and apply a speed
move_vector = [c * 5 for c in normalize(reduced)]
# move the monkey...
player_rect.move_ip(*move_vector)
# ...but keep it inside the screen
player_rect.clamp_ip(screen.get_rect())
screen.blit(player, player_rect)
pygame.display.flip()
clock.tick(60)
if __name__ == '__main__':
main()
I am trying to create a game where "player_one.png" is controlled by the arrow keys to move around and dodge a bunch of randomly placed "player_two.png" that can move around on their own in random directions on a football field.
I have created a program that displays the field and the two images. I am having difficulty getting "player_two.png" display multiple copies on the field and cannot get them to move.
I also cannot get the "player_one.png" image to move based on the arrow key. I found a program using Sprites that moves a red block in the same way I want my player to move but cannot switch out the sprite with my image.
Here is my initial set-up which displays the field and the two images facing each other.
import pygame
import random
pygame.init()
#colors
black = (0, 0, 0)
white = (255, 255, 255)
green = (0, 100, 0)
red = (255, 0, 0)
size = [1000, 500]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Tony's newest game attempt")
#boolean for while loop
done = False
#create clock
clock = pygame.time.Clock()
#declare font
font = pygame.font.Font(None, 25)
player_one = pygame.image.load("player_one.png").convert()
player_one.set_colorkey(white)
player_two = pygame.image.load("player_two.png").convert()
player_two.set_colorkey(white)
while done == False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
screen.fill(green)
for x in range(60,940,35):
pygame.draw.line(screen, white, [x, 0], [x, 500], 1)
score = 0
text = font.render("Score:" +str(score), True, black)
screen.blit(text, [0, 0])
screen.blit(player_one, [940, 240])
screen.blit(player_two, [60, 240])
pygame.display.flip()
clock.tick(20)
pygame.quit()
The sprite program that uses a class (something I could not get to work with images) moves the Player sprite using this code: (Please note this is not the entire program).
class Player(pygame.sprite.Sprite):
# Constructor function
def __init__(self, color, x, y):
# Call the parent's constructor
pygame.sprite.Sprite.__init__(self)
# Set height, width
self.image = pygame.Surface([35, 35])
self.image.fill(color)
# Make our top-left corner the passed-in location.
self.rect = self.image.get_rect()
self.rect.x = 930
self.rect.y = 250
def reset_player(self):
self.rect.x = 930
self.rect.y = 250
# Find a new position for the player
def update(self):
self.rect.x += self.change_y
self.rect.y += self.change_x
while done == False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done=True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.rect.x -= player.rect.width
elif event.key == pygame.K_RIGHT:
player.rect.x += player.rect.width
elif event.key == pygame.K_UP:
player.rect.y -= player.rect.height
elif event.key == pygame.K_DOWN:
player.rect.y += player.rect.height
# -- Draw everything
# Clear screen
screen.fill(green)
for x in range(60,940,35):
pygame.draw.line(screen, white, [x, 0], [x, 500], 1)
# Draw sprites
all_sprites_list.draw(screen)
text = font.render("Score: "+str(score), True, black)
screen.blit(text, [10, 10])
# Flip screen
pygame.display.flip()
# Pause
clock.tick(20)
pygame.quit()
Can someone please help me figure out how to get my image to move the way the sprite does. Or help me display "player_two.png" all over the field and move in random directions. It would be best if the "player_two.png" moved every once every 3 times I hit an arrow key. If this is vague please email me and I can send my code. I need to finish this game in 2 weeks!
Multiple comments on the game -
I don't see where self.change_y is defined. Also, shouldn't the update function be like - self.rect.x += self.change_x instead of self.rect.x += self.change_y?
Also, the main loop should be something like this
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_LEFT:
if player.rect.x > 0:
player.rect.x -= player.rect.width
elif event.key == pygame.K_RIGHT:
if player.rect.x < screen_width: # the screen/game width
player.rect.x += player.rect.width
# Something similar for the up & down keys
I would recommend you to look at this question.
I think you have the right idea but aren't executing it well.
Try going to your game loop and when displaying an image, display like so:
gameDisplay.blit(player1, (player1X,player1Y))
This way, you can use a if statement to change playerX and player1Y. Insert the following code under the code that quits pygame:
elif e.type == pygame.KEYDOWN:
if e.key == pygame.K_LEFT:
player1X -= 5
pygame.display.update()
elif e.key == pygame.K_RIGHT:
player1X += 5
pygame.display.update()
The reason this works is because the variable that is defining X and Y are not staic. You can also do the same thing for up and down using:
elif e.key == pygame.K_UP:
or
elif e.key == pygame.K_DOWN:
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))