简体   繁体   中英

Python tkinter snake game restart

I`m trying to code a snake game in python using tkinter but I am not able to find a solution regarding a restart function. In short, I want to create a button with the text "Restart" or "Play again" only when you die and once you press the Restart button the game starts again.

Here is the code:

GAMEWIDTH = 900

GAMEHEIGHT = 600

GAMESPEED = 70

ITEMSSIZE = 30

BODYWIDTH = 2

BODYCOLOR = "#03fc0b"

FOODCOLOR = "yellow"

BACKGROUNDCOLOR = "#cf03fc"

def snake_game(): global Sarpe, Mancare, directie, points, points_increment

def snake_turn(snake, food):
    a, b = snake.coordonate[0]

    if directie == "up":
        b -= ITEMSSIZE
    elif directie == "down":
        b += ITEMSSIZE
    elif directie == "left":
        a -= ITEMSSIZE
    elif directie == "right":
        a += ITEMSSIZE

    snake.coordonate.insert(0, (a, b))
    cube = tablou.create_rectangle(a, b, a + ITEMSSIZE, b + ITEMSSIZE, fill=BODYCOLOR)
    snake.cubes.insert(0, cube)
    if a == food.coordonate[0] and b == food.coordonate[1]:
        global points
        points += 1
        points_increment.config(text="Points:{}".format(points))
        tablou.delete("food")
        food = Mancare()

    else:
        del snake.coordonate[-1]
        tablou.delete(snake.cubes[-1])
        del snake.cubes[-1]

    if verify_collisions(snake):
        you_died()
    else:
        snakeGUI.after(GAMESPEED, snake_turn, snake, food)

def change_movement(new_directie):
    global directie

    if new_directie == "left":
        if directie != "right":
            directie = new_directie
    elif new_directie == "right":
        if directie != "left":
            directie = new_directie
    elif new_directie == "up":
        if directie != "down":
            directie = new_directie
    elif new_directie == "down":
        if directie != "up":
            directie = new_directie

def verify_collisions(snake):
    a, b = snake.coordonate[0]

    if a < 0 or a >= GAMEWIDTH:
        return True
    elif b < 0 or b >= GAMEHEIGHT:
        return True
    for snake_body in snake.coordonate[1:]:
        if a == snake_body[0] and b == snake_body[1]:
            return True

def you_died():
    tablou.delete(ALL)
    tablou.create_text(tablou.winfo_width() / 2, tablou.winfo_height() / 2, font=("gameplay", 90), text="GAME OVER",
                       fill="#03fc1c", tag="game over")


class Sarpe:
    def __init__(self):
        self.body_size = BODYWIDTH
        self.coordonate = []
        self.cubes = []

        for i in range(0, BODYWIDTH):
            self.coordonate.append([0, 0])

        for a, b in self.coordonate:
            cube = tablou.create_rectangle(a, b, a + ITEMSSIZE, b + ITEMSSIZE, fill=BODYCOLOR, tag="snake")
            self.cubes.append(cube)

class Mancare:
    def __init__(self):
        a = random.randint(0, (GAMEWIDTH / ITEMSSIZE) - 1) * ITEMSSIZE
        b = random.randint(0, (GAMEHEIGHT / ITEMSSIZE) - 1) * ITEMSSIZE

        self.coordonate = [a, b]
        tablou.create_oval(a, b, a + ITEMSSIZE, b + ITEMSSIZE, fill=FOODCOLOR, tag="food")

snakeGUI = Tk()
snakeGUI.title("Snake")
snakeGUI.resizable(False, False)

points = 0
directie = "down"

points_increment = Label(snakeGUI, text="Points:{}".format(points), font=("consolas", 40))
points_increment.pack()

tablou = Canvas(snakeGUI, bg="#cf03fc", height=GAMEHEIGHT, width=GAMEWIDTH)
tablou.pack()

snakeGUI.update()

snakeGUI_width = snakeGUI.winfo_width()
snakeGUI_height = snakeGUI.winfo_height()
screen_width = snakeGUI.winfo_screenwidth()
screen_height = snakeGUI.winfo_screenheight()

a = int((screen_width / 2) - (snakeGUI_width / 2))
b = int((screen_height / 2) - (snakeGUI_height / 2))

snakeGUI.geometry(f"{snakeGUI_width}x{snakeGUI_height}+{a}+{b}")

snakeGUI.bind("<Left>", lambda event: change_movement("left"))
snakeGUI.bind("<Right>", lambda event: change_movement("right"))
snakeGUI.bind("<Up>", lambda event: change_movement("up"))
snakeGUI.bind("<Down>", lambda event: change_movement("down"))

snake = Sarpe()
food = Mancare()

snake_turn(snake, food)

snakeGUI.mainloop()

snake_game()

Thanks in advance!

I have not used this logic with tkinter before, but you could define the WHOLE thing as system, then call system when you lose, so it does the loop all over again!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM