Skip to content

Instantly share code, notes, and snippets.

@lnksz
Created June 25, 2021 22:07
Show Gist options
  • Save lnksz/f3c1b4902ad6e9ffeb21fd36ffd0f836 to your computer and use it in GitHub Desktop.
Save lnksz/f3c1b4902ad6e9ffeb21fd36ffd0f836 to your computer and use it in GitHub Desktop.
cli snake start
import readchar
import time
from os import system, name
def clearscreen():
# for windows
if name == 'nt':
_ = system('cls')
# for mac and linux(here, os.name is 'posix')
else:
_ = system('clear')
class Snake():
def __init__(self, pos_x=0, pos_y=0):
self.head_col = pos_x
self.head_row = pos_y
class Board():
def __init__(self, width=80, height=20):
self.width = width
self.height = height
self.snake = Snake(width // 2, height // 2)
board = [ [' ' for _ in range(0, self.width)] for _ in range(0, self.height)]
for i, row in enumerate(board):
if i == 0 or i == (self.height - 1):
row[0] = '+'
row[1:-1] = '-' * (self.width - 2)
row[-1] = '+'
else:
row[0] = '|'
row[-1] = '|'
if self.snake.head_row == i:
row[self.snake.head_col] = 'O'
row.append('\n')
self.board = board
def __str__(self):
s = ''
for row in self.board:
for c in row:
s += c
return s
def update_snake(self, cntrl):
self.board[self.snake.head_row][self.snake.head_col] = ' '
if cntrl == 'a':
self.snake.head_col -= 1
elif cntrl == 'd':
self.snake.head_col += 1
elif cntrl == 'w':
self.snake.head_row -= 1
elif cntrl == 's':
self.snake.head_row += 1
self.board[self.snake.head_row][self.snake.head_col] = 'O'
board = Board()
print(board)
while True:
c = readchar.readchar()
if c == 'b':
exit(0)
board.update_snake(c)
clearscreen()
print(board)
time.sleep(0.001)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment