Created
October 5, 2023 13:18
-
-
Save seifalmotaz/63bf55bd96679390a769bcb9427b10f0 to your computer and use it in GitHub Desktop.
Snake Cursor Game with Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import random | |
import curses | |
screen = curses.initscr() | |
curses.curs_set(0) | |
screen_height, screen_width = screen.getmaxyx() | |
print(f"screen_height: {screen_height}, screen_width: {screen_width}") | |
window = curses.newwin(screen_height, screen_width, 0, 0) | |
window.keypad(True) | |
window.timeout(100) # 100 milliseconds = 0.1 seconds == 10 frames per second 10/sec | |
snake_x = screen_width // 4 | |
snake_y = screen_height // 2 | |
snake_body = [ | |
[snake_y, snake_x], | |
[snake_y, snake_x - 1], | |
[snake_y, snake_x - 2], | |
] | |
food = [screen_height // 2, screen_width // 2] | |
window.addch(food[0], food[1], curses.ACS_PI) | |
key = curses.KEY_RIGHT | |
while True: | |
next_key = window.getch() | |
key = key if next_key == -1 else next_key | |
snake_head = snake_body[0] # [y, x] | |
screen_border_x = [0, screen_width] | |
screen_border_y = [0, screen_height] | |
checker_borders = ( | |
snake_head[0] in screen_border_y or snake_head[1] in screen_border_x | |
) # True or False | |
if checker_borders or snake_head in snake_body[1:]: | |
curses.endwin() | |
quit() | |
new_head_position = [snake_head[0], snake_head[1]] # [y, x] | |
if key == curses.KEY_DOWN: | |
new_head_position[0] += 1 | |
if key == curses.KEY_UP: | |
new_head_position[0] -= 1 | |
if key == curses.KEY_LEFT: | |
new_head_position[1] -= 1 | |
if key == curses.KEY_RIGHT: | |
new_head_position[1] += 1 | |
snake_body.insert(0, new_head_position) | |
if snake_head == food: | |
food = None | |
while food is None: | |
new_food = [ | |
random.randint(1, screen_height - 1), | |
random.randint(1, screen_width - 1), | |
] | |
food = new_food if new_food not in snake_body else None | |
window.addch(food[0], food[1], curses.ACS_PI) | |
else: | |
tail = snake_body.pop() | |
window.addch(tail[0], tail[1], " ") | |
window.addch(snake_body[0][0], snake_body[0][1], curses.ACS_CKBOARD) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment