Pygame: problems with shooting in Space Invaders - python

I've been attempting to make a Space Invaders clone in pygame. I decided to write it so that the bullet shot from the player's ship can only be fired again when it leaves the screen but I've not been capable of doing so. How do I do it?
import pygame
pygame.init()
screen_size = (500, 500)
ship_size = (50, 50)
x, y = 250, 450
x_rect, y_rect = x + 15, y - 20
height_rect, width_rect = 20, 20
vel = 50
shoot = False
"""Loads screen and set gives it a title."""
screen = pygame.display.set_mode(screen_size)
pygame.display.set_caption("Space Invaders")
"""Initializes images for the game and resizes them."""
space_ship = pygame.image.load("Space Invaders Ship.jpg")
space_ship = pygame.transform.scale(space_ship, ship_size)
space = pygame.image.load("Space.jpg")
space = pygame.transform.scale(space, screen_size)
clock = pygame.time.Clock()
run = True
while run:
"""Controls the fps."""
clock.tick(60)
"""Registers keyboard's input."""
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and x > 0:
x -= vel
elif event.key == pygame.K_RIGHT and x + 50 < 500:
x += vel
elif event.key == pygame.K_SPACE:
x_rect, y_rect = x + 15, y - 20
shoot = True
"""Constantly draws on the screen."""
screen.fill((0, 0, 0))
screen.blit(space, (0, 0))
screen.blit(space_ship, [x, y])
"""Shoots a bullet from where the ship currently is."""
if shoot:
pygame.draw.rect(screen, (250, 250, 0),
[x_rect, y_rect, height_rect, width_rect])
y_rect -= 5
elif y_rect + width_rect > 0:
shoot = False
y_rect = y - 20
pygame.display.flip()

You have to create a list of bullets:
bullet_list = []
Add a new bullet position to the list when SPACE is pressed:
elif event.key == pygame.K_SPACE:
bullet_list.append([x + 15, y - 20])
Move and draw the bullets in the list in a loop:
for bullet in bullet_list:
pygame.draw.rect(screen, (250, 250, 0),
[*bullet, height_rect, width_rect])
bullet[1] -= 5
Delete a bullet from the list if the y-coordinate is less than 0:
for bullet in bullet_list[:]:
if bullet[1] < 0:
bullet_list.remove(bullet)
Complete example:
import pygame
pygame.init()
screen_size = (500, 500)
ship_size = (50, 50)
x, y = 250, 450
x_rect, y_rect = x + 15, y - 20
height_rect, width_rect = 20, 20
vel = 50
bullet_list = []
"""Loads screen and set gives it a title."""
screen = pygame.display.set_mode(screen_size)
pygame.display.set_caption("Space Invaders")
"""Initializes images for the game and resizes them."""
space_ship = pygame.image.load("Space Invaders Ship.jpg")
space_ship = pygame.transform.scale(space_ship, ship_size)
space = pygame.image.load("Space.jpg")
space = pygame.transform.scale(space, screen_size)
clock = pygame.time.Clock()
run = True
while run:
"""Controls the fps."""
clock.tick(60)
"""Registers keyboard's input."""
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and x > 0:
x -= vel
elif event.key == pygame.K_RIGHT and x + 50 < 500:
x += vel
elif event.key == pygame.K_SPACE:
bullet_list.append([x + 15, y - 20])
"""Constantly draws on the screen."""
screen.fill((0, 0, 0))
screen.blit(space, (0, 0))
screen.blit(space_ship, [x, y])
"""Shoots a bullet from where the ship currently is."""
for bullet in bullet_list:
pygame.draw.rect(screen, (250, 250, 0),
[*bullet, height_rect, width_rect])
bullet[1] -= 5
for bullet in bullet_list[:]:
if bullet[1] < 0:
bullet_list.remove(bullet)
pygame.display.flip()

Related

Pygame take actions when releasing key [duplicate]

