I am currently attempting to programm a small game. An enemy is supposed to chase the player, the actual chasing is not implemented yet. I still need to figure out how to do that, but that's not the question.
I have made it so that the player returns to the start point once they collide with the enemy. In addition to that, a text 'Game over' is supposed to appear. The function for that is called at the end of the game loop and while the text appeared briefly(it actually only appeared once, I have tried it multiple times), it does not stay. I was planing on making it appear and then disappear after a few seconds so that the player can play again, but I'm not sure why it disappears instantly.
If this is the wrong place to post this, please tell me, I will delete this post. This is my code, would be amazing if somebody could help me out:
import pygame #imports pygame
import math
pygame.init()
#screen
screen = pygame.display.set_mode((800,600)) #width and height
#title and icon
pygame.display.set_caption("The Great Chase") #changes title
icon = pygame.image.load('game-controller.png')
pygame.display.set_icon(icon) #setting icon
#player
playerImg = pygame.image.load('scary-monster.png')
playerX = 370
playerY = 480
playerX_change = 0
playerY_change = 0
#enemy
enemyImg = pygame.image.load('caterpillar.png')
enemyX = 370
enemyY = 50
enemyX_change = 0
enemyY_change = 0
#GAME OVER
game_over_font = pygame.font.Font('Bubblegum.ttf',64)
def game_over_text():
game_over_text = game_over_font.render("GAME OVER", True, (255, 0, 0))
screen.blit(game_over_text, (200, 250))
def player(x, y): #function for player
screen.blit(playerImg, (x, y)) #draws image of player, blit -> means to draw
def enemy(x, y): #function for enemy
screen.blit(enemyImg,(x,y))
def isCollision(playerX, playerY, enemyX, enemyY):
distance = math.sqrt((math.pow(playerX-enemyX,2)) + (math.pow(playerY - enemyY,2)))
if distance < 25:
return True
else:
return False
def chase():
distance = math.sqrt((math.pow(playerX-enemyX,2)) + (math.pow(playerY - enemyY,2)))
#Game loop
running = True
while running:
screen.fill((255,255,0)) #0-255 RGB-> red, green & blue
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# if keystroke check whether right or left or up or down
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_UP:
playerY_change = -0.2
if event.key == pygame.K_DOWN:
playerY_change = 0.2
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
playerY_change = 0
playerX += playerX_change
playerY += playerY_change
#creating borders so that player won't leave screen
if playerX <=0:
playerX = 0
elif playerX >=768:
playerX = 768
if playerY <= 0:
playerY = 0
elif playerY >=568:
playerY = 568
#collision
collision = isCollision(playerX, playerY, enemyX, enemyY)
if collision:
playerY = 480
game_over_text()
player(playerX, playerY)
enemy(enemyX, enemyY)
pygame.display.update()
The collision only occurs for a moment and the game over text is only shown when the object collides. If you want to persist the text, set a gameover variable when the collision is detected and display the text based on the state of the variable:
gameover = False
running = True
while running:
# [...]
collision = isCollision(playerX, playerY, enemyX, enemyY)
if collision:
playerY = 480
gameover = True
player(playerX, playerY)
enemy(enemyX, enemyY)
if gameover:
game_over_text()
pygame.display.update()
Note, collision is set in every frame depending on the position of the objects. However, gameover is set once when a collision occurs and then maintains its state.
Related
This question already has answers here:
Countdown timer in Pygame
(8 answers)
Spawning multiple instances of the same object concurrently in python
(1 answer)
Closed 5 months ago.
I am new to pygame programming and I am making a game with the help of tutorials. I finished the tutorial and want to add a new feature to my game.
Game Overview
I have created a space invader game where there are enemies moving on the x-axis and slowly coming down. In bottom there is a space ship which can move on the x axis and can shoot bullets to destroy or kill the enemies. The enemies respawn after being killed and if an enemy reaches the bottom, it is game over
Code
# importing modules
import pygame
import random
import math
from pygame import mixer
# initialize pygame
pygame.init()
# creating a window
screen = pygame.display.set_mode((800, 600))
# Background Music
mixer.music.load('background.wav')
mixer.music.play(-1)
# Background
bg_img = pygame.image.load("background3.png")
bg = pygame.transform.scale(bg_img, (800, 600))
# Title and Icon
pygame.display.set_caption("Space Shooters")
icon = pygame.image.load('spaceship.png')
pygame.display.set_icon(icon)
# Player
player = pygame.image.load('spaceship2.png')
playerX = 370
playerY = 500
playerX_change = 0
# Enemy
enemyImg = []
enemyX = []
enemyY = []
enemyX_change = []
enemyY_change = []
num_of_enemies = 6
for i in range(num_of_enemies):
enemyImg.append(pygame.image.load('enemy.png'))
enemyX.append(random.randint(6, 730))
enemyY.append(random.randint(45, 150))
enemyX_change.append(0.3)
enemyY_change.append(40)
# Bullet
# Ready - The bullet can't be seen
# Fire - The bullet has been shot
bulletImg = pygame.image.load('bullet.png')
bulletX = 0
bulletY = 480
bulletX_change = 0
bulletY_change = 1.5
bullet_state = "Ready"
# Score
score_value = 0
font = pygame.font.Font('freesansbold.ttf', 32)
textX = 10
textY = 10
# Game Over
over_font = pygame.font.Font('freesansbold.ttf', 64)
# Function for displaying text
def show_score(x, y):
score = font.render("Score : " + str(score_value), True, (255, 255, 255))
screen.blit(score, (x, y))
def game_over_text():
over_text = over_font.render("GAME OVER", True, (255, 255, 255))
screen.blit(over_text, (200, 250))
# Defining and drawing spaceship
def spaceship(x, y):
screen.blit(player, (x, y))
# Defining and drawing enemy
def enemy(x, y, i):
screen.blit(enemyImg[i], (x, y))
def fire_bullet(x, y):
global bullet_state
bullet_state = "Fire"
screen.blit(bulletImg, (x + 16, y + 10))
def Iscollision(enemyX, enemyY, bulletX, bulletY):
distance = math.sqrt((math.pow(enemyX - bulletX, 2)) + (math.pow(enemyY - bulletY, 2)))
if distance < 27:
return True
else:
return False
# making the game window run endlessly and game loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Keystroke check (right, left)
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.key == pygame.K_SPACE:
# Checking whether bullet is there on screen, if not making it ready, if yes disabling spacebar
if bullet_state == "Ready":
# Get the current X cordinate of spaceship
bulletX = playerX
fire_bullet(bulletX, bulletY)
bullet_sound = mixer.Sound('laser.wav')
bullet_sound.play()
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
# Changing X coordinates to move spaceship
playerX += playerX_change
if playerX <= 6:
playerX = 6
elif playerX >= 730:
playerX = 730
screen.fill(0)
screen.blit(bg, (0, 0))
# Enemy Movement
for i in range(num_of_enemies):
# Game Over
if enemyY[i] > 440:
for j in range(num_of_enemies):
enemyY[j] = 2000
game_over_text()
break
for i in range(num_of_enemies):
enemyX[i] += enemyX_change[i]
if enemyX[i] <= 6:
enemyX_change[i] = 0.3
enemyY[i] += enemyY_change[i]
elif enemyX[i] >= 730:
enemyX_change[i] = -0.3
enemyY[i] += enemyY_change[i]
# Collision
collision = Iscollision(enemyX[i], enemyY[i], bulletX, bulletY)
# if collision and if collision is true are both the same
if collision:
collision_sound = mixer.Sound('explosion.wav')
collision_sound.play()
bulletY = 480
bullet_state = "Ready"
score_value += 1
enemyX[i] = random.randint(6, 730)
enemyY[i] = random.randint(45, 150)
enemy(enemyX[i], enemyY[i], i)
# Deleting each frame of enemy moving so that it runs smoothly
# Bullet Movement
if bulletY <= 0:
bulletY = 480
bullet_state = "Ready"
if bullet_state == "Fire":
fire_bullet(bulletX, bulletY)
bulletY -= bulletY_change
spaceship(playerX, playerY)
show_score(textX, textY)
# updating display
pygame.display.update()
New Feature
I want to add a feature that when a laser ( I have a picture) hits the spaceship, shot by the enemies, the spaceship can't move for 10 seconds. I have already tryed other stack overflow questions but they don't match my needs.
If you only have one cooldown to manage, a simple and clean way to do it is by using a custom event :
# Custom event
COOLDOWN_END = pg.USEREVENT
When you detect a collision you simply start a timer :
# Custom event
pg.time.set_timer(COOLDOWN_END, 1000, 1)
The first parameter is the event you are going to send to your event handler, the 2nd is the time in ms (so 1 sec here) and last one is the number of iteration. Here you just want to send the event once, so put 1.
The last step is to do catch this event in your handler and do what you want with it :
for evt in pg.event.get():
if evt.type == pg.QUIT:
exit()
if evt.type == COOLDOWN_END:
print(evt)
# Your logic goes here
Let's put everything together :
(Here, I simply used this technique to have a COOLDOWN_END event 1 sec after I clicked)
# General imports
import pygame as pg
import sys
# Init
pg.init()
# Vars
screen = pg.display.set_mode((500, 500))
pg.display.set_caption("name")
# Clock
FPS = 60
clock = pg.time.Clock()
# Custom event
COOLDOWN_END = pg.USEREVENT
# Main functions
def update():
pass
def draw():
# Clear screen
screen.fill((0,0,0))
def handle_evt():
for evt in pg.event.get():
if evt.type == pg.QUIT:
exit()
if evt.type == pg.KEYDOWN:
if evt.key == pg.K_ESCAPE:
exit()
if evt.type == pg.MOUSEBUTTONDOWN:
if evt.button == 1:
on_click()
if evt.type == COOLDOWN_END:
print(evt)
def on_click():
pg.time.set_timer(COOLDOWN_END, 1000, 1)
def exit():
pg.quit()
sys.exit()
# Main loop
if __name__ == '__main__':
while True:
handle_evt()
update()
draw()
clock.tick(FPS)
pg.display.flip()
You may use custom event with from pygame.locals import USEREVENT.
An alternative is to keep track of time of when you got hit using pygame.time.get_ticks() + some stun cooldown system, and applying only to the portion of the code involved with player movement.
stun_duration = 10000 # milliseconds
damaged_timestamp = -stun_duration # allows to get stunned starting from pygame.init() call
running = True
while running:
for event in pygame.event.get():
# preceding code
# check if beyond stun cooldown
if pygame.time.get_ticks() - damaged_timestamp > stun_duration:
damaged_timestamp = pygame.time.get_ticks()
# Keystroke check (right, left)
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.key == pygame.K_SPACE:
# Checking whether bullet is there on screen, if not making it ready, if yes disabling spacebar
if bullet_state == "Ready":
# Get the current X cordinate of spaceship
bulletX = playerX
fire_bullet(bulletX, bulletY)
bullet_sound = mixer.Sound('laser.wav')
bullet_sound.play()
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
playerX_change = 0
# Changing X coordinates to move spaceship
playerX += playerX_change
if playerX <= 6:
playerX = 6
elif playerX >= 730:
playerX = 730
# proceeding code
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()
Pygame is perfectly installed, everything else is working fine spaceship movement and enemy movement but i am not able to see the bullet which i have drawn from inside the fire_bullet function, I have tried drawing it from outside the function and that does seem to work .
import pygame
import os
import random
pygame.init()
#Screen
screen = pygame.display.set_mode((800, 600))
#Title and Icon
pygame.display.set_caption('Space Invaders ')
UFO = pygame.image.load(os.path.join('Assets2', 'ufo.png'))
pygame.display.set_icon(UFO)
#player
playerImg = pygame.image.load(os.path.join('Assets2', 'spaceship.png'))
playerX = 370
playerY = 480
VEL = 0
def player(x, y):
screen.blit(playerImg, (x, y))
#enemy
enemyImg = pygame.image.load(os.path.join('Assets2', 'enemy.png'))
enemyimg1 = pygame.transform.scale(enemyImg, (45, 50))
enemyX = random.randint(0,800)
enemyY = random.randint(50,150)
enemyX_change = 0.7
enemyY_change = 40
def enemy(x,y):
screen.blit(enemyimg1, (x, y))
#background
bg = pygame.image.load(os.path.join('Assets2', 'space.png'))
#bullet
bulletimg = pygame.image.load(os.path.join('Assets2', 'bullet.png'))
bulletX = 0
bulletY = 480
bulletX_change = 0
bulletY_change = 10
bullet_state = "ready" #Ready - Rest, Fire - Motion
def fire_bullet(x,y):
global bullet_state
bullet_state = "fire"
screen.blit(bulletimg, (x+16, y+10))
run = True
#Game loop
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# Movement
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
VEL = -1.4
if event.key == pygame.K_RIGHT:
VEL= 1.4
# Bullet positioning
if event.key == pygame.K_SPACE:
fire_bullet(playerX, bulletY)
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
VEL = 0
playerX += VEL
# Restricting boundaries of spaceship
if playerX <= 0:
playerX = 0
elif playerX >= 736:
playerX = 736
enemyX += enemyX_change
# Restricting boundaries of Enemy
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
screen.fill((255,255,0))
screen.blit(bg, (0,0))
player(playerX, playerY)
enemy(enemyX, enemyY)
pygame.display.update()
Also all the assets are fine and dowloaded correctly so idk why is it still not showing the bullet drawn from inside the function
Your bullet is so fast that you can barely see it. You have to limit the frames per second. Use pygame.time.Clock to control the frames per second and thus the game speed.
The method tick() of a pygame.time.Clock object, delays the game in that way, that every iteration of the loop consumes the same period of time. See pygame.time.Clock.tick():
This method should be called once per frame.
e.g.:
clock = pygame.time.Clock()
#Game loop
while run:
clock.tick(60)
# [...]
This question already has answers here:
How to detect collisions between two rectangular objects or images in pygame
(1 answer)
Why is my collision test always returning 'true' and why is the position of the rectangle of the image always wrong (0, 0)?
(1 answer)
How do I detect collision in pygame?
(5 answers)
Closed 2 years ago.
import pygame
import os
pygame.init()
# Images
bgImg = pygame.image.load("Images/background.png")
playerImgRight = (pygame.image.load("Images/playerRight.png"))
playerImgLeft = pygame.image.load("Images/playerLeft.png")
playerImgBack = pygame.image.load("Images/playerBack.png")
chestClosed = pygame.transform.scale(pygame.image.load("Images/chestsClosed.png"), (30, 40))
chestOpened = pygame.transform.scale(pygame.image.load("Images/chestOpen.png"), (30, 40))
currentPlayerImg = playerImgBack
screen = pygame.display.set_mode((800, 800))
pygame.display.set_caption("Richmonia")
pygame.display.set_icon(currentPlayerImg)
clock = pygame.time.Clock()
playerX = 380
playerY = 380
playerXSpeed = 0
playerYSpeed = 0
Chest Class
I want but the collision detection in the chest update function
class Chest:
def __init__(self, x, y, openImage, closeImage, playerX, playerY):
self.x = x
self.y = y
self.openImage = openImage
self.closeImage = closeImage
self.currentImage = self.closeImage
self.playerX = playerX
self.playerY = playerY
def update(self):
print("Placeholder")
def show(self):
screen.blit(self.currentImage, (self.x, self.y))
chestOne = Chest(100, 100, chestOpened, chestClosed, playerX, playerY)
running = True
while running:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
currentPlayerImg = playerImgBack
playerYSpeed = -5
if event.key == pygame.K_DOWN:
currentPlayerImg = playerImgBack
playerYSpeed = 5
if event.key == pygame.K_LEFT:
currentPlayerImg = playerImgLeft
playerXSpeed = -5
if event.key == pygame.K_RIGHT:
currentPlayerImg = playerImgRight
playerXSpeed = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
playerYSpeed = 0
if event.key == pygame.K_DOWN:
playerYSpeed = 0
if event.key == pygame.K_LEFT:
playerXSpeed = 0
if event.key == pygame.K_RIGHT:
playerXSpeed = 0
if playerY <= 0:
playerY = 0
if playerY >= 740:
playerY = 740
if playerX <= 0:
playerX = 0
if playerX >= 760:
playerX = 760
playerX += playerXSpeed
playerY += playerYSpeed
screen.blit(bgImg, (0, 0))
chestOne.show()
chestOne.update()
screen.blit(currentPlayerImg, (playerX, playerY))
pygame.display.update()
pygame.quit()
quit()
I know there is a way with sprites but I want to know if there is a way to do it with just the images.
Also bonus question how to I get the fps.
Use a pygame.Rect object and colliderect() to find a collision between a rectangle and an object.
pygame.Surface.get_rect.get_rect() returns a rectangle with the size of the Surface object, that always starts at (0, 0) since a Surface object has no position. The position of the rectangle can be specified by a keyword argument:
running = True
while running:
# [...]
player_rect = currentPlayerImg.get_rect(topleft = (playerX, playerY))
chestOne_rect = chestOne.currentImage.get_rect(topleft = (self.x, self.y))
if player_rect .colliderect(chestOne_rect):
print("hit")
# [...]
The method tick() of a pygame.time.Clock object, delays the game in that way, that every iteration of the loop consumes the same period of time.
So in your case the frames per second are 60:
while running:
clock.tick(60)
pygame.time.Clock.tick returns the number of milliseconds passed since the previous call. If you call it in the application loop, then this is the number of milliseconds passed since the last frame.
while run:
ms_since_last_frame = clock.tick(60)
I made a loop to keep the "enemy" character moving to left and right, but for some reason that I really can't tell why, he just goes to the right and when he hits the border limit that I defined, he "teleports" to the left border and keeps going to the right forever. I even tried to make the "enemyX_change" beeing negative, but he just goes to the left, hit the border and stops. I'm using Python 3.8.
import pygame
import random
# Initiate pygame
pygame.init()
# Display the game window
screen = pygame.display.set_mode((800, 600))
# Title and Icon
pygame.display.set_caption('Space Invaders')
icon = pygame.image.load('icon.png')
pygame.display.set_icon(icon)
# Player
playerSprite = pygame.image.load('player.png')
playerX = 370
playerY = 480
playerX_change = 0
# Enemy
enemySprite = pygame.image.load('enemy.png')
enemyX = random.randint(0, 736)
enemyY = random.randint(50, 150)
enemyX_change = 0.3
enemyY_change = 0
def player(x, y):
screen.blit(playerSprite, (x, y))
def enemy(x, y):
screen.blit(enemySprite, (x, y))
# Game Loop
running = True
while running:
# Background color (RGB)
screen.fill((0, 0, 0))
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# If a key is pressed, check if it's the right or left arrow key
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
# Move the spaceship to the left or right
playerX += playerX_change
# Prevents the player from going off the border
if playerX <= 0:
playerX = 0
elif playerX >= 736:
playerX = 736
# Moves the enemy
enemyX += enemyX_change
# Prevents the enemy from going off the border
if enemyX <= 0:
enemyX = 0.3
elif enemyX >= 736:
enemyX = -0.3
player(playerX, playerY)
enemy(enemyX, enemyY)
pygame.display.update()
When the enemy goes out of bounds, then you have to change the movement direction (enemyX_change) rather than the position of the player (enemyX):
enemyX = -0.3
enemyX_change *= -1
Invert enemyX_change when it is less than 0 or greater than the width of the window:
# Moves the enemy
enemyX += enemyX_change
# Prevents the enemy from going off the border
if enemyX <= 0 or enemyX >= 736:
enemyX_change *= -1