Advertisement
Mr_D3a1h

Untitled

Apr 7th, 2023
931
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.68 KB | Gaming | 0 0
  1. import curses
  2. import random
  3.  
  4. # Initialize the game interface
  5. screen = curses.initscr()
  6. curses.curs_set(0)
  7. screen_height, screen_width = screen.getmaxyx()
  8.  
  9. # Initialize the game board
  10. game_board = [[' ' for x in range(screen_width)] for y in range(screen_height)]
  11. snake = [(screen_height // 2, screen_width // 2)]
  12. food = (random.randint(1, screen_height - 2), random.randint(1, screen_width - 2))
  13.  
  14. # Define the game loop
  15. while True:
  16.     # Handle user input
  17.     key = screen.getch()
  18.     if key == curses.KEY_UP:
  19.         snake.insert(0, (snake[0][0] - 1, snake[0][1]))
  20.     elif key == curses.KEY_DOWN:
  21.         snake.insert(0, (snake[0][0] + 1, snake[0][1]))
  22.     elif key == curses.KEY_LEFT:
  23.         snake.insert(0, (snake[0][0], snake[0][1] - 1))
  24.     elif key == curses.KEY_RIGHT:
  25.         snake.insert(0, (snake[0][0], snake[0][1] + 1))
  26.  
  27.     # Update the game state
  28.     if snake[0] == food:
  29.         food = (random.randint(1, screen_height - 2), random.randint(1, screen_width - 2))
  30.     else:
  31.         snake.pop()
  32.  
  33.     # Check for collisions
  34.     if (snake[0][0] == 0 or snake[0][0] == screen_height - 1 or
  35.             snake[0][1] == 0 or snake[0][1] == screen_width - 1 or
  36.             snake[0] in snake[1:]):
  37.         curses.endwin()
  38.         quit()
  39.  
  40.     # Redraw the game board
  41.     screen.clear()
  42.     for y in range(screen_height):
  43.         for x in range(screen_width):
  44.             if (y, x) in snake:
  45.                 screen.addch(y, x, 'O')
  46.             elif (y, x) == food:
  47.                 screen.addch(y, x, 'X')
  48.             else:
  49.                 screen.addch(y, x, game_board[y][x])
  50.     screen.refresh()
  51.     curses.napms(100)
  52.  
  53. # Clean up the game interface
  54. curses.endwin()
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement