0

I wanted to add a timer after I've cleared level 4 in the game I am making. The timer should be of 10 seconds in which it should display "upgrading" and then continue to level 5. How do I do that? I'm having trouble in this and would like your help. I have tried many different methods but none of them worked. Please help as I need to submit this project before 25th August.

My current code:

import random

import pygame
from pygame import mixer

pygame.font.init()
pygame.init()

# THE SCREEN SIZE
WIDTH, HEIGHT = 800, 600
WIN = pygame.display.set_mode((WIDTH, HEIGHT))

# THE GAME NAME
pygame.display.set_caption("The Space Walker")

# ENEMIES
REDEX = pygame.image.load("REDEX.png")
GENEX = pygame.image.load("GENEX.png")
BREX = pygame.image.load("BREX.png")
BOSS = pygame.image.load("Boss.png")

# THE PLAYER
player = pygame.image.load("BLShip.png")
THESPACEWALKER = pygame.image.load("SPACEWALKER.png")

# ENEMY LASERS
REDEXASER = pygame.image.load("REDEXASER.png")
GENEXASER = pygame.image.load("GENEXASER.png")
BREXASER = pygame.image.load("BREXASER.png")
BOSSXASER = pygame.image.load("BOSSXASER.png")

# PLAYER LASER
LAME = pygame.image.load("SPACEXASER.png")
NEOXASER = pygame.image.load("NEOXASER.png")

# GAME BACKGROUND
BG = pygame.transform.scale(pygame.image.load("background.png"), (WIDTH, HEIGHT))

# GAME MUSIC
music = pygame.mixer.music.load('background.mp3')
pygame.mixer.music.play(-1)


# FUNCTIONS BEING USED IN THE GAME

# PAUSE FUNCTION


def pause():
    paused = True

    while paused:
        pause_font = pygame.font.SysFont("freesansbold.ttf", 80)
        con_font = pygame.font.SysFont("freesansbold.ttf", 80)
        for event in pygame.event.get():

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_c:
                    paused = False

        pause_label = pause_font.render("Paused", 1, (255, 255, 255))
        WIN.blit(pause_label, (WIDTH / 2 - pause_label.get_width() / 2, 250))
        con_label = con_font.render("C to Continue", 1, (255, 255, 255))
        WIN.blit(con_label, (WIDTH / 2 - con_label.get_width() / 2, 300))
        pygame.display.update()
        pygame.mixer.pause()
        pygame.time.Clock()


class Laser:
    def __init__(self, x, y, img):
        self.x = x
        self.y = y
        self.img = img
        self.mask = pygame.mask.from_surface(self.img)

    def draw(self, window):
        window.blit(self.img, (self.x, self.y))

    def move(self, vel):
        self.y += vel

    def off_screen(self, height):
        return not (height >= self.y >= 0)

    def collision(self, obj):
        return collide(self, obj)


class Ship:
    COOLDOWN = 30

    def __init__(self, x, y, health=100):
        self.x = x
        self.y = y
        self.health = health
        self.ship_img = None
        self.laser_img = None
        self.lasers = []
        self.cool_down_counter = 0

    def draw(self, window):
        window.blit(self.ship_img, (self.x, self.y))
        for laser in self.lasers:
            laser.draw(window)

    def move_lasers(self, vel, obj):
        self.cooldown()
        for laser in self.lasers:
            laser.move(vel)
            if laser.off_screen(HEIGHT):
                self.lasers.remove(laser)
            elif laser.collision(obj):
                obj.health -= 10
                self.lasers.remove(laser)

    def cooldown(self):
        if self.cool_down_counter >= self.COOLDOWN:
            self.cool_down_counter = 0
        elif self.cool_down_counter > 0:
            self.cool_down_counter += 1

    def shoot(self):
        if self.cool_down_counter == 0:
            laser = Laser(self.x - 17, self.y, self.laser_img)
            self.lasers.append(laser)
            self.cool_down_counter = 1
        lsound = mixer.Sound('Lfire.wav')
        lsound.play()

    def get_width(self):
        return self.ship_img.get_width()

    def get_height(self):
        return self.ship_img.get_height()


class Player(Ship):
    def __init__(self, x, y, health=100):
        super().__init__(x, y, health)
        self.ship_img = player
        self.laser_img = LAME
        self.mask = pygame.mask.from_surface(self.ship_img)
        self.max_health = health

    def move_lasers(self, vel, objs):
        self.cooldown()
        for laser in self.lasers:
            laser.move(vel)
            if laser.off_screen(HEIGHT):
                self.lasers.remove(laser)
            else:
                for obj in objs:
                    if laser.collision(obj):
                        colli = mixer.Sound('coll.wav')
                        colli.play()
                        obj.health -= 10
                        if laser in self.lasers:
                            self.lasers.remove(laser)

    def draw(self, window):
        super().draw(window)
        self.healthbar(window)

    def healthbar(self, window):
        pygame.draw.rect(window, (255, 0, 0),
                         (self.x, self.y + self.ship_img.get_height() + 10, self.ship_img.get_width(), 10))
        pygame.draw.rect(window, (0, 255, 0), (
            self.x, self.y + self.ship_img.get_height() + 10,
            self.ship_img.get_width() * (self.health / self.max_health),
            10))


class Enemy(Ship):
    COLOR_MAP = {
        "red": (REDEX, REDEXASER),
        "green": (GENEX, GENEXASER),
        "blue": (BREX, BREXASER),
        "black": (BOSS, BOSSXASER)
    }

    def __init__(self, x, y, color, health=10):
        super().__init__(x, y, health)
        self.ship_img, self.laser_img = self.COLOR_MAP[color]
        self.mask = pygame.mask.from_surface(self.ship_img)

    def move(self, vel):
        self.y += vel

    def shoot(self):
        if self.cool_down_counter == 0:
            laser = Laser(self.x - 20, self.y, self.laser_img)
            self.lasers.append(laser)
            self.cool_down_counter = 1
        if self.y > 0:
            lsound = mixer.Sound('Lfire.wav')
            lsound.play()


def collide(obj1, obj2):
    offset_x = obj2.x - obj1.x
    offset_y = obj2.y - obj1.y
    return obj1.mask.overlap(obj2.mask, (offset_x, offset_y)) is not None


def text_objects(text, font):
    textSurface = font.render(text, True, (0, 0, 0))
    return textSurface, textSurface.get_rect()


