Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How are we supposed to add a highscore keeper which if asked by the user will tell the highscoire of at least 5 people with their names

What I have tried:

Python


# Simple Snake Game 
# By yash

import turtle
import time
import random

delay = 0.1

# Score
score = 0
high_score = 0

# Set up the screen
wn = turtle.Screen()
wn.title("Snake Game by yash")
wn.bgcolor("green")
wn.setup(width=600, height=600)
wn.tracer(0) # Turns off the screen updates

# Snake head
head = turtle.Turtle()
head.speed(0)
head.shape("circle")
head.color("black")
head.penup()
head.goto(0,0)
head.direction = "stop"

# Snake food
food = turtle.Turtle()
food.speed(0)
food.shape("square")
food.color("red")
food.penup()
food.goto(0,100)

segments = []

# Pen
pen = turtle.Turtle()
pen.speed(0)
pen.shape("square")
pen.color("white")
pen.penup()
pen.hideturtle()
pen.goto(0, 260)
pen.write("Score: 0  High Score: 0", align="center", font=("Courier", 24, "normal"))

# Functions
def go_up():
    if head.direction != "down":
        head.direction = "up"

def go_down():
    if head.direction != "up":
        head.direction = "down"

def go_left():
    if head.direction != "right":
        head.direction = "left"

def go_right():
    if head.direction != "left":
        head.direction = "right"

def move():
    if head.direction == "up":
        y = head.ycor()
        head.sety(y + 20)

    if head.direction == "down":
        y = head.ycor()
        head.sety(y - 20)

    if head.direction == "left":
        x = head.xcor()
        head.setx(x - 20)

    if head.direction == "right":
        x = head.xcor()
        head.setx(x + 20)

# Keyboard bindings
wn.listen()
wn.onkeypress(go_up, "w")
wn.onkeypress(go_down, "s")
wn.onkeypress(go_left, "a")
wn.onkeypress(go_right, "d")

# Main game loop
while True:
    wn.update()

    # Check for a collision with the border
    if head.xcor()>290 or head.xcor()<-290 or head.ycor()>290 or head.ycor()<-290:
        time.sleep(1)
        head.goto(0,0)
        head.direction = "stop"

        # Hide the segments
        for segment in segments:
            segment.goto(1000, 1000)
        
        # Clear the segments list
        segments.clear()

        # Reset the score
        score = 0

        # Reset the delay
        delay = 0.1

        pen.clear()
        pen.write("Score: {}  High Score: {}".format(score, high_score), align="center", font=("Courier", 24, "normal")) 


    # Check for a collision with the food
    if head.distance(food) < 20:
        # Move the food to a random spot
        x = random.randint(-290, 290)
        y = random.randint(-290, 290)
        food.goto(x,y)

        # Add a segment
        new_segment = turtle.Turtle()
        new_segment.speed(0)
        new_segment.shape("square")
        new_segment.color("grey")
        new_segment.penup()
        segments.append(new_segment)

        # Shorten the delay
        delay -= 0.001

        # Increase the score
        score += 10

        if score > high_score:
            high_score = score
        
        pen.clear()
        pen.write("Score: {}  High Score: {}".format(score, high_score), align="center", font=("Courier", 24, "normal")) 

    # Move the end segments first in reverse order
    for index in range(len(segments)-1, 0, -1):
        x = segments[index-1].xcor()
        y = segments[index-1].ycor()
        segments[index].goto(x, y)

    # Move segment 0 to where the head is
    if len(segments) > 0:
        x = head.xcor()
        y = head.ycor()
        segments[0].goto(x,y)

    move()    

    # Check for head collision with the body segments
    for segment in segments:
        if segment.distance(head) < 20:
            time.sleep(1)
            head.goto(0,0)
            head.direction = "stop"
        
            # Hide the segments
            for segment in segments:
                segment.goto(1000, 1000)
        
            # Clear the segments list
            segments.clear()

            # Reset the score
            score = 0

            # Reset the delay
            delay = 0.1
        
            # Update the score display
            pen.clear()
            pen.write("Score: {}  High Score: {}".format(score, high_score), align="center", font=("Courier", 24, "normal"))

    time.sleep(delay)

wn.mainloop()
Posted
Updated 29-Jan-21 1:26am
Comments
Richard MacCutchan 28-Jan-21 5:50am    
Your question is not clear.
YASH CHATURVEDI 28-Jan-21 8:46am    
@Richard MacCutchan
I would like to save the highscores of the game.
The thing is that I need a file that stores the best highscores, and showing them from the biggest score to the lowest.
like this
john=15
yash=10
and so on...
is this okay sir
Richard MacCutchan 28-Jan-21 9:46am    
So what is the problem? You can store those details in a simple text file: see 7. Input and Output — Python 3.7.9 documentation[^].
YASH CHATURVEDI 28-Jan-21 11:38am    
the problem is that we have to take the input from the user not from a [redefined place
Richard MacCutchan 28-Jan-21 11:41am    
Er, your previous comment states "I need a file that stores the best highscores"
So take the scores from the user at the input and write them to a file.

Here is a simple example of load and save. The data is loaded into a list of list, each entry containing the name and score value. On save, the list is sorted by score in descending order, and the top five entries are written to the save file.
Python
# load the score entries from a text file
def loadscores(file: str) -> []:
    scores = []
    fi = open("scores.txt", "r")
    oldscores = fi.read()
    fi.close()
    items = oldscores.split('\n')
    print(list)
    for item in items:
        if item != '':
            next = item.split('=')
            next[1] = int(next[1])
            scores.append(next)
    print("Loaded:", scores)
    return scores

# save the top five entries to a new file
def savescores(file: str, scores: []):
    savelist = sorted(scores, key=lambda it: it[1], reverse=True)
    try:
        fo = open("newscores.txt", "w")
        count = 0
        for item in savelist:
            fo.write(item[0] + '=' + str(item[1]) + '\n')
            count += 1
            if count == 5:  # only save the top 5
                break
        fo.close()
        print("Saved:", savelist[:5]) # only list the five saved items
    except:
        print("Save operation failed")

The text in the score file is in the following format:
Fred=31
Mary=27
John=23
George=17
Brenda=12
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900