0

I've finished my first game, and I'd like to add the high score to the 'game over' screen.

I have a variable called 'score'. This 'score' increases as you get further into the game. This 'score' also shows on screen while playing. If you die your final score shows up on the 'game over' screen. All I want to do is add the high score to this screen.

I've searched for this, but somehow haven't found a clear awnser. I've found many different awnsers, but all too specific to the code the people were using. There has to be a simple awnser to this question, right?

There's only 1 player, and I only want to show 1 high score. I'm still very new to programming, please keep it as simple as possible

Updated code with awnser in it under game_over

import pygame
import sys
import time
import random
from pygame.locals import *

pygame.init()

pygame.display.set_mode()

def main():

    width = 1400
    height = 800

    blue = (0, 0, 255)
    black = (0, 0, 0)
    white = (255, 255, 255)
    red = (255, 0, 0)

    dino = pygame.image.load("dino.png").convert_alpha()
    meteor = pygame.image.load("meteor.png").convert_alpha()

    player_location = [width - 1350, height - 200]
    player_size = [100, 200]

    obstacle_size = [101, 101]
    obstacle_location = [width - 100, height - 100]

    obstacle_list = [obstacle_location]

    screen = pygame.display.set_mode((width, height))

    speed = 10

    score = 0

    clock = pygame.time.Clock()
    FPS = 80

    myFont = pygame.font.SysFont("monospace", 35)

    run = True

    def set_speed(score, speed):
        if score < 5:
            speed = 10
        elif score < 10:
            speed = 15
        elif score < 20:
            speed = 20
        elif score < 35:
            speed = 25
        elif score < 50:
            speed = 30
        elif score < 75:
            speed = 35
        elif score < 100:
            speed = 40
        else:
            speed = 50
        return speed

    def spawn_obstacle(obstacle_list):
        delay = random.random()
        dist = random.choice([100, 300])
        if len(obstacle_list) < 3 and delay < 0.0075:
            x_pos = width-100
            y_pos = height-dist
            obstacle_list.append([x_pos, y_pos])

    def draw_obstacle(obstacle_list):
        for obstacle_location in obstacle_list:
            pygame.draw.rect(screen, white, (obstacle_location[0], obstacle_location[1], obstacle_size[0], obstacle_size[1]))
            screen.blit(meteor, (obstacle_location[0], obstacle_location[1]))

    def update_obstacle_positions(obstacle_list, score):
        for idx, obstacle_location in enumerate(obstacle_list):
            if obstacle_location[0] >= 0 and obstacle_location[0] < width:
                obstacle_location[0] -= speed
            else:
                obstacle_list.pop(idx)
                score += 1
        return score

    def collision_check(obstacle_list, player_location):
        for obstacle_location in obstacle_list:
            if detect_collision(obstacle_location, player_location):
                return True
            return False


    def detect_collision(player_location, obstacle_location):
        p_x = player_location[0]
        p_y = player_location[1]

        p_width = player_size[0]
        p_height = player_size[1]

        o_x = obstacle_location[0]
        o_y = obstacle_location[1]

        o_width = obstacle_size[0]
        o_height = obstacle_size[1]

        if (o_x >= p_x and o_x < (p_x + p_width)) or (p_x >= o_x and p_x < (o_x + o_width)):
            if (o_y >= p_y and o_y < (p_y + p_height)) or (p_y >= o_y and p_y < (o_y + o_height)):
                return True
        return False

    end_it = False
    while (end_it == False):
        screen.fill(black)
        for event in pygame.event.get():
            if event.type == MOUSEBUTTONDOWN:
                end_it = True
            if event.type == pygame.QUIT:
                    run = False
                    pygame.quit()
                    sys.exit()
        myfont = pygame.font.SysFont("Britannic Bold", 40)
        label = myfont.render("Click to start", 1, red)
        screen.blit(label,(600,550))
        label_2 = myfont.render("Hold ARROW UP to jump", 1, white)
        screen.blit(label_2, (520, 380))
        myfont2 = pygame.font.SysFont("Britannic Bold", 120)
        label_3 = myfont.render("Hold SPACE to duck", 1, white)
        screen.blit(label_3, (550, 420))
        label_4 = myfont2.render("T-REX RUN", 1, white)
        screen.blit(label_4, (470,200))
        pygame.display.flip()

    def game_over():
        while game_over:
            screen.fill(black)
            text = "Game Over, Press SPACE to restart"
            label = myFont.render(text, 1, white)
            screen.blit(label, (350, 350))
            end_score = "Score:" + str(score)
            label_2 = myFont.render(end_score, 1, white)
            screen.blit(label_2, (350, 250))

            file = open("highscore.txt", "r")
            content = file.read()
            content = str(content)
            if content < str(score):
                file = open("highscore.txt", "w")
                file.write(str(score))
                hs = "You got a new highscore"
                label_3 = myFont.render(hs, 1, white)
                screen.blit(label_3, (350, 250)) 
                pygame.display.update()
            else:
                hs = "Highscore: " + content
                label_3 = myFont.render(hs, 1, white)
                screen.blit(label_3, (350, 250)) 
                pygame.display.update()  

            file.close()

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

                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_SPACE:
                        main()

    while run: 

        clock.tick(FPS)

        for event in pygame.event.get():

            if event.type == pygame.QUIT:
                run = False
                pygame.quit()
                sys.exit()

            if event.type == pygame.KEYDOWN:

                x = player_location[0]
                y = player_location[1]

                p_width = player_size[0]  
                p_height = player_size[1]


                if event.key == pygame.K_UP:
                    y -= 200

                player_location = [x,y] 

            if event.type == pygame.KEYUP:

                if event.key == pygame.K_SPACE or event.key == pygame.K_UP:
                   player_size = [100, 200]
                   player_location = [50, 600]

        keys = pygame.key.get_pressed()
        if keys[pygame.K_SPACE]:
            p_height = 100
            y = 700

            player_size = [p_width,p_height]
            player_location = [x,y]

        screen.fill(white)

        spawn_obstacle(obstacle_list)
        score = update_obstacle_positions(obstacle_list, score)
        speed = set_speed(score, speed)

        text = "Score:" + str(score)
        label = myFont.render(text, 1, blue)
        screen.blit(label, (600, 250))

        if collision_check(obstacle_list, player_location):
            game_over()

        draw_obstacle(obstacle_list)

        pygame.draw.rect(screen, white, (player_location[0], player_location[1], player_size[0], player_size[1]))
        screen.blit(dino, (player_location[0], player_location[1]-39))

        pygame.display.update()

