Skip to content

Instantly share code, notes, and snippets.

@repen
Created March 5, 2020 16:48
Show Gist options
  • Save repen/dfaf3ecbb5b4327a489411c9c387e062 to your computer and use it in GitHub Desktop.
Save repen/dfaf3ecbb5b4327a489411c9c387e062 to your computer and use it in GitHub Desktop.
sn
import os
import time
def getChar():
# figure out which function to use once, and store it in _func
if "_func" not in getChar.__dict__:
try:
# for Windows-based systems
import msvcrt # If successful, we are on Windows
getChar._func=msvcrt.getch
except ImportError:
# for POSIX-based systems (with termios & tty support)
import tty, sys, termios # raises ImportError if unsupported
def _ttyRead():
fd = sys.stdin.fileno()
oldSettings = termios.tcgetattr(fd)
try:
tty.setcbreak(fd)
answer = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, oldSettings)
return answer
getChar._func=_ttyRead
return getChar._func()
class Dot:
def __init__(self):
self.dot = '*'
def add_dot(self):
return self.dot
class Snake:
DEFAULT_MOVE_DIR = 'd'
def __init__(self, x=10, y=10):
self.snake = []
self.x = x
self.y = y
self.dir = None
self.speed = 1
def snake_add_body(self):
dot = Dot()
self.snake.append(dot.add_dot())
def move(self):
self.dir = getChar()
# self.dir = input()
if self.dir == 'a':
self.x -= self.speed
elif self.dir == 'd':
self.x += self.speed
elif self.dir == 'w':
self.y -= self.speed
elif self.dir == 's':
self.y += self.speed
class Board:
def __init__(self, width=10, heigh=10):
self.width = width
self.heigh = heigh
def print_board(self, cord):
print("Clear")
os.system('clear')
for i in range(self.heigh):
for j in range(self.width):
if cord.x == j and cord.y == i:
print(''.join(cord.snake), end='')
if j == 0:
print('#', end='')
elif i == 0:
print('#', end='')
elif i == self.heigh-1:
print('#', end='')
elif j == self.width-1:
print('#', end='')
else:
print(' ', end='')
print()
class Game:
def __init__(self):
pass
def start_game(self):
board = Board(width=40, heigh=20)
snake = Snake(10, 10)
snake.snake_add_body()
snake.snake_add_body()
snake.snake_add_body()
while not ((snake.x > board.width-1 or snake.x < 1) or (snake.y > board.heigh-1 or snake.y < 1)):
board.print_board(snake)
snake.move()
time.sleep(0.15)
else:
print("GAMEOVER!!!")
game = Game()
game.start_game()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment