How to build a propper player movement script Pygame [duplicate] - python

This question already has answers here:
How can I make a sprite move when key is held down
(6 answers)
Closed 1 year ago.
Ok so im new to PyGame, and im making a space invader game, im currently building the movement script.
for some reason my character is infinitely moving to the right when i press the right key.. i know this must be a really simple solution i am just not seeing it lol i would appreciate an answer.
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Space Invader')
icon = pygame.image.load('pepper.png')
pygame.display.set_icon(icon)
#Player
playerImg = pygame.image.load('sombreroship.png')
playerX = 370
playerY = 480
playerX_Change = 0
def player (x, y): screen.blit(playerImg, (x, y) )
running = True
while running:
# RGB STANDS FOR RED, GREEN, BLUE THE NUMBERS GOES MAX TO 255 FOR EXAMPLE_:
screen.fill((0, 0, 30)) # this will display yellow
for event in pygame.event.get():
if event.type == pygame.QUIT: #if we click the X the program ends
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_Change = -0.1
if event.key == pygame.K_RIGHT:
playerX_Change = 0.1
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_Change = 0.1
playerX += playerX_Change
player(playerX, playerY)
pygame.display.update()

I suggest to use pygame.key.get_pressed() instead of the key board events.
The keyboard events (see pygame.event module) occur only once when the state of a key changes. The KEYDOWN event occurs once every time a key is pressed. KEYUP occurs once every time a key is released. Use the keyboard events for a single action or a step-by-step movement.
pygame.key.get_pressed() returns a sequence with the state of each key. If a key is held down, the state for the key is True, otherwise False. Use pygame.key.get_pressed() to evaluate the current state of a button and get continuous movement:
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Space Invader')
icon = pygame.image.load('pepper.png')
pygame.display.set_icon(icon)
#Player
playerImg = pygame.image.load('sombreroship.png')
playerX = 370
playerY = 480
def player (x, y):
screen.blit(playerImg, (x, y) )
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT: #if we click the X the program ends
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_RIGHT] :
playerX += 0.1
if keys[pygame.K_LEFT] :
playerX -= 0.1
# RGB STANDS FOR RED, GREEN, BLUE THE NUMBERS GOES MAX TO 255 FOR EXAMPLE_:
screen.fill((0, 0, 30)) # this will display yellow
player(playerX, playerY)
pygame.display.update()

Related

I have written this code in python and while I am pressing the buttons it should move to the right and left accordingly but it is not [duplicate]

This question already has answers here:
How can I make a sprite move when key is held down
(6 answers)
Closed 23 days ago.
Here i have written the code for playerX_change (it is the value which was first defined as 0)and when any key was pressed like left or right it should respond by changing the value of x , but it is not
I tried to correct the indexing and also tried to create new variables for it , pls try something else and suggest the recommended changes
here is the code
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("It's a game -_-")
icon = pygame.image.load('ufo.png')
pygame.display.set_icon(icon)
running: bool = True
playerimg = pygame.image.load('spaceship3.png')
playerX = 370
playerY = 480
def player(x, y):
screen.blit(playerimg, (x, y))
while running:
screen.fill((22, 11, 222))
playerX_change = 0
player(playerX, playerY)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# it shows basically that every key pressed inside the window gets stored in pygame.event
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -0.1
if event.key == pygame.K_RIGHT:
playerX_change =0.1
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
welcome to the community, what you are trying to do is to move the player to the left or right whenever you press the left/right, however, you are not changing the PlayerX variable by the PlayerX_change. This therefore will not move the player, try replacing PlayerX_change = 0 to PlayerX += PlayerX_change so that you update the players X position and that it will only stop on the key up.

In Pygame, the image doesn't get erased when moved to another location on the game window