main()

1 Answers1

1

You can try creating a .txt file called highscore. First of all, you can code (at the beginning of your code) newfile = open("highscore.txt", "w+") to create your file. Then delete that code and in your code (I think this is the right place for it) have:

def game_over():
            while game_over:
                screen.fill(black)
                text = "Game Over, Press SPACE to restart"
                label = myFont.render(text, 1, white)
                screen.blit(label, (350, 350))
                end_score = "Score:" + str(score)
                label_2 = myFont.render(end_score, 1, white)
                screen.blit(label_2, (350, 250))
                file = open("highscore.txt", "r")
                content = file.read()
                content = int(content)
                file.close()
                if content > score:
                    file = open("highscore.txt", "w")
                    file.write(score)
                    hs = "You got the highscore. well done!"
                    label_3 = my_Font.render(hs, 1, white)
                    screen.blit(label_3, (350, 150)) #Or any other position you want!
                    pygame.display.update()
                else:
                    hs = "The highscore is: ", content
                    label_3 = my_Font.render(hs, 1, white)
                    screen.blit(label_3, (350, 150)) #Or any other position you want!
                    pygame.display.update()  

content can be what you output for the highscore at the end and can be how your code decides whether the user has the new highscore or not. I hope this helped!!! If you are creating file outside of python remember to save file with type of file at the end (for example .txt) and to have the file in the same directory (folder) as your python program. If you don't understand this ask me to make it simpler. I have not tested this so there may be errors for you to fix but try it first and then tell me how the code did!

Thomas
  • 1,214
  • 4
  • 18
  • 45
  • I still have some trouble understanding . I added my code to my post, maybe that'll help you as well... – Zino Wardenier Apr 05 '20 at 13:25
  • @ZinoWardenier I have changed it to fit your code. I have not tested so forgive me for any syntax or other errors . – Thomas Apr 05 '20 at 13:44
  • at first I got " TypeError: '>' not supported between instances of 'str' and 'int' ", so under content = file.read() I added content = int(content). If I ran this I got " label_3 = myFont.render(hs, 1, white) TypeError: text must be a unicode or bytes ". I don't know how to fix this... – Zino Wardenier Apr 05 '20 at 14:03
  • From the sources I have looked at I think this may be because the hs text has the symbol - in it. Try removing that. If it works would you mind giving me a tick on the answer if it doesn't then reply and I'll spend hours upon hours to try and fix it (else you have to ask another question) @ZinoWardenier – Thomas Apr 05 '20 at 14:18
  • In case you want the sources for yourself : https://stackoverflow.com/questions/28819746/typeerror-text-must-be-a-unicode-or-bytes https://stackoverflow.com/questions/31942122/rendering-unicode-in-pygame https://stackoverflow.com/questions/1207457/convert-a-unicode-string-to-a-string-in-python-containing-extra-symbols http://www.pygame.org/docs/ref/freetype.html#pygame.freetype.Font.render – Thomas Apr 05 '20 at 14:18
  • I've messed around with it abit and now it works :D. The changes I made to what you wrote: under content = file.read() I added content = str(content) (ot int :P)/if content < str(score): (< instead of >) (added str to score)/file.write(str(score)) (str infront of score)/ in the else: hs = "..." + content (+ instead of ,) I didn't have enough characters to copy me code, hope you understand – Zino Wardenier Apr 05 '20 at 15:59
  • I've edited my code in my original post, that'll be easier to understand ;) Hope I managed to help you a little as well. Thanks a lot for your help, now my first game is fully finnished :D – Zino Wardenier Apr 05 '20 at 16:00
  • Just realised it doesn't give the 'You got a new highscore' when you beat the highscore. But it still says Score: and then High score: with the same number as Score, but that honestly doesn't matter to me – Zino Wardenier Apr 05 '20 at 16:24