Basically I want to make two stages of the game: the main game and the end screen, which shows up after time runs out. The endscreen shows, shows your score and to go back playing the game you press space, however my current code does not work. Can you please explain why and give advice. I need the answer specifically for this case, because of that I'll be able to understand it better.
import pygame
import random
import time
# GLOBAL VARIABLES
COLOR = (255, 100, 98)
SURFACE_COLOR = (0, 0, 0)
WIDTH = 500
HEIGHT = 500
RED = (255, 0, 0)
score = 0
# Object class
class Sprite(pygame.sprite.Sprite):
def __init__(self, color, height, width):
super().__init__()
self.image = pygame.Surface([width, height])
self.image.fill(SURFACE_COLOR)
self.image.set_colorkey(COLOR)
pygame.draw.rect(self.image, color, pygame.Rect(0, 0, width, height))
self.rect = self.image.get_rect()
def move(self, speed, speed2):
self.rect.x += speed
self.rect.y += speed2
def randpos(self):
self.rect.x = random.randint(0, WIDTH)
self.rect.y = random.randint(0, HEIGHT)
pygame.init()
size = (WIDTH, HEIGHT)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Zoog chase")
all_sprites_list = pygame.sprite.Group()
object_ = Sprite(RED, 50, 50)
object2_ = Sprite((0, 255, 0), 30, 30)
object2_.randpos()
all_sprites_list.add(object_)
all_sprites_list.add(object2_)
font = pygame.font.SysFont("Roboto", 100)
t = 5.00
start = time.time()
font2 = pygame.font.SysFont('Roboto', 50)
endScreen = False
playing = True
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if playing:
elapsed = time.time() - start
if t - elapsed <= 0:
time.sleep(1)
endScreen = True
playing = False
collide = pygame.sprite.collide_rect(object_, object2_)
if collide:
score += 1
t += 0.75
object2_.randpos()
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
object_.move(-5, 0)
if keys[pygame.K_RIGHT]:
object_.move(5, 0)
if keys[pygame.K_UP]:
object_.move(0, -5)
if keys[pygame.K_DOWN]:
object_.move(0, 5)
all_sprites_list.update()
screen.fill(SURFACE_COLOR)
timer = font2.render("{:.2f}".format(t - elapsed), True, (211, 211, 211))
timer_rect = timer.get_rect(center=(WIDTH / 2, 50))
screen.blit(timer, timer_rect)
img = font.render(str(score), True, (169, 169, 169))
img_rect = img.get_rect(center=(screen.get_rect().center))
screen.blit(img, img_rect)
all_sprites_list.draw(screen)
if endScreen:
keys = pygame.key.get_pressed()
if playing == False and endScreen == True:
if keys[pygame.K_SPACE]:
endScreen = False
playing = True
t = 5.00
score = 0
screen.fill((0, 0, 0))
font = pygame.font.SysFont("Roboto", 75)
score_text = font.render("Your score: " + str(score), True, (255, 255, 255))
score_text_rect = score_text.get_rect(center=(screen.get_rect().center))
screen.blit(score_text, score_text_rect)
pygame.display.flip()
clock.tick(60)
Tried to make two stages of the game, didn't work out, thus need help.