gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
write a snake game in python and ncurses with score and number of times food is eaten
- User
write a snake game in python and ncurses with score and number of times food is eaten
- Assistant
Here's an example of a snake game written in Python using the
ncurseslibrary. It includes tracking the score and the number of times food is eaten.import curses import random # Initialize the screen stdscr = curses.initscr() curses.curs_set(0) sh, sw = stdscr.getmaxyx() w = curses.newwin(sh, sw, 0, 0) w.keypad(1) w.timeout(100) # Create the snake snake_x = sw // 4 snake_y = sh // 2 snake = [ [snake_y, snake_x], [snake_y, snake_x - 1], [snake_y, snake_x - 2] ] # Create the first food food = [sh // 2, sw // 2] w.addch(food[0], food[1], curses.ACS_PI) # Initial direction key = curses.KEY_RIGHT # Initialize the score and food eaten count score = 0 food_eaten = 0 # Game logic while True: next_key = w.getch() key = key if next_key == -1 else next_key # Check if snake hits the wall if snake[0][0] in [0, sh] or snake[0][1] in [0, sw] or snake[0] in snake[1:]: curses.endwin() quit() # New head position new_head = [snake[0][0], snake[0][1]] # Move the snake based on the key pressed if key == curses.KEY_DOWN: new_head[0] += 1 if key == curses.KEY_UP: new_head[0] -= 1 if key == curses.KEY_LEFT: new_head[1] -= 1 if key == curses.KEY_RIGHT: new_head[1] += 1 snake.insert(0, new_head) # Check if snake eats the food if snake[0] == food: score += 1 food_eaten += 1 food = None while food is None: nf = [ random.randint(1, sh - 1), random.randint(1, sw - 1) ] food = nf if nf not in snake else None w.addch(food[0], food[1], curses.ACS_PI) else: tail = snake.pop() w.addch(tail[0], tail[1], ' ') w.addch(snake[0][0], snake[0][1], curses.ACS_CKBOARD) # Print the current score and food eaten count score_text = "Score: {}".format(score) food_text = "Food Eaten: {}".format(food_eaten) w.addstr(0, sw // 2 - len(score_text) // 2, score_text) w.addstr(0, sw - len(food_text) - 1, food_text) curses.endwin()