Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import curses
- from random import randint
- import time
- # constants and game settings
- WIN_HEIGHT = 20
- WIN_WIDTH = 50
- snake_init_length = 3
- init_direction = curses.KEY_RIGHT
- ESC = 27 # is defined as key #27 in curses module
- # set up window
- curses.initscr()
- win = curses.newwin(WIN_HEIGHT, WIN_WIDTH, 0, 0) # first y, then x coordinate
- win.keypad(1) # equally 1 could be used
- curses.noecho() # no echo of inputs
- curses.curs_set(0) # hide cursor
- win.border(0) # no border
- win.nodelay(1) # Don't wait for next user key input
- # initialize snake
- def init_margin(var):
- return randint(var//3, 2*var//3)
- snake_init_y = (init_margin(WIN_HEIGHT))
- snake_init_x = (init_margin(WIN_WIDTH))
- def snake(length):
- snake = []
- counter = 0
- for i in range(length+1):
- snake.append((snake_init_y,snake_init_x-counter))
- counter += 1
- return snake
- snake = snake(snake_init_length)
- # initialize food
- while True:
- food_init_y = (init_margin(WIN_HEIGHT))
- food_init_x = (init_margin(WIN_WIDTH))
- if (food_init_y, food_init_x) not in snake:
- break
- food = (food_init_y, food_init_x)
- win.addch(food[0], food[1], "#")
- # start the game
- key = init_direction
- score = 0
- while key != ESC:
- win.addstr(0,2, f"Score {score}") # line,column,str
- win.timeout(150 - (len(snake))//5 + (len(snake)//10 % 120)) # increase speed
- prev_key = key
- event = win.getch()
- if key == ord("P"):
- time.sleep(2)
- if event != -1:
- key = event
- else:
- key = prev_key
- if key not in [curses.KEY_LEFT, curses.KEY_RIGHT, curses.KEY_UP, curses.KEY_DOWN, ESC]:
- key = prev_key
- # calculate the next coordinates
- y = snake[0][0]
- x = snake[0][1]
- if key == curses.KEY_DOWN:
- y += 1
- if key == curses.KEY_UP:
- y -= 1
- if key == curses.KEY_LEFT:
- x -= 1
- if key == curses.KEY_RIGHT:
- x += 1
- snake.insert(0, (y,x)) # append O(n)
- # check if we hit the border
- if y == 0:
- break
- if y == WIN_HEIGHT-1:
- break
- if x == 0:
- break
- if x == WIN_WIDTH-1:
- break
- # check if snake runs over itself
- if snake[0] in snake[1:]:
- break
- # check if snake hits food
- if snake[0] == food:
- # eat the food
- score += 1
- food = ()
- while food == ():
- food = (randint(1,WIN_HEIGHT-2), randint(1,WIN_WIDTH-2))
- if food in snake:
- food = ()
- win.addch(food[0], food[1], "#")
- else:
- # move the snake
- last = snake.pop()
- win.addch(last[0], last[1], " ")
- win.addch(snake[0][0], snake[0][1], '*')
- curses.endwin()
- print(f"Hooray! Your final score is {score}.")
Add Comment
Please, Sign In to add comment