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.
Related
This question already has answers here:
How can i shoot a bullet with space bar?
(1 answer)
How do I stop more than 1 bullet firing at once?
(1 answer)
Pygame: problems with shooting in Space Invaders
(1 answer)
Closed 3 months ago.
what i've created here is Space Invaders Game and everything works except function bullet(x,y) can somebody help me to fix this i want to create two bullet_statements for example when it is "ready" statement it won't shoot and when is "fire" statement it will shoot that happens when i press space and bullet should go from coordinates(BulletY-480) till (BulletY-0)
import pygame
import random
background_color = ((0,0,0))
screen = pygame.display.set_mode((800,600))
pygame.display.set_caption("Spaceship Invaders")
screen.fill(background_color)
icon = pygame.image.load('spaceship.png')
pygame.display.set_icon(icon)
playerImg = pygame.image.load('space-invaders.png')
playerX = 370
playerY = 480
playerX_change = 0
#Bullet
bulletImg = pygame.image.load('bullet.png')
bulletX = 0
bulletY = 480
bulletX_change = 0
bulletY_change = 5
bullet_state = "ready" #Ready - Rest, Fire - Motion
#background
BackgroundImg = pygame.image.load('background.jpg')
EnemyImg = pygame.image.load('monster.png')
EnemyX = (random.randint(150,500))
EnemyY = (random.randint(0,150))
EnemyX_change = 0.2
EnemyY_change = 40
def player(x,y):
screen.blit(playerImg,(playerX,playerY))
def enemy(x,y):
screen.blit(EnemyImg,(EnemyX,EnemyY))
def bullet(x,y):
global bullet_state
bullet_state = "fire"
screen.blit(bulletImg,(x+15,y+10))
running = True
while running:
screen.blit(BackgroundImg,(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.2
if event.key == pygame.K_RIGHT:
playerX_change = 0.2
if event.key == pygame.K_SPACE:
bullet(playerX,bulletY)
if event.type == pygame.KEYUP:
playerX_change = 0
EnemyX += EnemyX_change
if playerX < 0:
playerX = 0
if playerX > 736:
playerX = 736
playerX += playerX_change
if EnemyX > 736:
EnemyX_change = -0.2
EnemyX += EnemyX_change
EnemyY += EnemyY_change
if EnemyX < 0:
EnemyX_change = 0.2
EnemyX += EnemyX_change
EnemyY += EnemyY_change
player(playerX,playerY)
enemy(EnemyX,EnemyY)
pygame.display.update()
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
This question already has answers here:
How can i shoot a bullet with space bar?
(1 answer)
How do I stop more than 1 bullet firing at once?
(1 answer)
Closed 2 years ago.
My objective is to make a space invaders type of game, where the spaceship can move up, down, left and right, and fire bullets at the alien.
I've yet to make the collision part of the code as I am stuck at the firing bullets part.
I've assigned spacebar to fire bullets yet I'm unable to see any bullet firing.
Please help me out.
import pygame
import random
# for initialising pygame (req for every pygame app)
pygame.init()
# making the basic window (dimensions must be written inside a tuple )
screen = pygame.display.set_mode((500, 500))
# background
background = pygame.image.load('C:/Users/aryan/Downloads/background.jpg')
# load and set the logo
logo = pygame.image.load('C:/Users/aryan/Downloads/bp.png') # directory of logo
pygame.display.set_icon(logo)
pygame.display.set_caption("space wars") # program name
# define a variable to control the main loop
running = True
# player
playerimg = pygame.image.load('C:/Users/aryan/Downloads/spaceship.png')
playerX = 218 # x and y coordinates of image
playerY = 350
playerxchange = 0 # this will be the change in movement in x direction of our image
playerychange = 0 # this will be the change in movement in y direction of our image
def player(x, y):
screen.blit(playerimg, (x, y)) # blit draws our image on the surface(basically the background)
# syntax for blit(imagename, (xcoordinate,ycoordinate))
# enemy
enemyimg = pygame.image.load('C:/Users/aryan/Downloads/enemy.png')
enemyX = random.randint(0, 476)
enemyY = 20
enemyxchange = 0.2
enemyychange = 40
# game over
overimg = pygame.image.load('C:/Users/aryan/Downloads/gameover.png')
# bullet
bulletimg = pygame.image.load('C:/Users/aryan/Downloads/bullet.png')
bulletX = 0
bulletY = 350
bulletxchange = 0
bulletychange = 7
bullet_state = "ready" # "ready" you cant see bullet on screen
# "fire" you can see bullet firing
def enemy(x, y):
screen.blit(enemyimg, (x, y)) # blit draws our image on the surface(basically the background)
# syntax for blit(imagename, (xcoordinate,ycoordinate))
def firebullet(x, y):
global bullet_state
bullet_state = "ready"
screen.blit(bulletimg, (x+12, y+6))
# main loop
while running:
screen.fill((120, 120, 120)) # in order (r, g, b) . (0, 0, 0) is black (255, 0, 0) is red...
screen.blit(background, (0, 0))
# event handling, gets all event from the event queue
for event in pygame.event.get():
# only do something if the event is of type QUIT
if event.type == pygame.QUIT:
# change the value to False, to exit the main loop
running = False
# checking keystroke
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
playerxchange += 0.2 # change in movement will be 0.2 towards the right
if event.key == pygame.K_LEFT:
playerxchange -= 0.2 # change in movement will be 0.2 towards the right
#if event.key == pygame.K_UP:
# playerychange -= 0.2
#if event.key == pygame.K_DOWN:
# playerychange += 0.2
if event.key == pygame.K_SPACE:
bullet_state = "fire"
firebullet(playerX, bulletY)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: #or event.key == pygame.K_DOWN or event.key == pygame.K_UP:
playerxchange = 0
playerychange = 0
playerY += playerychange
playerX += playerxchange # the value of playerx changes by +- 0.1 depending on keystroke
if playerX <= -64: # this teleports the spaceship from left end to right end
playerX = 564
elif playerX >= 564: # this teleports spaceship from right end to left
playerX = -64
if playerY >= 436: # this prevents spaceship from leaving vertically
playerY = 436
if playerY <= 0:
playerY = 0
# enemy movement
enemyX += enemyxchange
if enemyY >= 476:
enemyY = 476
enemyYchange = 0
enemyXchange = 0
if enemyX <= 0:
enemyxchange = 0.1
enemyY += enemyychange
elif enemyX >= 465:
enemyxchange = -0.1
enemyY += enemyychange
# bullet movement
if bullet_state is "fire":
firebullet(playerX, bulletY)
bulletY -= bulletychange
player(playerX, playerY) # player method is called AFTER screen.fill otherwise the screen will fill after image has been blitted
enemy(enemyX, enemyY)
pygame.display.update() # necessary for events to keep updating
Also, the comments may seem trivial, but I am a beginner.
You don't see the bullet firing because you only call screen.blit(bulletimg, (x+12, y+6)) once in your firebullet function. After this, a new loop begins and the background gets printed over it with screen.blit(background, (0, 0)), and no code is called to render your bullet anymore. What you need is to keep each bullet in memory and call .blit() every loop iteration so that they're all printed correctly.
Here's a basic solution:
...
bullets = [] #Array to store the position of the bullets
...
def firebullet(x, y):
global bullet_state
bullet_state = "ready"
bullets.append([x + 12, y + 6]) # Creating a new bullet
...
while running:
...
if bullet_state is "fire":
firebullet(playerX, bulletY)
# bulletY -= bulletychange # No longer necessary, we'll do this right afterwards
for bullet in bullets:
screen.blit(bulletimg, (bullet[0], bullet[1])) # Print a bullet
bullet[0] -= bulletxchange # Updates its position
bullet[1] -= bulletychange
if bullet[1] < 0:
bullets.remove(bullet) # If the bullet goes offscreen, delete it from the array
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
This question already has answers here:
How to get if a key is pressed pygame [duplicate]
(1 answer)
Not letting the character move out of the window
(2 answers)
Closed 2 years ago.
So I've written my border code under #Border but I don't know whats wrong with it. When I run the program the icon collides with the border only on when it reaches zero for both the x and y axis not when it reaches the maximum for both x and y-64 pixels. Also I was wondering how would you rotate an image based off of user key input.
import pygame
pygame.init()
screen = pygame.display.set_mode((900, 500))
# Game Window caption
pygame.display.set_caption("Snake Time")
# Game Window Icon
icon = pygame.image.load('snake.png')
pygame.display.set_icon(icon)
# Snake Player Image
Snake_Player = pygame.image.load('Snake Head.png')
PlayerX = 420
PlayerY = 435
PlayerX_Change = 0
PlayerY_Change = 0
def player(x, y):
screen.blit(Snake_Player, (x, y))
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Player Movement
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
PlayerX_Change = -0.7
PlayerY_Change = 0
if event.key == pygame.K_RIGHT:
PlayerX_Change = 0.7
PlayerY_Change = 0
if event.key == pygame.K_UP:
PlayerY_Change = -0.7
PlayerX_Change = 0
if event.key == pygame.K_DOWN:
PlayerY_Change = 0.7
PlayerX_Change = 0
#Border
if PlayerX <= 0:
PlayerX = 0
elif PlayerX >= 836:
PlayerX = 0
elif PlayerY <= 0:
PlayerY = 0
elif PlayerY >= 500:
PlayerY = 0
PlayerX += PlayerX_Change
PlayerY += PlayerY_Change
# Game Window Color
screen.fill((30, 90, 0))
player(PlayerX, PlayerY)
pygame.display.update()
I recommend to use pygame.key.get_pressed() for the movement of the player, rather than the KEYDOWN event.
Furthermore, use a pygame.Rect to evaluate the collisions with the border. Rectangle with the size of the pygame.Surface can be get by the get_rect() method:
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Player Movement
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
PlayerX -= 0.7
if keys[pygame.K_RIGHT]:
PlayerX += 0.7
if keys[pygame.K_UP]:
PlayerY -= 0.7
if keys[pygame.K_DOWN]:
PlayerY += 0.7
#Border
player_rect = Snake_Player.get_rect(topleft = (PlayerX, PlayerY))
if player_rect.left < 0:
PlayerX = 0
elif player_rect.right > screen.get_width():
PlayerX = screen.get_width() - player_rect.width
if player_rect.top < 0:
PlayerY = 0
elif player_rect.bottom > screen.get_height():
PlayerY = screen.get_height() - player_rect.height
# Game Window Color
screen.fill((30, 90, 0))
player(PlayerX, PlayerY)
pygame.display.update()
try this and continue with the other keys:
if keys[pygame.K_LEFT] and PlayerX - 0.7 > 0:
PlayerX - 0.7