I have been trying out the Pygame game library on my Mac, and when I got to try moving around an image around the game window, for some reason, it doesn't get erased.
The code I tried to run:
import pygame
pygame.init()
# Creates the screen.
screen = pygame.display.set_mode([800, 600])
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load("ufo.png")
pygame.display.set_icon(icon)
# Player sprite.
playerImg = pygame.image.load("player.png")
playerX = 350
playerY = 500
playerX_change = 0
# Function to draw the player
def player(x, y):
screen.blit(playerImg, (playerX, playerY))
# Game loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -0.1
print("Left key is pressed!")
if event.key == pygame.K_RIGHT:
playerX_change = 0.1
print("Right key is pressed!")
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
playerX += playerX_change
I have tried to run similar code on my PC, and it worked like intended. I have no idea what to do.
You have to clear the screen in every frame:
clock = pygame.time.Clock()
running = True
while running:
clock.tick(100)
# event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# update objects
speed = 1
keys = pygame.key.get_pressed()
playerX += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * speed
# clear screen
screen.fill(0)
# draw scene
player(playerX, playerY)
# update display
pygame.dispaly.flip()
The typical PyGame application loop has to:
limit the frames per second to limit CPU usage with pygame.time.Clock.tick
handle the events by calling either pygame.event.pump() or pygame.event.get().
update the game states and positions of objects dependent on the input events and time (respectively frames)
clear the entire display or draw the background
draw the entire scene (blit all the objects)
update the display by calling either pygame.display.update() or pygame.display.flip()

Pygame character does not show up on screen

I try to get my Pygame character on screen but I cannot get it to appear so I can control it for a game I am building
Here is the code:
import pygame
#turn on pygame
pygame.init()
#window, window name and icon
screen = pygame.display.set_mode((1920,1080))
pygame.display.set_caption("When The Sky Turns Grey")
icon = pygame.image.load('cat.png')
pygame.display.set_icon(icon)
#Player
playerIMG = pygame.image.load('cat.png')
playerX = 960
playerY = 1080
playerXchange = 0
def player():
screen.blit(playerIMG, (playerX, playerY))
#Game loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
#KEYS
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
playerX_change = -5
if event.key == pygame.K_d:
playerX_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_a or event.key == pygame.K_d:
playerXchange = 0
playerX += playerXchange
#RGB
screen.fill((0, 0, 255))
#draw player (call player function)
player()
pygame.display.update()
I cannot get it to show up at all, no matter what I change.
I am new to pygame and if anyone can help I will be grateful
Thank you!
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
There is 2 problems in this question
First your cat Y position is to much that it went under the screen, it should be like this:
playerY = 540 # Don't go over 1080 which is the screen height
Second you didn't update the display so it doesn't show anything on the screen, at the very end of the while loop put pygame.display.update after player()

How do I make sure that my pygame car keeps moving if one key is held down and another is released? [duplicate]

