So I have a task to build a game and I decided to build a Shmup or a shoot em up, in which the spaceship has to survive for as long as it can whilst dodging asteroids. I have added the base of the game, such as the movement mechanics for the spaceship and borders but I need to add asteroids, but I am very inexperienced and am a total beginner(I did this just looking through guides), so I need some help to make the asteroid code in which the asteroids randomly generate outside the screen and then come on the screen towards the player. I thank you in ahead for spending time to answer my question.
Here is the code:-
import pygame
import random
from pygame.constants import SCRAP_SELECTION
WIDTH, HEIGHT = 300, 500
WIN = pygame.display.set_mode((WIDTH, HEIGHT)) # window
pygame.display.set_caption("Shmup")
#colours
WHITE = (255,255,255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
FPS = 60
VEL = 5
SPACESHIP_WIDTH , SPACESHIP_HEIGHT = 55,40
#imgs
YELLOW_SPACESHIP_IMAGE = pygame.image.load('spaceship_yellow.png')
YELLOW_SPACESHIP = pygame.transform.scale(YELLOW_SPACESHIP_IMAGE, (SPACESHIP_WIDTH, SPACESHIP_HEIGHT))
ASTEROID_IMAGES = pygame.image.load('asteroid.png')
ASTEROID = pygame.transform.scale(ASTEROID_IMAGES, (40, 40))
#movement
def movement(keys_pressed, yellow):
keys_pressed = pygame.key.get_pressed()
if keys_pressed[pygame.K_LEFT]:
yellow.x -= VEL
keys_pressed = pygame.key.get_pressed()
if keys_pressed[pygame.K_RIGHT]:
yellow.x += VEL
keys_pressed = pygame.key.get_pressed()
if keys_pressed[pygame.K_UP]:
yellow.y -= VEL
keys_pressed = pygame.key.get_pressed()
if keys_pressed[pygame.K_DOWN]:
yellow.y += VEL
#draw
def draw_window(yellow):
WIN.fill(WHITE)
WIN.blit(YELLOW_SPACESHIP, (yellow.x, yellow.y))
pygame.display.update()
#main code
def main():
yellow = pygame.Rect(50, 450, SPACESHIP_WIDTH , SPACESHIP_HEIGHT) #the spaceship is called yellow
clock = pygame.time.Clock()
run = True
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if yellow.right > WIDTH:
yellow.right = WIDTH
if yellow.left < 0:
yellow.left = 0
if yellow.top < 0:
yellow.top = 0
if yellow.bottom > HEIGHT:
yellow.bottom = HEIGHT
keys_pressed = pygame.key.get_pressed()
movement(keys_pressed, yellow)
draw_window(yellow)
pygame.quit()
if __name__ == "__main__":
main()