I want to make my character jump. In my current attempt, the player moves up as long as I hold down SPACEv and falls down when I release SPACE.
import pygame
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
rect = pygame.Rect(135, 220, 30, 30)
vel = 5
run = True
while run:
clock.tick(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
rect.centerx = (rect.centerx + (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel) % 300
if keys[pygame.K_SPACE]:
rect.y -= 1
elif rect.y < 220:
rect.y += 1
window.fill((0, 0, 64))
pygame.draw.rect(window, (64, 64, 64), (0, 250, 300, 100))
pygame.draw.circle(window, (255, 0, 0), rect.center, 15)
pygame.display.flip()
pygame.quit()
exit()
However, I want the character to jump if I hit the SPACE once. I want a smooth jump animation to start when SPACE is pressed once.
How would I go about this step by step?
To make a character jump you have to use the KEYDOWN event, but not pygame.key.get_pressed(). pygame.key.get_pressed () is for continuous movement when a key is held down. The keyboard events are used to trigger a single action or to start an animation such as a jump. See alos How to get keyboard input in pygame?
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.
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
jump = True
Use pygame.time.Clock ("This method should be called once per frame.") you control the frames per second and thus the game speed and the duration of the jump.
clock = pygame.time.Clock()
while True:
clock.tick(100)
The jumping should be independent of the player's movement or the general flow of control of the game. Therefore, the jump animation in the application loop must be executed in parallel to the running game.
When you throw a ball or something jumps, the object makes a parabolic curve. The object gains height quickly at the beginning, but this slows down until the object begins to fall faster and faster again. The change in height of a jumping object can be described with the following sequence:
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10]
Such a series can be generated with the following algorithm (y is the y coordinate of the object):
jumpMax = 10
if jump:
y -= jumpCount
if jumpCount > -jumpMax:
jumpCount -= 1
else:
jump = False
A more sophisticated approach is to define constants for the gravity and player's acceleration as the player jumps:
acceleration = 10
gravity = 0.5
The acceleration exerted on the player in each frame is the gravity constant, if the player jumps then the acceleration changes to the "jump" acceleration for a single frame:
acc_y = gravity
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if vel_y == 0 and event.key == pygame.K_SPACE:
acc_y = -acceleration
In each frame the vertical velocity is changed depending on the acceleration and the y-coordinate is changed depending on the velocity. When the player touches the ground, the vertical movement will stop:
vel_y += acc_y
y += vel_y
if y > ground_y:
y = ground_y
vel_y = 0
acc_y = 0
See also Jump
Example 1: replit.com/#Rabbid76/PyGame-Jump
import pygame
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
rect = pygame.Rect(135, 220, 30, 30)
vel = 5
jump = False
jumpCount = 0
jumpMax = 15
run = True
while run:
clock.tick(50)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if not jump and event.key == pygame.K_SPACE:
jump = True
jumpCount = jumpMax
keys = pygame.key.get_pressed()
rect.centerx = (rect.centerx + (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel) % 300
if jump:
rect.y -= jumpCount
if jumpCount > -jumpMax:
jumpCount -= 1
else:
jump = False
window.fill((0, 0, 64))
pygame.draw.rect(window, (64, 64, 64), (0, 250, 300, 100))
pygame.draw.circle(window, (255, 0, 0), rect.center, 15)
pygame.display.flip()
pygame.quit()
exit()
Example 2: replit.com/#Rabbid76/PyGame-JumpAcceleration
import pygame
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
player = pygame.sprite.Sprite()
player.image = pygame.Surface((30, 30), pygame.SRCALPHA)
pygame.draw.circle(player.image, (255, 0, 0), (15, 15), 15)
player.rect = player.image.get_rect(center = (150, 235))
all_sprites = pygame.sprite.Group([player])
y, vel_y = player.rect.bottom, 0
vel = 5
ground_y = 250
acceleration = 10
gravity = 0.5
run = True
while run:
clock.tick(100)
acc_y = gravity
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if vel_y == 0 and event.key == pygame.K_SPACE:
acc_y = -acceleration
keys = pygame.key.get_pressed()
player.rect.centerx = (player.rect.centerx + (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel) % 300
vel_y += acc_y
y += vel_y
if y > ground_y:
y = ground_y
vel_y = 0
acc_y = 0
player.rect.bottom = round(y)
window.fill((0, 0, 64))
pygame.draw.rect(window, (64, 64, 64), (0, 250, 300, 100))
all_sprites.draw(window)
pygame.display.flip()
pygame.quit()
exit()

Pygame window jumps out and disappears immediately [duplicate]

I want to make my character jump. In my current attempt, the player moves up as long as I hold down SPACEv and falls down when I release SPACE.
import pygame
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
rect = pygame.Rect(135, 220, 30, 30)
vel = 5
run = True
while run:
clock.tick(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
rect.centerx = (rect.centerx + (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel) % 300
if keys[pygame.K_SPACE]:
rect.y -= 1
elif rect.y < 220:
rect.y += 1
window.fill((0, 0, 64))
pygame.draw.rect(window, (64, 64, 64), (0, 250, 300, 100))
pygame.draw.circle(window, (255, 0, 0), rect.center, 15)
pygame.display.flip()
pygame.quit()
exit()
However, I want the character to jump if I hit the SPACE once. I want a smooth jump animation to start when SPACE is pressed once.
How would I go about this step by step?
To make a character jump you have to use the KEYDOWN event, but not pygame.key.get_pressed(). pygame.key.get_pressed () is for continuous movement when a key is held down. The keyboard events are used to trigger a single action or to start an animation such as a jump. See alos How to get keyboard input in pygame?
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.
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
jump = True
Use pygame.time.Clock ("This method should be called once per frame.") you control the frames per second and thus the game speed and the duration of the jump.
clock = pygame.time.Clock()
while True:
clock.tick(100)
The jumping should be independent of the player's movement or the general flow of control of the game. Therefore, the jump animation in the application loop must be executed in parallel to the running game.
When you throw a ball or something jumps, the object makes a parabolic curve. The object gains height quickly at the beginning, but this slows down until the object begins to fall faster and faster again. The change in height of a jumping object can be described with the following sequence:
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10]
Such a series can be generated with the following algorithm (y is the y coordinate of the object):
jumpMax = 10
if jump:
y -= jumpCount
if jumpCount > -jumpMax:
jumpCount -= 1
else:
jump = False
A more sophisticated approach is to define constants for the gravity and player's acceleration as the player jumps:
acceleration = 10
gravity = 0.5
The acceleration exerted on the player in each frame is the gravity constant, if the player jumps then the acceleration changes to the "jump" acceleration for a single frame:
acc_y = gravity
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if vel_y == 0 and event.key == pygame.K_SPACE:
acc_y = -acceleration
In each frame the vertical velocity is changed depending on the acceleration and the y-coordinate is changed depending on the velocity. When the player touches the ground, the vertical movement will stop:
vel_y += acc_y
y += vel_y
if y > ground_y:
y = ground_y
vel_y = 0
acc_y = 0
See also Jump
Example 1: replit.com/#Rabbid76/PyGame-Jump
import pygame
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
rect = pygame.Rect(135, 220, 30, 30)
vel = 5
jump = False
jumpCount = 0
jumpMax = 15
run = True
while run:
clock.tick(50)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if not jump and event.key == pygame.K_SPACE:
jump = True
jumpCount = jumpMax
keys = pygame.key.get_pressed()
rect.centerx = (rect.centerx + (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel) % 300
if jump:
rect.y -= jumpCount
if jumpCount > -jumpMax:
jumpCount -= 1
else:
jump = False
window.fill((0, 0, 64))
pygame.draw.rect(window, (64, 64, 64), (0, 250, 300, 100))
pygame.draw.circle(window, (255, 0, 0), rect.center, 15)
pygame.display.flip()
pygame.quit()
exit()
Example 2: replit.com/#Rabbid76/PyGame-JumpAcceleration
import pygame
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
player = pygame.sprite.Sprite()
player.image = pygame.Surface((30, 30), pygame.SRCALPHA)
pygame.draw.circle(player.image, (255, 0, 0), (15, 15), 15)
player.rect = player.image.get_rect(center = (150, 235))
all_sprites = pygame.sprite.Group([player])
y, vel_y = player.rect.bottom, 0
vel = 5
ground_y = 250
acceleration = 10
gravity = 0.5
run = True
while run:
clock.tick(100)
acc_y = gravity
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if vel_y == 0 and event.key == pygame.K_SPACE:
acc_y = -acceleration
keys = pygame.key.get_pressed()
player.rect.centerx = (player.rect.centerx + (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel) % 300
vel_y += acc_y
y += vel_y
if y > ground_y:
y = ground_y
vel_y = 0
acc_y = 0
player.rect.bottom = round(y)
window.fill((0, 0, 64))
pygame.draw.rect(window, (64, 64, 64), (0, 250, 300, 100))
all_sprites.draw(window)
pygame.display.flip()
pygame.quit()
exit()

Python, how can i solve this jumping problem? [duplicate]

I want to make my character jump. In my current attempt, the player moves up as long as I hold down SPACEv and falls down when I release SPACE.
import pygame
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
rect = pygame.Rect(135, 220, 30, 30)
vel = 5
run = True
while run:
clock.tick(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
rect.centerx = (rect.centerx + (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel) % 300
if keys[pygame.K_SPACE]:
rect.y -= 1
elif rect.y < 220:
rect.y += 1
window.fill((0, 0, 64))
pygame.draw.rect(window, (64, 64, 64), (0, 250, 300, 100))
pygame.draw.circle(window, (255, 0, 0), rect.center, 15)
pygame.display.flip()
pygame.quit()
exit()
However, I want the character to jump if I hit the SPACE once. I want a smooth jump animation to start when SPACE is pressed once.
How would I go about this step by step?
To make a character jump you have to use the KEYDOWN event, but not pygame.key.get_pressed(). pygame.key.get_pressed () is for continuous movement when a key is held down. The keyboard events are used to trigger a single action or to start an animation such as a jump. See alos How to get keyboard input in pygame?
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.
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
jump = True
Use pygame.time.Clock ("This method should be called once per frame.") you control the frames per second and thus the game speed and the duration of the jump.
clock = pygame.time.Clock()
while True:
clock.tick(100)
The jumping should be independent of the player's movement or the general flow of control of the game. Therefore, the jump animation in the application loop must be executed in parallel to the running game.
When you throw a ball or something jumps, the object makes a parabolic curve. The object gains height quickly at the beginning, but this slows down until the object begins to fall faster and faster again. The change in height of a jumping object can be described with the following sequence:
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10]
Such a series can be generated with the following algorithm (y is the y coordinate of the object):
jumpMax = 10
if jump:
y -= jumpCount
if jumpCount > -jumpMax:
jumpCount -= 1
else:
jump = False
A more sophisticated approach is to define constants for the gravity and player's acceleration as the player jumps:
acceleration = 10
gravity = 0.5
The acceleration exerted on the player in each frame is the gravity constant, if the player jumps then the acceleration changes to the "jump" acceleration for a single frame:
acc_y = gravity
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if vel_y == 0 and event.key == pygame.K_SPACE:
acc_y = -acceleration
In each frame the vertical velocity is changed depending on the acceleration and the y-coordinate is changed depending on the velocity. When the player touches the ground, the vertical movement will stop:
vel_y += acc_y
y += vel_y
if y > ground_y:
y = ground_y
vel_y = 0
acc_y = 0
See also Jump
Example 1: replit.com/#Rabbid76/PyGame-Jump
import pygame
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
rect = pygame.Rect(135, 220, 30, 30)
vel = 5
jump = False
jumpCount = 0
jumpMax = 15
run = True
while run:
clock.tick(50)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if not jump and event.key == pygame.K_SPACE:
jump = True
jumpCount = jumpMax
keys = pygame.key.get_pressed()
rect.centerx = (rect.centerx + (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel) % 300
if jump:
rect.y -= jumpCount
if jumpCount > -jumpMax:
jumpCount -= 1
else:
jump = False
window.fill((0, 0, 64))
pygame.draw.rect(window, (64, 64, 64), (0, 250, 300, 100))
pygame.draw.circle(window, (255, 0, 0), rect.center, 15)
pygame.display.flip()
pygame.quit()
exit()
Example 2: replit.com/#Rabbid76/PyGame-JumpAcceleration
import pygame
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
player = pygame.sprite.Sprite()
player.image = pygame.Surface((30, 30), pygame.SRCALPHA)
pygame.draw.circle(player.image, (255, 0, 0), (15, 15), 15)
player.rect = player.image.get_rect(center = (150, 235))
all_sprites = pygame.sprite.Group([player])
y, vel_y = player.rect.bottom, 0
vel = 5
ground_y = 250
acceleration = 10
gravity = 0.5
run = True
while run:
clock.tick(100)
acc_y = gravity
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if vel_y == 0 and event.key == pygame.K_SPACE:
acc_y = -acceleration
keys = pygame.key.get_pressed()
player.rect.centerx = (player.rect.centerx + (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel) % 300
vel_y += acc_y
y += vel_y
if y > ground_y:
y = ground_y
vel_y = 0
acc_y = 0
player.rect.bottom = round(y)
window.fill((0, 0, 64))
pygame.draw.rect(window, (64, 64, 64), (0, 250, 300, 100))
all_sprites.draw(window)
pygame.display.flip()
pygame.quit()
exit()

How do I update the text in python pygame when a certain command is true?

I'm trying to build a space invader-like game for fun.
It's mostly done, but when I shoot the enemy I want the text on the screen with his health to decrease.
Here is my code stripped only to the health updating part:
import pygame
from sys import exit
enemy_health = 10
pygame.init()
win = pygame.display.set_mode((1000, 1000))
pygame.display.set_caption("Fighter Pilot Go!")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 55)
enemy_health_text = font.render(f'Enemy Health: {enemy_health}', False, 'white')
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
enemy_health_text -= 1
win.blit(enemy_health_text, (350, 60)
That's not all of the game, but it's the basic idea.
The score doesn't update in the game till a laser hits the enemy.
Here is the whole game, if the code helps you understand my issue:
import pygame
from sys import exit
import random
speed = 5
laser_speed = 7
bullets = []
score = 0
max_num_of_bullet = 3
background_speed = 3
enemy_health = 10
direction = True
enemy_speed = 7
pygame.init()
win = pygame.display.set_mode((1000, 1000))
pygame.display.set_caption("Fighter Pilot Go!")
clock = pygame.time.Clock()
background1 = pygame.image.load('assets/background.gif')
background2 = pygame.image.load('assets/background.gif')
background1_rect = background1.get_rect(topleft=(0, 0))
background2_rect = background2.get_rect(topleft=(0, -1000))
player = pygame.image.load('assets/player.gif')
player_rect = player.get_rect(midtop=(500, 750))
enemy = pygame.image.load('assets/enemy.gif')
enemy_rect = enemy.get_rect(center=(500, 350))
laser = pygame.image.load('assets/laser.gif')
# laser_rect = laser.get_rect(midtop=(500, 800))
font = pygame.font.Font(None, 55)
enemy_health_text = font.render(f'Enemy Health: {enemy_health}', False, 'white')
def is_collided_with(a, b):
return abs(a[0] - b.centerx) < 51 and abs(a[1] - b.centery) < 51
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
if len(bullets) <= max_num_of_bullet - 1:
bullets.append([player_rect.x + 49, player_rect.y - 60])
elif len(bullets) > max_num_of_bullet - 1:
continue
else:
print("Something Weird is Happening!")
key = pygame.key.get_pressed()
if key[pygame.K_a]:
player_rect.x -= speed
if key[pygame.K_d]:
player_rect.x += speed
win.blit(background1, background1_rect)
win.blit(background2, background2_rect)
win.blit(player, player_rect)
win.blit(enemy, enemy_rect)
background1_rect.y += background_speed
background2_rect.y += background_speed
if direction:
enemy_rect.x -= enemy_speed
elif not direction:
enemy_rect.x += enemy_speed
if enemy_rect.x <= 0:
direction = False
elif enemy_rect.x >= 900:
direction = True
if player_rect.x < -20:
player_rect.x = 1020
if player_rect.x > 1020:
player_rect.x = -20
for bullet in bullets:
win.blit(laser, bullet)
for bullet in bullets:
bullet[1] -= laser_speed
win.blit(enemy_health_text, (350, 60))
for bullet in bullets:
if is_collided_with(bullet, enemy_rect):
bullets.remove(bullet)
enemy_health -= 1
for bullet in bullets:
if bullet[1] < 0:
bullets.remove(bullet)
if background1_rect.y >= 1000:
background1_rect.topleft = (0, -1000)
if background2_rect.y >= 1000:
background2_rect.topleft = (0, -1000)
if enemy_health <= 0:
pass
pygame.display.update()
clock.tick(60)
Any help would be appreciated. :) Thanks!
The text is rendered in the enemy_health_text Surface with the value of enemy_health. You have to change enemy_health and render the text again:
font = pygame.font.Font(None, 55)
enemy_health_text = font.render(f'Enemy Health: {enemy_health}', False, 'white')
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
enemy_health -= 1
enemy_health_text = font.render(f'Enemy Health: {enemy_health}', False, 'white')
win.fill(0)
win.blit(enemy_health_text, (350, 60)
pygame.display.flip()

Pygame: Spaceinvaders: can't shoot bullets

I am currently building a mockup of space invaders.
I want to make the user shoot stuff and the invaders will die (1hit kill), but I can't seem to figure out how to do that. I have tried drawing a small rectangle, but then the background paints over it. Thanks for your help!
import pygame, sys, random
from pygame.locals import *
# set up pygame
pygame.init()
mainClock = pygame.time.Clock()
# set up the window
windowwidth = 800
windowheight = 700
windowSurface = pygame.display.set_mode((windowwidth, windowheight), 0, 32)
pygame.display.set_caption('Sp#c3 inv#d3r5')
# set up movement variables
moveLeft = False
moveRight = False
moveUp = False
moveDown = False
# set up direction variables
DOWNLEFT = 1
DOWNRIGHT = 3
UPLEFT = 7
UPRIGHT = 9
LEFT = 4
RIGHT = 6
UP = 8
DOWN = 2
MOVESPEED = 10
MOVE = 2
# set up counting
score = 0
# set up the colors
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (135, 206, 250)
# set up font
font = pygame.font.SysFont(None, 50)
def makeship(windowwidth): # set up the bouncer and food data structures
user = pygame.Rect(350, 600, 100, 25)
return user
def drawwalls(walls):
for i in range(6):
wall = pygame.Rect(0,i+1,100,25)
pygame.draw.rect(windowSurface,GREEN,wall)
walls.append(wall)
def makeinvaders(invaders):
y = 0
for i in invaders: # each row
x = 0
for j in range(10):
# create invader
invader = pygame.Rect(75+x, 100+y, 40, 25)
# append invader to invaders[row]
i.append(invader)
# increase invader's x attribute by 50
x += 60
# increase invaders y by 35
y += 45
return invaders
def movepaddle(user):
# move the paddle
if moveLeft and user.left > 0:
user.left -= MOVESPEED
if moveRight and user.right < windowwidth:
user.right += MOVESPEED
return user
def moveinvaders(invaders, invdir):
# move the invaders
for row in invaders:
for invader in row:
if invdir == RIGHT and invaders[1][9].right < windowwidth:
invader.right += MOVE
elif invaders[1][9].right > windowwidth:
invader.left -= MOVE
invdir = LEFT
if invdir == LEFT and invaders[0][0].left > 0:
invader.left -= MOVE
elif invaders[0][0].left < 0:
invader.right += MOVE
invdir = RIGHT
return invdir
def shootbullets(windowSurface,blue2):
x = pygame.Rect(400,595,2,5)
pygame.draw.rect(windowSurface,GREEN,x)
def movebullets(bullets):
for bullet in bullets:
pass
def drawstuff(user, invaders):
# draw the user onto the surface
pygame.draw.rect(windowSurface, BLACK, user)
for i in invaders:
for invader in i:
if invader in invaders[0]:
pygame.draw.rect(windowSurface, BLACK, invader)
elif invader in invaders[1]:
pygame.draw.rect(windowSurface, BLACK, invader)
elif invader in invaders[2]:
pygame.draw.rect(windowSurface, BLACK, invader)
elif invader in invaders[3]:
pygame.draw.rect(windowSurface, BLACK, invader)
elif invader in invaders[4]:
pygame.draw.rect(windowSurface, BLACK, invader)
invaders = [[],[],[],[],[]]
invdir = LEFT
walls = []
drawwalls(walls)
# make the figures
user = makeship(windowwidth)
# make invaders
invaders = makeinvaders(invaders)
# run the game loop
while True:
# draw the black background onto the surface
windowSurface.fill(WHITE)
# check for the QUIT event
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
# change the keyboard variables
if event.key == K_LEFT or event.key == ord('a'):
moveRight = False
moveLeft = True
if event.key == K_RIGHT or event.key == ord('d'):
moveLeft = False
moveRight = True
if event.key == K_SPACE:
shootbullets(windowSurface,RED)
if event.type == KEYUP:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
if event.key == K_LEFT or event.key == ord('a'):
moveLeft = False
if event.key == K_RIGHT or event.key == ord('d'):
moveRight = False
# draw stuff
drawstuff(user, invaders)
# move invaders
invdir = moveinvaders(invaders, invdir)
# paddle movement
user = movepaddle(user)
# draw the window onto the screen
pygame.display.update()
mainClock.tick(80)
Take a look at this minimal space invaders-like game I've written for another question:
import pygame
# you'll be able to shoot every 450ms
RELOAD_SPEED = 450
# the foes move every 1000ms sideways and every 3500ms down
MOVE_SIDE = 1000
MOVE_DOWN = 3500
screen = pygame.display.set_mode((300, 200))
clock = pygame.time.Clock()
pygame.display.set_caption("Micro Invader")
# create a bunch of events
move_side_event = pygame.USEREVENT + 1
move_down_event = pygame.USEREVENT + 2
reloaded_event = pygame.USEREVENT + 3
move_left, reloaded = True, True
invaders, colors, shots = [], [] ,[]
for x in range(15, 300, 15):
for y in range(10, 100, 15):
invaders.append(pygame.Rect(x, y, 7, 7))
colors.append(((x * 0.7) % 256, (y * 2.4) % 256))
# set timer for the movement events
pygame.time.set_timer(move_side_event, MOVE_SIDE)
pygame.time.set_timer(move_down_event, MOVE_DOWN)
player = pygame.Rect(150, 180, 10, 7)
while True:
clock.tick(40)
if pygame.event.get(pygame.QUIT): break
for e in pygame.event.get():
if e.type == move_side_event:
for invader in invaders:
invader.move_ip((-10 if move_left else 10, 0))
move_left = not move_left
elif e.type == move_down_event:
for invader in invaders:
invader.move_ip(0, 10)
elif e.type == reloaded_event:
# when the reload timer runs out, reset it
reloaded = True
pygame.time.set_timer(reloaded_event, 0)
for shot in shots[:]:
shot.move_ip((0, -4))
if not screen.get_rect().contains(shot):
shots.remove(shot)
else:
hit = False
for invader in invaders[:]:
if invader.colliderect(shot):
hit = True
i = invaders.index(invader)
del colors[i]
del invaders[i]
if hit:
shots.remove(shot)
pressed = pygame.key.get_pressed()
if pressed[pygame.K_LEFT]: player.move_ip((-4, 0))
if pressed[pygame.K_RIGHT]: player.move_ip((4, 0))
if pressed[pygame.K_SPACE]:
if reloaded:
shots.append(player.copy())
reloaded = False
# when shooting, create a timeout of RELOAD_SPEED
pygame.time.set_timer(reloaded_event, RELOAD_SPEED)
player.clamp_ip(screen.get_rect())
screen.fill((0, 0, 0))
for invader, (a, b) in zip(invaders, colors):
pygame.draw.rect(screen, (150, a, b), invader)
for shot in shots:
pygame.draw.rect(screen, (255, 180, 0), shot)
pygame.draw.rect(screen, (180, 180, 180), player)
pygame.display.flip()
It uses colliderect to detect collisions, which your code is missing.
Also, the code in general and especially the movement code is a lot simpler than yours; so maybe it can serve as an inspiration for you.

Categories