import pygame
import time
import random
pygame.init()
### VARIABLES ###
# spaceship
MOVEMENT_SPEED = 6
SPACESHIP_WIDTH, SPACESHIP_HEIGHT = 70, 40
RECT_WIDTH, RECT_HEIGHT = 30, 30
# window
GRAVITY = 1
FPS = 60
WIDTH, HEIGHT = 700, 900
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
#colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)
GRAY = (50, 50, 50)
# spacesgips
SPACESHIP = pygame.image.load('block_game\\Assets\\space_ship.png')
SPACESHIP = pygame.transform.scale(surface=SPACESHIP, size=(SPACESHIP_WIDTH, SPACESHIP_HEIGHT))
SPACESHIP = pygame.transform.rotate(surface=SPACESHIP, angle=90)
# background
BG = pygame.image.load('block_game\\Assets\\background.jpg')
BG = pygame.transform.scale(BG, (WIDTH, HEIGHT))
# random
rand_width = random.randint(0, WIDTH - SPACESHIP_WIDTH)
rand_height = random.randint(0, HEIGHT - 500)
# rects
RECT_WIDTH, RECT_HEIGHT = 30, 30
rand_rect = pygame.Rect(rand_width, rand_height, RECT_WIDTH, RECT_HEIGHT)
list_colors = [WHITE]#, BLACK, RED, YELLOW, GRAY]
rand_color = random.choice(list_colors)
### VARIANLES ###
This is just how I'm handling the movement so the character doesn't move out the screen.
def handle_movement(keys_pressed, spaceship_rect):
if keys_pressed[pygame.K_a] and spaceship_rect.x > 0:
spaceship_rect.x -= MOVEMENT_SPEED
if keys_pressed[pygame.K_d] and spaceship_rect.x < WIDTH - 40:
spaceship_rect.x += MOVEMENT_SPEED
if keys_pressed[pygame.K_w] and spaceship_rect.y > 600:
spaceship_rect.y -= MOVEMENT_SPEED
if keys_pressed[pygame.K_s] and spaceship_rect.y < HEIGHT - 75:
spaceship_rect.y += MOVEMENT_SPEED
#print(spaceship_rect)
Here I'm planing to do something if I collide with the blocks like, for example, lose a life.
# checking for collision
def collision_check(spaceship_rect):
if spaceship_rect.colliderect(rand_rect):
print("collide")
This is the way I tried to spawn some rects in some random positions.
def drawing_blocks():
pygame.draw.rect(WIN, rand_color, pygame.Rect(rand_rect)) # draw rect
rand_rect.y += 1
print(rand_rect.y)
if rand_rect.y == HEIGHT:
# and here i want to draw a new block like before
pass
This doesn't work for me too, I want to spawn 3-5 blocks but in different positions using maybe the random module.
def draw_window(spaceship_rect):
WIN.fill(WHITE) # backgorund
WIN.blit(BG, (0, 0)) # backgorund
WIN.blit(source=SPACESHIP, dest=(spaceship_rect)) # spaceship
drawing_blocks()
pygame.display.update()
main loop
def main():
clock = pygame.time.Clock()
spaceship_rect = pygame.Rect(300, 800, SPACESHIP_WIDTH ,SPACESHIP_HEIGHT)
run = True
while run:
clock.tick(FPS)
for event in pygame.event.get(): # quit funktion
if event.type == pygame.QUIT:
run = False
pygame.quit()
# updateing game
keys_pressed = pygame.key.get_pressed() # checking if any key is pressed
handle_movement(keys_pressed, spaceship_rect)
draw_window(spaceship_rect)
collision_check(spaceship_rect)
pygame.quit()
if __name__ == '__main__':
main()