Where should I put my pause key at or located at? - python

Okay so I started a project today where I created Space Invaders. The only I'm personally having issues with is the pause and unpause button. I'm using Python 3.7.4 and Pygame 1.9.6.
paused = False
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_p: # Pausing
paused = True
if event.key == pygame.K_u: # Unpausing
paused = False
if not paused:
# RGB = Red, Green, Blue
screen.fill((0, 0, 0))
# Background Image
screen.blit(background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# if keystroke is pressed check whether its right or left
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -5
if event.key == pygame.K_RIGHT:
playerX_change = 5
if event.key == pygame.K_SPACE:
if bullet_state is "ready":
bullet_Sound = mixer.Sound('laser.wav')
bullet_Sound.play()
# Get the current x coordinate of the spaceship
bulletX = playerX
fire_bullet(bulletX, bulletY)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
So I don't know if I should have the pause button first or not.
I've tried:
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_p: # Pausing
paused = True
if event.key == pygame.K_u: # Unpausing
paused = False
if not paused:
while running:
'''The rest of the code'''
Where the # Pausing is:
I've tried:
if event.key == pygame.K_p:
paused = not paused # for pause and unpausing
No 'u' key.
So I'm just lost on where I should put it at. So it would be nice with the help. I looked at question: pausing/ Unpausing in Pygame for help. So anything else let me know.

Here's a minimal, complete example of a ball moving. You can pause and unpause its movement by pressing P. You can change its speed using ←↑→↓. Pressing Spacebar will reset the speed.
import pygame
WIDTH = 640
HEIGHT = 480
FPS = 30
class Ball(pygame.sprite.Sprite):
"""Moving ball sprite"""
def __init__(self, color="white", size=20, speedx=-5, speedy=-5):
pygame.sprite.Sprite.__init__(self)
self.color = pygame.color.Color(color)
# instead of loading an image from file, draw a circle.
self.image = pygame.Surface((size * 2, size * 2), pygame.SRCALPHA)
pygame.draw.circle(self.image, self.color, (size, size), size)
self.rect = self.image.get_rect()
# start ball in the middle of the screen
self.rect.x = WIDTH / 2 - self.rect.width / 2
self.rect.y = HEIGHT / 2 - self.rect.height / 2
self.speedx = speedx
self.speedy = speedy
self.size = size
def update(self):
# reverse direction if out of bounds
if not (0 < self.rect.x < WIDTH - self.size*2):
self.speedx *= -1
if not (0 < self.rect.y < HEIGHT - self.size*2):
self.speedy *= -1
# update position
self.rect.x += self.speedx
self.rect.y += self.speedy
pygame.init()
window = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
ball = Ball()
balls = pygame.sprite.Group()
balls.add(ball)
paused = False
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYUP:
if event.key == pygame.K_p:
paused = not paused
elif event.key == pygame.K_UP:
ball.speedy += 5
elif event.key == pygame.K_DOWN:
ball.speedy -= 5
if event.key == pygame.K_RIGHT:
ball.speedx += 5
elif event.key == pygame.K_LEFT:
ball.speedx -= 5
elif event.key == pygame.K_SPACE:
# reset speed
ball.speedx = 2
ball.speedy = 0
# update game elements
if not paused:
pygame.display.set_caption('Running')
ball.update()
else:
pygame.display.set_caption('Paused')
# draw surface - fill background
window.fill(pygame.color.Color("grey"))
## draw sprites
balls.draw(window)
# show surface
pygame.display.update()
# limit frames
clock.tick(FPS)
pygame.quit()
Note that whilst paused, events are still being handled, so you can still adjust the speed. To change this behaviour, you'd need to discard specific events when paused is True.

Related

How can i solve this: my image doesn't appear on the screen

import sys
import pygame
(width, height) = (800, 600)
screen = pygame.display.set_mode((width, height))
pygame.display.flip()
#Title and Icon
pygame.display.set_caption("Space Invader")
icon = pygame.image.load("spaceship.png")
pygame.display.set_icon(icon)
#Player
playerImg = pygame.image.load("player.png")
playerX = 370
playerY = 480
player_change = 0
def player(x, y):
screen.blit(playerImg, (x, y))
#Game loop
running = True
while running:
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
pygame.display.flip()
#RGB- Red, Green, Blue
screen.fill((0, 128, 128))
# if keystroke is pressed check whether its right or left
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
# 5 = 5 + -0.1 -> 5 = 5 -0.1
# 5 = 5 + 0.1
playerX += playerX_change
player(playerX, playerY)
pygame.display.update()
New atcoding so I followed this youtube video and there his image loaded and mine did too at first. But later if
I added these lines of code, it stopped appearing on the screen. I followed his instructions step by step.
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
How can i solve this problem
You just need 1 application loop. All the events must be handled in the event loop. You have to correct the Indentation.
Also see How to get keyboard input in pygame?:
speed = 1
# application loop
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
keys = pygame.key.get_pressed()
playerX += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * speed
# clear display
screen.fill((0, 128, 128))
# draw scene
player(playerX, playerY)
# update diesplay
pygame.display.update()
pygame.quit()
sys.exit()
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()
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
pygame.display.flip()
#RGB- Red, Green, Blue
screen.fill((0, 128, 128))
# if keystroke is pressed check whether its right or left
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
# **This code is outside of main loop**
playerX += playerX_change
player(playerX, playerY)
pygame.display.update()
You are running main loop twice(while running) and the new code you added was out of it's scope.

My key does not work eventhough I pressed it already Python Pygame

import pygame, sys
pygame.init()
pygame.display.set_caption("test 1")
#main Variables
clock = pygame.time.Clock()
window_size = (700, 700)
screen = pygame.display.set_mode(window_size, 0, 32)
#player variables
playerx = 150
playery = -250
player_location = [playerx, playery]
player_image = pygame.image.load("player/player.png").convert_alpha()
player_rect = player_image.get_rect(center = (80,50))
#button variables
move_right = False
move_left = False
move_up = False
move_down = False
while True:
screen.fill((4, 124, 32))
screen.blit(player_image, player_location, player_rect)
if move_right == True:
playerx += 4
if move_left == True:
playerx -= 4
if move_up == True:
playery -= 4
if move_down == True:
playery += 4
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_d:
move_right = True
if event.key == pygame.K_a:
move_left = True
if event.key == pygame.K_w:
move_up = True
if event.key == pygame.K_s:
move_down = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_d:
move_right = False
if event.key == pygame.K_a:
move_left = False
if event.key == pygame.K_w:
move_up = False
if event.key == pygame.K_s:
move_down = False
pygame.display.update()
clock.tick(120)
I cant get it to work. I pressed the button but it wont go up or down. It worked well when i used no rectangle for the player. I wanter so i can move the character up and down in the y axis also. I just started to learn how to use PyGame so please help me thanks.
As you move the player, you change the playerx and playery variables. However, the player id drawn to the position that is stored in player_location. You must update player_location before drawing the player:
while True:
screen.fill((4, 124, 32))
player_location = [playerx, playery]
screen.blit(player_image, player_location, player_rect)
# [...]
Note that you don't need player_location at all. Draw the player at [playerx, playery]:
while True:
screen.fill((4, 124, 32))
screen.blit(player_image, [playerx, playery], player_rect)

trying to rotate an image in pygame for movement

im new to programming so im following some tutorials online to make a basic game. in order to create the movement for my character, i followed this tutorial
https://www.youtube.com/watch?v=4aZe84vvE20&t=692s&ab_channel=ClearCode
after following the rotation part of the video, i tried testing it out. however, it does not work for some reason. im not sure why this is. i do not get an error, but the character stays in one place and does not rotate once i press the left and right arrow keys. could somebody have a look at my code and let me know what i have done wrong? thanks a lot
import pygame
pygame.init()
window = pygame.display.set_mode((650, 650))
pygame.display.set_caption ("Game")
green = (0,255,0)
window.fill(green)
class Player(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.og_image = pygame.image.load("player1.png")
self.image = self.og_image
self.rect = self.image.get_rect (center = (345,345))
self.angle = 0
self.rotate_speed = 1
self.direction = 0
def rotate(self):
if self.direction == 1:
self.angle -= self.rotate_speed
print(self.angle)
elif self.direction == -1:
self.angle += self.rotate_speed
print(self.angle)
self.image = pygame.transform.rotozoom(self.og_image, self.angle, 1)
self.rect = self.image.get_rect(center = (self.rect.center))
def update(self):
self.rotate()
player_1 = Player()
players = pygame.sprite.GroupSingle()
players.add(player_1)
players.draw(window)
run = True
while run == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
players.sprite.direction += 1
if event.key == pygame.K_LEFT:
players.sprite.direction -= 1
if event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
players.sprite.direction -= 1
if event.key == pygame.K_LEFT:
players.sprite.direction += 1
players.update()
pygame.display.update()
pygame.quit()
You have to draw the Sprites in the Group (players.draw(window)) and you have to clear the display (window.fill(green)) before drawing the objects. Note, you have to do this in the application loop rather than the event loop (It's a matter of Indentation):
run = True
while run == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
players.sprite.direction += 1
if event.key == pygame.K_LEFT:
players.sprite.direction -= 1
if event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
players.sprite.direction -= 1
if event.key == pygame.K_LEFT:
players.sprite.direction += 1
# INDENTATION
#<--|
players.update()
window.fill(green)
players.draw(window)
pygame.display.update()

Block cannot move

I am trying to move this rectangle to make Pong. I had it working before but I messed up the code.
Could anyone help me make it move and possibly make my code look cleaner?
Again, I made it move, but the problem seems to be in the Update method.
Possibly the ScreenSide parameter???...
import pygame, sys, random
from pygame.locals import *
pygame.init()
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((800, 600))
rectImg1 = 'Rect.jpg'
rectImg2 = 'Rect2.jpg'
RIGHT = "RIGHT"
LEFT = "LEFT"
WHITE = (255,255,255)
FPS = 30
PADDLE_SPEED = 5
BALL_SPEED = 10
fpsClock = pygame.time.Clock()
xPos = 0
yPos = 0
leftY = 20
rightY = 20
class Paddle(pygame.sprite.Sprite):
def __init__(self, screenSide):
pygame.sprite.Sprite.__init__(self)
self.screenSide = screenSide
if self.screenSide == LEFT:
self.image = pygame.image.load(rectImg1).convert_alpha()
self.rect = self.image.get_rect()
self.rect.x = 20
self.rect.y = 20
def update(self):
if self.screenSide == LEFT:
self.y = leftY
allSpritesGroup = pygame.sprite.Group()
paddle = Paddle(LEFT)
allSpritesGroup.add(paddle)
#code to make it move
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if paddle.screenSide == LEFT:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_s:
paddle.y += PADDLE_SPEED
elif event.key == pygame.K_w:
paddle.y -= PADDLE_SPEED
elif event.type == pygame.KEYUP:
if event.key == pygame.K_s or event.key == pygame.K_w:
paddle.y == 0
screen.fill((255,255,255))
allSpritesGroup.draw(screen)
allSpritesGroup.update()
pygame.display.flip()
fpsClock.tick(FPS)
pygame.quit()
Just a guess but your problem might be in:
elif event.type == pygame.KEYUP:
if event.key == pygame.K_s or event.key == pygame.K_w:
paddle.y == 0
This looks more like a comparison and if not then you're setting the y to 0 whenever you let go of a key.
Also, You're right about the update function:
def update(self):
if self.screenSide == LEFT:
self.y = leftY
You're constantly setting the y to 20 so it won't move since every time it updates its moved to 20.
Your event handling is broken. The KEYDOWN and KEYUP events are outside of the event loop because of this line if paddle.screenSide == LEFT:. You also need to update paddle.rect.y not paddle.y and you should do that in the class not with global variables. I'd give the paddles a self.y_speed attribute which you set in the event loop and then use it to update the self.rect.y position each frame in the update method. And remove the screenSide checks and just pass the image and position to the sprites during the instantiation.
import sys
import pygame
pygame.init()
screen = pygame.display.set_mode((800, 600))
screen_rect = screen.get_rect()
rectImg1 = pygame.Surface((30, 50))
rectImg1.fill((20, 20, 120))
rectImg2 = pygame.Surface((30, 50))
rectImg2.fill((120, 10, 20))
WHITE = (255,255,255)
FPS = 30
PADDLE_SPEED = 5
fpsClock = pygame.time.Clock()
class Paddle(pygame.sprite.Sprite):
def __init__(self, image, pos):
pygame.sprite.Sprite.__init__(self)
self.image = image
self.rect = self.image.get_rect(topleft=pos)
self.y_speed = 0
def update(self):
self.rect.y += self.y_speed
allSpritesGroup = pygame.sprite.Group()
paddle = Paddle(rectImg1, (20, 20))
paddle2 = Paddle(rectImg2, (750, 20))
allSpritesGroup.add(paddle, paddle2)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_s:
paddle.y_speed = PADDLE_SPEED
elif event.key == pygame.K_w:
paddle.y_speed = -PADDLE_SPEED
elif event.type == pygame.KEYUP:
if event.key == pygame.K_s or event.key == pygame.K_w:
paddle.y_speed = 0
allSpritesGroup.update()
screen.fill(WHITE)
allSpritesGroup.draw(screen)
pygame.display.flip()
fpsClock.tick(FPS)

Player movement stops when direction reverses in Pygame

I am messing around with pygame and I am eventually working towards a pong clone. I implemented player movement with the arrow keys and when ever I switch from going up to immediately going down, my player freezes and won't move again until I press that direction key again. Here is my code:
import sys, pygame
pygame.init()
display_width = 640
display_height = 480
display = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Test Game")
black = (0,0,0)
white = (255,255,255)
clock = pygame.time.Clock()
running = True
class Player:
def __init__(self,x,y,hspd,vspd,color,screen):
self.x = x
self.y = y
self.hspd = hspd
self.vspd = vspd
self.color = color
self.screen = screen
def draw(self):
pygame.draw.rect(self.screen,self.color,(self.x,self.y,32,32))
def move(self):
self.x += self.hspd
self.y += self.vspd
player = Player(0,0,0,0,black,display)
while running:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
player.hspd = 0
if event.key == pygame.K_LEFT:
player.hspd = 0
if event.key == pygame.K_UP:
player.vspd = 0
if event.key == pygame.K_DOWN:
player.vspd = 0
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
player.hspd = 4
if event.key == pygame.K_LEFT:
player.hspd = -4
if event.key == pygame.K_UP:
player.vspd = -4
if event.key == pygame.K_DOWN:
player.vspd = 4
#Clear the screen
display.fill(white)
#Move objects
player.move()
#Draw objects
player.draw()
#Update the screen
pygame.display.flip()
print "I made it!"
pygame.quit()
sys.exit()
I suggest you work with key.get_pressed() to check for the current set of pressed keys.
In your scenario - when you press down and release up (in that order) - the speed is set to 0, so you need to inspect the keys pressed not just by the current event.
Here is a working version of the relevant part:
def current_speed():
# uses the fact that true = 1 and false = 0
currently_pressed = pygame.key.get_pressed()
hdir = currently_pressed[pygame.K_RIGHT] - currently_pressed[pygame.K_LEFT]
vdir = currently_pressed[pygame.K_DOWN] - currently_pressed[pygame.K_UP]
return hdir * 4, vdir * 4
while running:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
player.hspd, player.vspd = current_speed()
#Clear the screen
display.fill(white)
#Move objects
player.move()
#Draw objects
player.draw()
#Update the screen
pygame.display.flip()
To expand on LPK's answer, your key down (for event.key == pygame.K_DOWN) is likely being processed before your key up (from event.key == pygame.K_UP) is processed. So while both are down (and you can confirm this), you may experience movement, until you release the up key.
your problem is here:
if event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
player.hspd = 0
if event.key == pygame.K_LEFT:
player.hspd = 0
if event.key == pygame.K_UP:
player.vspd = 0
if event.key == pygame.K_DOWN:
player.vspd = 0
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
player.hspd = 4
if event.key == pygame.K_LEFT:
player.hspd = -4
if event.key == pygame.K_UP:
player.vspd = -4
if event.key == pygame.K_DOWN:
player.vspd = 4
I am guessing that your key event down is still consumed when u switch the keys immediately, meaning no other key down event is getting triggered as long as the first event didn't fire its key up event yet.
EDIT: maybe its better to check if the player is moving and if so just reverse speed . Then you would only need to check the down event.
Otherwise your event will be consumed and not checked properly.
For your method you would need to store the occurred key events since the last frame and check that list.

Categories

Resources