Загрузка данных
import curses
import random
import os
HIGHSCORE_FILE = "highscore.txt"
def load_highscore():
if os.path.exists(HIGHSCORE_FILE):
with open(HIGHSCORE_FILE, "r") as f:
return int(f.read() or 0)
return 0
def save_highscore(score):
with open(HIGHSCORE_FILE, "w") as f:
f.write(str(score))
def main(stdscr):
curses.curs_set(0)
sh, sw = stdscr.getmaxyx()
win = curses.newwin(sh, sw, 0, 0)
win.keypad(1)
highscore = load_highscore()
def create_apple(snake):
while True:
apple = [
random.randint(1, sh - 2),
random.randint(1, sw - 2)
]
if apple not in snake:
return apple
def draw_border():
for x in range(sw):
win.addch(0, x, '#')
win.addch(sh-1, x, '#')
for y in range(sh):
win.addch(y, 0, '#')
win.addch(y, sw-1, '#')
def eat_sound():
curses.beep()
def game_over_sound():
for _ in range(3):
curses.beep()
curses.napms(100)
def game():
snake = [[sh//2, sw//4], [sh//2, sw//4 - 1], [sh//2, sw//4 - 2]]
direction = curses.KEY_RIGHT
apples = 0
level = 1
speed = 120
apple = create_apple(snake)
while True:
win.clear()
draw_border()
# интерфейс
win.addstr(0, 2, f" Apples: {apples} ")
win.addstr(0, 20, f" Level: {level} ")
win.addstr(0, 35, f" Record: {highscore} ")
win.addstr(0, sw//2 - 10, " P:Pause Q:Quit ")
# яблоко
win.addch(apple[0], apple[1], 'A')
key = win.getch()
if key == ord('q'):
return "quit", apples
elif key == ord('p'):
while True:
k = win.getch()
if k == ord('p'):
break
elif k == ord('q'):
return "quit", apples
elif key in [curses.KEY_UP, curses.KEY_DOWN, curses.KEY_LEFT, curses.KEY_RIGHT]:
if (key == curses.KEY_UP and direction != curses.KEY_DOWN) or \
(key == curses.KEY_DOWN and direction != curses.KEY_UP) or \
(key == curses.KEY_LEFT and direction != curses.KEY_RIGHT) or \
(key == curses.KEY_RIGHT and direction != curses.KEY_LEFT):
direction = key
head = snake[0].copy()
if direction == curses.KEY_UP:
head[0] -= 1
elif direction == curses.KEY_DOWN:
head[0] += 1
elif direction == curses.KEY_LEFT:
head[1] -= 1
elif direction == curses.KEY_RIGHT:
head[1] += 1
# столкновение
if (
head[0] == 0 or head[0] == sh-1 or
head[1] == 0 or head[1] == sw-1 or
head in snake
):
game_over_sound()
return "gameover", apples
snake.insert(0, head)
# съели яблоко
if head == apple:
apples += 1
eat_sound()
apple = create_apple(snake)
if apples % 5 == 0:
level += 1
speed = max(40, speed - 10)
else:
snake.pop()
# рисуем змею
for i, part in enumerate(snake):
win.addch(part[0], part[1], 'O' if i == 0 else 'o')
win.timeout(speed)
while True:
result, score = game()
nonlocal_high = load_highscore()
if score > nonlocal_high:
save_highscore(score)
nonlocal_high = score
win.clear()
if result == "quit":
break
win.addstr(10, 10, "Game Over!")
win.addstr(11, 10, f"Apples: {score}")
win.addstr(12, 10, f"Record: {nonlocal_high}")
win.addstr(14, 10, "R - restart | Q - quit")
while True:
key = win.getch()
if key == ord('r'):
break
elif key == ord('q'):
return
curses.wrapper(main)