tetris and snake in numpy
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
2.7 KiB

7 months ago
import numpy as np
7 months ago
import curses
7 months ago
import time
7 months ago
import random
def main(stdscr):
7 months ago
curses.curs_set(0) # Hide the cursor for a cleaner look
stdscr.nodelay(True) # Non-blocking input to keep the game flowing
h, w = 20, 40 # Dimensions of the game board
board = np.zeros((h, w), dtype=int) # Game board initialization
snake = [(h // 2, w // 2)] # Starting position of the snake
board[h // 2, w // 2] = 1 # Mark the snake's start on the board
7 months ago
food = (random.randint(0, h - 1), random.randint(0, w - 1))
7 months ago
board[food] = 2 # Place initial food
direction = (0, 1) # Initial movement direction
last_update_time = time.time()
move_interval = 0.1 # Base move interval in seconds
vertical_adjustment = 2 # Vertical moves occur every this number of base intervals
7 months ago
while True:
key = stdscr.getch()
7 months ago
if key in [ord("Q"), ord("q")]:
7 months ago
break
7 months ago
if key in [ord("a"), ord("A")] and direction != (0, 1):
7 months ago
direction = (0, -1)
7 months ago
if key in [ord("d"), ord("D")] and direction != (0, -1):
7 months ago
direction = (0, 1)
7 months ago
if key in [ord("w"), ord("W")] and direction != (1, 0):
7 months ago
direction = (-1, 0)
7 months ago
if key in [ord("s"), ord("S")] and direction != (-1, 0):
7 months ago
direction = (1, 0)
7 months ago
current_time = time.time()
time_elapsed = current_time - last_update_time
7 months ago
7 months ago
# Adjust move interval based on direction
current_interval = move_interval * (
vertical_adjustment if direction in [(-1, 0), (1, 0)] else 1
)
if time_elapsed >= current_interval:
new_head = (snake[0][0] + direction[0], snake[0][1] + direction[1])
new_head = (new_head[0] % h, new_head[1] % w) # Toroidal field logic
7 months ago
7 months ago
if new_head in snake:
break # Collision detection
snake.insert(0, new_head)
if new_head == food:
7 months ago
food = (random.randint(0, h - 1), random.randint(0, w - 1))
7 months ago
while food in snake:
food = (random.randint(0, h - 1), random.randint(0, w - 1))
else:
tail = snake.pop()
board[tail] = 0
board[new_head] = 1
board[food] = 2
last_update_time = current_time # Reset the timer
7 months ago
7 months ago
# Clear and redraw the board
stdscr.clear()
for i in range(h):
for j in range(w):
if board[i, j] == 1:
stdscr.addch(i, j, "X")
elif board[i, j] == 2:
stdscr.addch(i, j, "O")
else:
stdscr.addch(i, j, " ")
7 months ago
7 months ago
stdscr.refresh()
7 months ago
curses.wrapper(main)