def main():
    run = True
    FPS = 60
    level = 3
    lives = 3
    crashed = 0

    main_font = pygame.font.SysFont("freesansbold.ttf", 50)
    winc_font = pygame.font.SysFont("freesansbold.ttf", 70)
    lost_font = pygame.font.SysFont("freesansbold.ttf", 70)

    enemies = []
    wave_length = 5
    enemy_vel = 1

    player_vel = 5
    laser_vel = 3

    player = Player(400 - 30, 500)

    clock = pygame.time.Clock()

    lost = False
    lost_count = 0

    winc = False
    winc_count = 0

    def redraw_window():
        WIN.blit(BG, (0, 0))
        # draw text
        lives_label = main_font.render(f"Lives: {lives}", 1, (255, 255, 255))
        level_label = main_font.render(f"Level: {level}", 1, (255, 255, 255))
        crashed_label = main_font.render(f"Crashed: {crashed}", 1, (255, 255, 255))

        WIN.blit(lives_label, (10, 10))
        WIN.blit(level_label, (WIDTH - level_label.get_width() - 10, 10))
        WIN.blit(crashed_label, (20, 550))

        for enemy in enemies:
            enemy.draw(WIN)

        player.draw(WIN)

        if lost:
            lost_label = lost_font.render("GAME OVER", 1, (255, 255, 255))
            WIN.blit(lost_label, (WIDTH / 2 - lost_label.get_width() / 2, 250))
            crashed_label = main_font.render(f"You crashed: {crashed} times", 1, (255, 60, 60))
            WIN.blit(crashed_label, (WIDTH / 2 - crashed_label.get_width() / 2, 305))
            credit_label = main_font.render(f"Game by (Aaditya & Aaryan) Sharma", 1, (255, 255, 0))
            WIN.blit(credit_label, (WIDTH / 2 - credit_label.get_width() / 2, 345))
            credit1_label = main_font.render(f"Thank you for playing The Space Walker!", 1, (255, 128, 0))
            WIN.blit(credit1_label, (WIDTH / 2 - credit1_label.get_width() / 2, 385))
            pygame.mixer.music.pause()
            LoseSound = mixer.Sound('LoseSound.wav')
            LoseSound.play()
        if winc:
            winc_label = winc_font.render("You Win!", 1, (255, 255, 255))
            WIN.blit(winc_label, (WIDTH / 2 - winc_label.get_width() / 2, 250))
            crashed_label = main_font.render(f"You crashed: {crashed} times", 1, (255, 60, 60))
            WIN.blit(crashed_label, (WIDTH / 2 - crashed_label.get_width() / 2, 305))
            credit_label = main_font.render(f"Game by (Aaditya & Aaryan) Sharma", 1, (255, 255, 0))
            WIN.blit(credit_label, (WIDTH / 2 - credit_label.get_width() / 2, 345))
            credit1_label = main_font.render(f"Thank you for playing The Space Walker!", 1, (255, 128, 0))
            WIN.blit(credit1_label, (WIDTH / 2 - credit1_label.get_width() / 2, 385))
            pygame.mixer.music.pause()
            WinSound = mixer.Sound('WinSound.wav')
            WinSound.play()
        pygame.display.update()

    while run:
        clock.tick(FPS)
        redraw_window()

        if lives <= 0 or player.health <= 0:
            lost = True
            lost_count += 1

        if lost:
            if lost_count > FPS * 9:
                run = False
            else:
                continue

        if level < 6:
            if len(enemies) == 0:
                level += 1
                wave_length += 3
                for i in range(wave_length):
                    if level == 1:
                        enemy = Enemy(random.randrange(25, WIDTH - 80), random.randrange(-1200, -100),
                                      random.choice(["blue"]))
                        enemies.append(enemy)
                    if level == 2:
                        enemy = Enemy(random.randrange(25, WIDTH - 80), random.randrange(-1200, -100),
                                      random.choice(["red"]))
                        enemies.append(enemy)
                    if level == 3:
                        enemy = Enemy(random.randrange(25, WIDTH - 80), random.randrange(-1200, -100),
                                      random.choice(["green"]))
                        enemies.append(enemy)
                    if level == 4:
                        enemy = Enemy(random.randrange(12, WIDTH - 80), random.randrange(-1200, -100),
                                      random.choice(["red", "green", "blue"]))
                        enemies.append(enemy)
                wave_length += 1
                for i in range(wave_length):
                    if level == 5:
                        FPS = 60
                        player.health = 30
                        player.ship_img = THESPACEWALKER
                        player.laser_img = NEOXASER
                        enemy = Enemy(random.randrange(0, WIDTH - 86), random.randrange(-40, -10),
                                      random.choice(["black"]))
                        enemies.append(enemy)

        if level > 5:
            winc = True
            winc_count += 1

        if winc:
            if winc_count > FPS * 9:
                run = False
            else:
                continue

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                quit()

        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT] and player.x - player_vel > 0:  # left
            player.x -= player_vel
        if keys[pygame.K_RIGHT] and player.x + player_vel + player.get_width() < WIDTH:  # right
            player.x += player_vel
        if keys[pygame.K_SPACE]:
            player.shoot()
        if keys[pygame.K_p]:
            pause()

        for enemy in enemies[:]:
            enemy.move(enemy_vel)
            enemy.move_lasers(laser_vel, player)

            if enemy.health == 0:
                enemies.remove(enemy)

            if random.randrange(0, 2 * 60) == 1:
                enemy.shoot()

            if collide(enemy, player):
                player.health -= 10
                enemies.remove(enemy)
                crashed += 1

            elif enemy.y + enemy.get_height() > HEIGHT:
                lives -= 1
                enemies.remove(enemy)

        player.move_lasers(-laser_vel, enemies)
    pygame.display.update()


