This question already has answers here:
How to get keyboard input in pygame?
(11 answers)
Closed 1 year ago.
from pygame.locals import *
import random
import pygame
from pygame.constants import K_RIGHT
# Initialize the pygame
pygame.init
# create the screen
screen = pygame.display.set_mode((800, 600))
# background
background = pygame.image.load('bg.png')
# Title and Icon
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load('ufo.png')
pygame.display.set_icon(icon)
# Player
playerImg = pygame.image.load('player.png')
playerX = 370
playerY = 480
playerX_change = 0
def player(x, y):
screen.blit(playerImg, (x, y))
# Enemy
enemyImg = pygame.image.load('alien.png')
enemyX = random.randint(0, 736)
enemyY = 50
enemyX_change = 1
enemyY_change = 40
def enemy(x, y):
screen.blit(enemyImg, (x, y))
# Bullet
# ready - you can't see bullet
# fire - you can see bullet and it's moving
bulletImg = pygame.image.load('bullet.png')
bulletX = 0
bulletY = 480
bulletX_change = 1
bulletY_change = 10
bullet_state = "ready"
def fire_bullet(x, y):
global bullet_state
bullet_state = "fire"
screen.blit(bulletImg, (x+16, y+10))
# Game Loop
running = True
while running:
# Changing RGB of background
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 wheter its right or left
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
fire_bullet(playerX, bulletY)
if event.key == pygame.K_LEFT:
playerX_change = -3
if event.key == pygame.K_RIGHT:
playerX_change = 3
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
# bounds
playerX += playerX_change
if playerX <= 0:
playerX = 0
elif playerX >= 736:
playerX = 736
# enemy movement
enemyX += enemyX_change
if enemyX <= 0:
enemyX_change = 1
enemyY += enemyY_change
elif enemyX >= 736:
enemyX_change = -1
enemyY += enemyY_change
# bullet movement
if bullet_state is "fire":
fire_bullet(playerX, bulletY)
bulletY -= bulletY_change
player(playerX, playerY)
enemy(enemyX, enemyY)
pygame.display.update()
I'm working on a tutorial project for begginers in PyGame. It is a copy of Space Inviders. When i'm pressing space nothing is happening, but when i press ctrl + shift + space it reacts as space, also after changing K_SPACE to K_LSHIFT or K_UP it is working but with other buttons it is not, I've tried changing "fire" and "ready" to True or False but it didn't fixed my problem
It is a matter of Indentation. You have to evaluate the events in the event loop instead of the application loop:
#Game Loop
running = True
while running:
# Changing RGB of background
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
# INDENTATION
#-->|
# if keystroke is pressed check wheter its right or left
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
fire_bullet(playerX, bulletY)
if event.key == pygame.K_LEFT:
playerX_change = -3
if event.key == pygame.K_RIGHT:
playerX_change = 3
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
Related
This question already has answers here:
How to get keyboard input in pygame?
(11 answers)
How can I make a sprite move when key is held down
(6 answers)
Closed 11 months ago.
Alright so the enemy I have only moves when I move my character, but it also sometimes spawns completely out of the game's window. Also the background, player and enemy just kinda... Dont pop up until I press a movement button, im so sorry for this lmfao Also sorry about the text and stuff I was told to put them there for reminders on wtf to
import pygame
import random
pygame.init()
screen = pygame.display.set_mode((800, 600))
background = pygame.image.load("BackgroundImg.jpg")
pygame.display.set_caption("Real Hero")
icon = pygame.image.load('Icon.png')
pygame.display.set_icon(icon)
playerImg = pygame.image.load('Player.png')
playerX = 370
playerY = 480
playerX_change = 0
enemyImg = pygame.image.load('Enemy.jpg')
enemyX = random.randint(0, 746)
enemyY = random.randint(50, 746)
enemyX_change = 0.2
enemyY_change = 40
def player(x, y):
screen.blit(playerImg, (x, y))
def enemy(x, y):
screen.blit(enemyImg, (x, y))
running = True
while running:
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 event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
playerX_change = -0.3
if event.key == pygame.K_RIGHT:
playerX_change = 0.3
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
playerX += playerX_change
if playerX <= 0:
playerX = 0
elif playerX >= 736:
playerX = 736
enemyX += enemyX_change
if enemyX <= 0:
enemyX_change = 0.2
enemyY += enemyY_change
elif enemyX >= 736:
enemyX_change = -0.2
enemyY += enemyY_change
enemy(enemyX, enemyY)
player(playerX, playerY)
pygame.display.update()
The reason as to why the enemy only moves when you press a movement key is because you have the enemy movement code inside of the if event.type == pygame.KEYDOWN: if statement. You are also only updating the screen when you press a movement key because the pygame.display.update() is also inside that ifstatement. You need to move any code that shouldn't only be run when a key is pressed out of the if statement.
This question already has an answer here:
How to make enemies fall at random on pygame?
(1 answer)
Closed 2 years ago.
my enemy in my game is supposed to move up and down and every time it reaches the bottom of the screen it is supposed to re spawn in a different spot and go down again. Here it is explained in a video.
pygame.init()
screen_width = 800
screen_height = 600
window = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Test')
time = pygame.time.Clock()
bg_color1 = (135, 142, 142) # MAIN BG COLOR
bg_color2 = (255, 0, 0) # red
bg_color3 = (255, 255, 0) # yellow
UFO = pygame.image.load('ufo.png')
bg_pic = pygame.image.load('Letsgo.jpg')
clock = pygame.time.Clock()
playerImg = pygame.image.load('enemy.png')
playerX = random.randrange(0, screen_width)
playerY = -50
playerX_change = 0
player_speed = 5
def player(x, y):
window.blit(playerImg, (playerX, playerY))
crashed = False
rect = UFO.get_rect()
obstacle = pygame.Rect(400, 200, 80, 80)
menu = True
playerY = playerY + player_speed
if playerY > screen_height:
playerX = random.randrange(0,screen_width)
playerY = -25
def ufo(x, y):
window.blit(UFO, (x, y))
while menu:
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
menu = False
window.fill((0, 0, 0))
time.tick(30)
window.blit(bg_pic, (0, 0))
pygame.display.update()
x = (screen_width * 0.45)
y = (screen_height * 0.8)
x_change = 0
car_speed = 0
y_change = 0
while not crashed:
x += x_change
if x < 0:
x = 0
elif x > screen_width - UFO.get_width():
x = screen_width - UFO.get_width()
y += y_change
if y < 0:
y = 0
elif y > screen_height - UFO.get_height():
y = screen_height - UFO.get_height()
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
############SIDE TO SIDE################
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
###########UP AND DOWN#################
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
## if playerY > screen_height:
playerX = random.randrange(0,screen_width)
playerY = -10
x += x_change
y += y_change
##
window.fill(bg_color1)
ufo(x, y)
player(playerX, playerY)
pygame.display.update()
clock.tick(100)
pygame.quit()
quit()
this is my full code and the code i used to make it move up and down was this.
playerX = random.randrange(0,screen_width)
playerY = -10
Thanks for any help!...........................................................................
What you are doing at the moment seems to be setting the Y once, you need to create a loop to constantly update the Y
The line with the condition if playerY > screen_height: is actually a comment:
## if playerY > screen_height:
so you're setting playerX every frame. It should look more like this:
if playerY > screen_height: # when out of screen
playerX = random.randrange(0,screen_width) # new random X
playerY = 0 # also reset y back to top
playerY += 10 # move
I've been trying to create a game screen but I can't seem to add a boundary around the houses on the screen so that the player doesn't walk over them. Below is my code
import pygame
import sys
from pygame import mixer
pygame.init()
playerImg = pygame.image.load('player.png')
WalkFront = [pygame.image.load('B1.png'), pygame.image.load('B2.png'),pygame.image.load('B3.png'),
pygame.image.load('B4.png')]
WalkBack = [pygame.image.load('F1.png'), pygame.image.load('F2.png'), pygame.image.load('F3.png'),
pygame.image.load('F4.png')]
WalkRight = [pygame.image.load('R1.png'), pygame.image.load('R2.png'), pygame.image.load('R3.png'),
pygame.image.load('R4.png')]
WalkLeft = [pygame.image.load('L1.png'), pygame.image.load('L2.png'), pygame.image.load('L3.png'),
pygame.image.load('L4.png')]
walkcount = 0
clock = pygame.time.Clock()
scr = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Pokemon: Red')
logo = pygame.image.load('logo.png')
pygame.display.set_icon(logo)
background = pygame.image.load('BG.png')
pallet = pygame.image.load('pallet town.png')
mixer.music.load('Start menu.mp3')
mixer.music.play(100, 0, 0)
playerX = 200
playerY = 200
up = False
down = False
left = False
right = False
def redrawgamewindow():
global walkcount
scr.fill((0, 0, 0))
scr.blit(pallet, (60, 0))
if walkcount + 1 >= 29:
walkcount = 0
if up:
scr.blit(WalkFront[walkcount // 7], (playerX, playerY))
walkcount += 1
elif down:
scr.blit(WalkBack[walkcount // 7], (playerX, playerY))
walkcount += 1
elif left:
scr.blit(WalkLeft[walkcount // 7], (playerX, playerY))
walkcount += 1
elif right:
scr.blit(WalkRight[walkcount // 7], (playerX, playerY))
walkcount += 1
else:
player(playerX, playerY)
pygame.display.update()
def player(x, y):
scr.blit(playerImg, (x, y))
def start_menu():
while True:
scr.fill((255, 255, 255))
scr.blit(background, (0, 0))
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
game()
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
pygame.display.update()
def game():
global playerX
global playerY
clock.tick(12)
mixer.music.pause()
mixer.music.load('pallet_music.mp3')
mixer.music.play(100)
playerX_change = 0
playerY_change = 0
running = True
while running:
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_UP:
global up
global down
global left
global right
up = True
down = False
playerY_change = -0.8
elif event.key == pygame.K_DOWN:
up = False
down = True
playerY_change = 0.8
else:
up = False
down = False
walkcount = 0
if event.key == pygame.K_LEFT:
playerX_change = -1
left = True
right = False
elif event.key == pygame.K_RIGHT:
playerX_change = 1
right = True
left = False
else:
left = False
right = False
walkcount = 0
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
playerY_change = 0
up = False
down = False
left = False
right = False
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
up = False
down = False
left = False
right = False
playerX += playerX_change
playerY += playerY_change
if playerX <= 90:
playerX = 90
elif playerX >= 670:
playerX = 670
if playerY <= 40:
playerY = 40
elif playerY >= 540:
playerY = 540
redrawgamewindow()
start_menu()
the background image has an area on it with a house in the top left. See the background image below so you can get a better idea. what I want is for the player to not be able to walk on the house so he gets blocked at the edge.
I recommend to define a rectangular area for the house. Use pygame.Rect. You have to find the values for hx, hy, hw and hh:
house_rect = pygame.Rect(hx, hy, hw, hh)
Create a rectangle for the player after the position of the player is changed. The size of the rectangle can be get from the pygame.Surface object which represents the player by get_rect(). The position has to be set by an keyword argument (topleft = (playerX, playerY)).
Use pygame.Rect.colliderect to evaluate if the player collides with the house and restrict the position of the player to the area outside the house:
playerX += playerX_change
player_rect = playerImg.get_rect(topleft = (playerX, playerY))
if player_rect.colliderect(house_rect):
if playerX_change > 0:
player_rect.right = house_rect.left
elif playerX_change < 0:
player_rect.left = house_rect.right
playerX = player_rect.x
playerY += playerY_change
player_rect = playerImg.get_rect(topleft = (playerX, playerY))
if player_rect.colliderect(house_rect):
if playerY_change < 0:
player_rect.top = house_rect.bottom
elif playerY_change > 0:
player_rect.bottom = house_rect.top
playerY = player_rect.y
I guess you have to patiently make the boundaries with x and y like this:
if x > boundaryX and y > boundaryY:
xOfThePlayer -= moving
It is an example you have to change this according to your needs.
so i was learning python and i finished the game and everything is working but now i have no idea about how to restart the game i mean when it ends what is next? how to start again
i will put a link for my full code and here is what have done so far.
Thank you so much!
if Bullet_state is "fire":
fire(BulletX, BulletY)
BulletY -= Bullet_MovementY
player(playerX, playerY)
score(textX, textY)
pygame.display.update()
For the restart logic, keep the current game loop but add a flag to indicate that the game has ended. In the loop, check for this flag and display the restart prompt if the flag is set. Also encapsulate the initialization process in a function so it can be called at each restart.
Note that I tested this in Python 3.8.
Try this code. When the score reaches 3, the game ends and the restart prompt is displayed.
import pygame
import random
import math
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Space Invadors')
icon = pygame.image.load('1.png')
pygame.display.set_icon(icon)
#Background
Background = pygame.image.load('background.png')
def SetGameStart(): # initialize variables
global Player_Image,playerX,playerY,Key_Movement,Enemy_Image,EnemyX,EnemyY,Enemy_MovementX,Enemy_MovementY
global Bullet_Image,BulletX,BulletY,Bullet_MovementX,Bullet_MovementY,Bullet_state,Score
# Player
Player_Image = pygame.image.load('player.png')
playerX = 370
playerY = 480
Key_Movement = 0
# Enemy
Enemy_Image = pygame.image.load('monster2.png')
EnemyX = random.randint(0, 735)
EnemyY = random.randint(50, 150)
Enemy_MovementX = 1.5
Enemy_MovementY = 40
# Bullet
Bullet_Image = pygame.image.load('bullet.png')
BulletX = 0
BulletY = 480
Bullet_MovementX = 0
Bullet_MovementY = 10
Bullet_state = "Ready"
Score = 0
def Fire(x, y):
global Bullet_state
Bullet_state = "Fire"
screen.blit(Bullet_Image, (x + 16, y + 10))
def player(x, y):
# blit is draw! draw an image on the screen
screen.blit(Player_Image, (x, y))
def Enemy(x, y):
screen.blit(Enemy_Image, (x, y))
def is_Collided(BulletX, BulletY, EnemyX, EnemyY):
distance = math.sqrt(math.pow(BulletX - EnemyX, 2) + math.pow(BulletY - EnemyY, 2))
if distance < 27:
return True
else:
return False
SetGameStart() # initialize variables
GameDone = False
def text_objects(text, font):
textSurface = font.render(text, True, (0,200,0))
return textSurface, textSurface.get_rect()
Close = True
while Close:
screen.fill((0, 0, 0))
screen.blit(Background, (0, 0))
if GameDone: # pause game loop, show restart prompt
largeText = pygame.font.SysFont("comicsansms",20)
TextSurf, TextRect = text_objects("Game Over. Press Space to restart.", largeText)
TextRect.center = ((800/2),(600/2))
screen.blit(TextSurf, TextRect)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
Close = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q: # press Q to quit
Close = False
break
if event.key == pygame.K_SPACE: # press space to restart
GameDone = False
SetGameStart() # initialize variables
continue # skip game process
for event in pygame.event.get():
if event.type == pygame.QUIT:
Close = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
Key_Movement = -4
if event.key == pygame.K_RIGHT:
Key_Movement = 4
if event.key == pygame.K_SPACE:
# to fix the Pressing on space will reload the Bullet
if Bullet_state is "Ready":
BulletX = playerX
Fire(BulletX, playerY)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
Key_Movement = 0
playerX += Key_Movement
if playerX <= 0:
playerX = 0
elif playerX >= 736:
playerX = 736
# Enemy movement limit
EnemyX += Enemy_MovementX
if EnemyX <= 0:
Enemy_MovementX = 1.5
EnemyY += Enemy_MovementY
elif EnemyX >= 736:
Enemy_MovementX = -1.5
EnemyY += Enemy_MovementY
if BulletY <= 0:
BulletY = 480
Bullet_state = "Ready"
if Bullet_state is "Fire":
Fire(BulletX, BulletY)
BulletY -= Bullet_MovementY
Collision = is_Collided(EnemyX, EnemyY, BulletX, BulletY)
if Collision:
BulletY = 480
Bullet_state = "Ready"
Score += 1
print(Score)
EnemyX = random.randint(0, 735)
EnemyY = random.randint(50, 150)
Enemy(EnemyX, EnemyY)
player(playerX, playerY)
pygame.display.update()
if Score == 3:
GameDone = True
Prompt
#enable pygame mode
import pygame
pygame.init()
#create screen
screen = pygame.display.set_mode((1000,600))
#Title + Logo
pygame.display.set_caption("Space Invader")
icon = pygame.image.load("chicken.png")
pygame.display.set_icon(icon)
#Player icon
player_icon = pygame.image.load("spaceship.png")
playerX = 400
playerY = 500
player_changeX = 0
player_changeY = 0
def player(x, y):
screen.blit(player_icon, (x, y))
surface.blit(image,((1920/2)-(image.get_width()/2),(1080/2)-
(image.get_height()/2)))
#game loop
running = True
while running:
# backround colour RGB
screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
#If key pressed check wether its right or left
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player_changeX = -1
if event.key == pygame.K_RIGHT:
player_changeX = 1
if event.key == pygame.K_UP:
player_changeY = -1
if event.key == pygame.K_DOWN:
player_changeY = 1
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key ==pygame.K_RIGHT:
player_changeX = 0
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
player_changeY = 0
# If player reaches boarder
if playerX >= 936:
player_changeX = -1
if playerX <= 0:
player_changeX = 1
if playerY <= 0:
player_changeY = 1
if playerY >= 550:
player_changeY = -1
#Player change in coordinates
playerX += player_changeX
playerY += player_changeY
player(playerX, playerY)
pygame.display.update()
I am creating a simple game as i just got into programing and I was wondering if you could make the game screen appear in the centre of your own screen as when I run it it keeps appearing on the bottom of my screen and I then have to manually move it into the centre. If you can please tell me how. Hope my question was formated good enough. Thank you for any help.
It depends; if it's a image you can do:
surface.blit(image,((screenwidth/2)-(image.get_width()/2),(screenheight/2)-(image.get_height()/2)))
Please tell me it it's different