This question already has answers here:
How can I make a sprite move when key is held down
(6 answers)
How to get keyboard input in pygame?
(11 answers)
Closed 1 year ago.
It is a bit confusing to explain. So, if you have questions, please ask them. I am creating a game using pygame and my "car" moves when you use the "up","down","left", and "right" keys. However, in the way I have it coded, when I release the right key for example but am still holding the left key down, it will change the movement to 0 and not recognize that the left key is still being held down. It makes the movement rather weird. I am trying to make this movement more smooth so that the game is more enjoyable, any ideas are helpful, thank you.
Here is my code:
import pygame
#Initializes pygame
pygame.init()
#Create the screen
screen = pygame.display.set_mode((1000, 800))
#Icon and Caption
icon = pygame.image.load('redcar.png')
pygame.display.set_icon(icon)
pygame.display.set_caption("Placeholder")
# Car
car = pygame.image.load('redcar.png')
x = 500
y = 600
x_change = 0
y_change = 0
def player(x,y):
screen.blit(car, (x, y))
#Game loop, keep window open unless you quit the window
running = True
while running:
#RGB
screen.fill((255, 255, 255))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
#If key is pressed, check what key it was
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -1
if event.key == pygame.K_RIGHT:
x_change = 1
if event.key == pygame.K_UP:
y_change = -1
if event.key == pygame.K_DOWN:
y_change = 1
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
x_change = 0
if event.key == pygame.K_RIGHT:
x_change = 0
if event.key == pygame.K_UP:
y_change = 0
if event.key == pygame.K_DOWN:
y_change = 0
x += x_change
y += y_change
player(x,y)
#For each event, update window
pygame.display.update()
You can solve this by using pygame.key.get_pressed(). That will tell you if a key is being held down. It works when any amount of keys are being held down.
Here's a simplified version of your code to demonstrate how that works:
import pygame
pygame.init()
pygame.font.init();
myfont = pygame.font.SysFont('Consolas', 30)
screen = pygame.display.set_mode((1000, 800))
running = True
while running:
screen.fill((255, 255, 255))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pressed = pygame.key.get_pressed()
if pressed[pygame.K_UP]:
textsurface = myfont.render('Up', False, (0, 0, 0))
screen.blit(textsurface,(0,0))
if pressed[pygame.K_DOWN]:
textsurface = myfont.render('Down', False, (0, 0, 0))
screen.blit(textsurface,(0,50))
if pressed[pygame.K_LEFT]:
textsurface = myfont.render('Left', False, (0, 0, 0))
screen.blit(textsurface,(0,100))
if pressed[pygame.K_RIGHT]:
textsurface = myfont.render('Right', False, (0, 0, 0))
screen.blit(textsurface,(0,150))
pygame.display.update()
If I hold Left and Up the window will show:
You could set x_change and y_change to zero before calling get_pressed(), then set those variables within the ifs, depending on which evaluate to true. e.g. Set x_change to -1 if the left key is being pressed.
You may want to think about what happens when the user is pressing up+down (or left+right). That could either cancel out or one key could take precedence.

Pygame when you press on key move image to position

Hey I want to learn how to move your image to a position.
I searched on Google and Youtube but I got a little bit information.
This is my code
import pygame as pg
pg.init()
# Create screen
screen = pg.display.set_mode((1100, 700))
# Background
background = pg.image.load('map.png')
# Player
playerImg = pg.image.load('player.png')
playerX = 80
playerY = 595
def player(x, y):
screen.blit(playerImg, (x, y))
# Game Loop
running = True
while running:
# Background image
screen.blit(background, (0, 0))
for event in pg.event.get():
if event.type == pg.QUIT:
running = False
# If keystroke is pressed check whether its right or left
if event.type == pg.KEYDOWN:
if event.key == pg.K_q:
screen.blit(playerImg, [80, 598])
if event.key == pg.K_w:
screen.blit(playerImg, [370, 598])
if event.key == pg.K_e:
screen.blit(playerImg, [665, 598])
if event.key == pg.K_r:
screen.blit(playerImg, [950, 598])
if playerX <= 80:
playerX = 80
elif playerX >= 950:
playerX = 950
player(playerX, playerY)
pg.display.update()
The problem what I have now
When I press one of the keys it shows the image but for like 1 second.
What I want
When I press the key it show the image and when I press the second key
I want that the image go to the new position.
If you don't want to show the image a the beginning, then init the player coordinates with an off screen position.
If a key is pressed, then you have to change the position (playerX, playerY):
playerX = -100
playerY = -100
running = True
while running:
# Background image
screen.blit(background, (0, 0))
for event in pg.event.get():
if event.type == pg.QUIT:
running = False
# If keystroke is pressed check whether its right or left
if event.type == pg.KEYDOWN:
if event.key == pg.K_q:
playerX, playerY = 80, 598
if event.key == pg.K_w:
playerX, playerY = 370, 598
if event.key == pg.K_e:
playerX, playerY = 665, 598
if event.key == pg.K_r:
playerX, playerY = 950, 598
player(playerX, playerY)
pg.display.update()
screen.blit(playerImg, ...) would just draw a 2nd player at a different position, for 1 single frame. That is hardly noticeable and may just cause a short flicker of a 2nd player image.
Note, the KEYDOWN event occurs once only, when the button is pressed. In that case your code blit a player, but it gets "cleared" immediately in the next frame by screen.blit(background, (0, 0)).

Categories

Resources