def butt():
    mouse = pygame.mouse.get_pos()
    if WIDTH / 2 - 75 + 150 > mouse[0] > WIDTH / 2 - 75 and 250 + 50 > mouse[1] > 250:
        pygame.draw.rect(WIN, (100, 100, 100), (WIDTH / 2 - 75, 250, 150, 50))
    else:
        pygame.draw.rect(WIN, (255, 255, 255), (WIDTH / 2 - 75, 250, 150, 50))

    smallText = pygame.font.Font("freesansbold.ttf", 20)
    textSurf, textRect = text_objects("Start", smallText)
    textRect.center = ((WIDTH / 2), (250 + (50 / 2)))
    WIN.blit(textSurf, textRect)

    for event in pygame.event.get():
        if WIDTH / 2 - 75 + 150 > mouse[0] > WIDTH / 2 - 75 and 250 + 50 > mouse[1] > 250:
            if event.type == pygame.MOUSEBUTTONDOWN:
                main()


def start_screen():
    run = True
    while run:
        WIN.blit(BG, (0, 0))

        butt()

        pygame.display.update()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

    pygame.quit()


start_screen()
Qiu YU
  • 517
  • 4
  • 20
  • 1
    What is the difference to your previous question? - [Ending screen is lagging for Space Invaders](https://stackoverflow.com/questions/63547431/ending-screen-is-lagging-for-space-invaders) – Rabbid76 Aug 23 '20 at 18:40
  • @Rabbid76 in that question after completing the game, the game just lagged and then displayed the end screen for 1 sec and close but I've fixed that so np i just need help in this – Yukihira Soma Aug 23 '20 at 18:42
  • 2
    I can't see any difference. In my opinion, you asked the same question three times. Don't post the code of the entire application. Just add the relevant code to the question. Please read [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) and [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask). – Rabbid76 Aug 23 '20 at 18:43
  • @Rabbid76 how are they same? 1st one is for shooting bullets, 2nd is for lagging while third is for timer – Yukihira Soma Aug 23 '20 at 18:45
  • 4
    Nobody can "see" that, because you put the entire application to question with almost no explanation. Show the code you are struggling with and explain exactly why you are struggle. Your question is of the kind "Please fix my application". – Rabbid76 Aug 23 '20 at 18:49
  • https://stackoverflow.com/questions/30720665/countdown-timer-in-pygame. This answer shows how to make a countdown-timer –  Aug 23 '20 at 18:50
  • @Rabbid76 plz man chill out i am new to this application i dont know how to use it well and im new to python as well that is y i didnt know on what part should i post because there can be things i have used in this game previously that might be causing this problem so i posted the whole code – Yukihira Soma Aug 23 '20 at 18:52
  • 3
    @YukihiraSoma This is not your 1st question, it is your 3rd and you've ignored the comments to your previous questions. Questions like this will hardly get a satisfying answer, because there is too much code and to less clarification about the problem. To find a good answer someone would have to debug your application. To debug the application the images have to be substituted. – Rabbid76 Aug 23 '20 at 18:57
  • @YukihiraSoma Just give us the images so we can debug the whole thing. Also, you should tell us what you have instead of just saying "I have tried many different methods". – Qiu YU Aug 24 '20 at 09:49

2 Answers2

1

Maybe you can do something like this:

import pygame
import time
pygame.init()

D = pygame.display.set_mode((500, 500))
font = pygame.font.Font(pygame.font.get_default_font(), 20)
start = time.time()
def display(waittime):
    now = time.time()
    surf = font.render("UPGRADING", True, (0, 255, 0))
    usurf = font.render("UPGRADED", True, (0, 255, 0))
    timer = now - start
    if timer < waittime:
        pygame.draw.rect(D, (0, 255, 0), (100, 20, timer * 20, 50))
        D.blit(surf, (150, 150))
    else:
        D.blit(usurf, (150, 150))
     
while True:
    D.fill((255, 255, 255))
    pygame.event.get()

    display(10)
    
    pygame.display.flip()
1
pause_time = 0

def count(level):

    time_left = 10

    if level == 4:

        if trig == 1

            time = int(pygame.time.get_ticks()/1000)

            trig = 2

        while time_left != 0:

            time_left=(10-(int(pygame.time.get_ticks()/1000) - time))

            myfont = pygame.font.Font(yourpreferedfont, yourpreferedsize)

            time_left_text = myfont.render(time_left, 0, (255, 255, 255))

            WIN.blit(time_left_text, (x, y))

plug in the code where it is supposed to be, also if it doesn't work, I couldn't test it because I don't have your images and it will give me an error.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61