Michael Pilosov
7 months ago
1 changed files with 67 additions and 0 deletions
@ -0,0 +1,67 @@ |
|||||
|
import curses |
||||
|
import random |
||||
|
|
||||
|
import numpy as np |
||||
|
|
||||
|
|
||||
|
def main(stdscr): |
||||
|
curses.curs_set(0) # Hide cursor |
||||
|
stdscr.nodelay(True) # Don't block I/O calls |
||||
|
stdscr.timeout(100) # Refresh rate |
||||
|
|
||||
|
# Initialize the board |
||||
|
h, w = 20, 40 # Board dimensions |
||||
|
board = np.zeros((h, w), dtype=int) |
||||
|
snake = [(h // 2, w // 2)] |
||||
|
board[h // 2, w // 2] = 1 |
||||
|
food = (random.randint(0, h - 1), random.randint(0, w - 1)) |
||||
|
board[food] = 2 # Food position |
||||
|
direction = (0, 1) # Initial direction (right) |
||||
|
|
||||
|
while True: |
||||
|
# Input handling |
||||
|
key = stdscr.getch() |
||||
|
if key in [ord("q"), ord("Q")]: |
||||
|
break |
||||
|
elif key in [ord("a"), ord("A")] and direction != (0, 1): |
||||
|
direction = (0, -1) |
||||
|
elif key in [ord("d"), ord("D")] and direction != (0, -1): |
||||
|
direction = (0, 1) |
||||
|
elif key in [ord("w"), ord("W")] and direction != (1, 0): |
||||
|
direction = (-1, 0) |
||||
|
elif key in [ord("s"), ord("S")] and direction != (-1, 0): |
||||
|
direction = (1, 0) |
||||
|
elif key == ord(" "): # Pause |
||||
|
stdscr.nodelay(False) |
||||
|
stdscr.getch() |
||||
|
stdscr.nodelay(True) |
||||
|
|
||||
|
# Update snake position |
||||
|
head = (snake[0][0] + direction[0], snake[0][1] + direction[1]) |
||||
|
head = (head[0] % h, head[1] % w) # Torus wrapping |
||||
|
|
||||
|
if head in snake: # Check self-collision |
||||
|
break |
||||
|
|
||||
|
snake.insert(0, head) # Move head |
||||
|
if head == food: # Check food collision |
||||
|
food = (random.randint(0, h - 1), random.randint(0, w - 1)) |
||||
|
while food in snake: |
||||
|
food = (random.randint(0, h - 1), random.randint(0, w - 1)) |
||||
|
else: |
||||
|
tail = snake.pop() |
||||
|
board[tail] = 0 |
||||
|
|
||||
|
board[head] = 1 |
||||
|
board[food] = 2 |
||||
|
|
||||
|
# Draw the board |
||||
|
stdscr.clear() |
||||
|
for i in range(h): |
||||
|
for j in range(w): |
||||
|
char = " " if board[i, j] == 0 else "*" if board[i, j] == 1 else "O" |
||||
|
stdscr.addch(i, j, char) |
||||
|
stdscr.refresh() |
||||
|
|
||||
|
|
||||
|
curses.wrapper(main) |
Loading…
Reference in new issue