0

I'm working on a snake game for a school assignment in Python Curses but the code I have written doesn't have a menu option and I am looking for one that will work for it. I really just need a play button to enter the game and an exit button to quit out of it. I've tried lots of methods but some either don't show up or I can't put the code in the selected button.

I have tried setting them in rows as I have seen two tutorials do. One required me to change my game code with a dif code to work but it didn't make any menu show up. (Code gotten from here https://www.youtube.com/watch?v=RXEOIAxgldw) The other had a simple menu which was very close to working as it did show up but didn't have a tutorial on how to connect it to the snake game as the same user had made a snake game as well. It's the one I had the most luck with but I can't figure out how to set it up so that when I chose "Play" it will play the game and when I chose "Exit" it will clear the game and stop running as when I select Exit the code doesn't stop and it goes back to a broken version of the snake game. (Code gotten from here https://www.youtube.com/watch?v=zwMsmBsC1GM)

Here is what my snake code looks like. All I need is a Play and Exit button and was wanting to know what would be the best way for that to work without altering my snake code too much. I'm a beginner to coding in curses so any help would be much appreciated. `

import curses
from random import randint

curses.initscr()
win = curses.newwin(20, 60, 0, 0)
win.keypad(1)
curses.noecho()
curses.curs_set(0)
win.border(0)
win.nodelay(1)

snake = [(4, 10), (4, 9), (4, 8)]
food = (10, 20)

score = 0

win.addch(food[0], food[1], '©')

ESC = 27
key = curses.KEY_RIGHT

while key != ESC:
    win.addstr(0, 2, 'Score ' + str(score) + ' ')
    win.timeout(150 - (len(snake)) // 5 + (len(snake) // 10 % 120))

    event = win.getch()
    prev_key = key
    key = event if event != -1 else prev_key

    if key not in [
            curses.KEY_LEFT, curses.KEY_RIGHT, curses.KEY_UP, curses.KEY_DOWN,
            ESC
    ]:
        key = prev_key

    y = snake[0][0]
    x = snake[0][1]
    if key == curses.KEY_DOWN:
        y += 1
    if key == curses.KEY_UP:
        y -= 1
    if key == curses.KEY_LEFT:
        x -= 1
    if key == curses.KEY_RIGHT:
        x += 1

    snake.insert(0, (y, x))

    if y == 0: break
    if y == 19: break
    if x == 0: break
    if x == 59: break

    if snake[0] in snake[1:]: break
    if snake[0] == food:
        score += 1
        food = ()

        while food == ():
            food = (randint(1, 18), randint(1, 58))
            if food in snake:
                food = ()
        win.addch(food[0], food[1], '©')

    else:
        last = snake.pop()
        win.addch(last[0], last[1], ' ')

    win.addch(snake[0][0], snake[0][1], '※')

curses.endwin()
print(f"Game over! Final score= {score}")

`

0 Answers0