Skip to content

Instantly share code, notes, and snippets.

@midsonlajeanty
Created October 23, 2023 22:07
Show Gist options
  • Save midsonlajeanty/42a0552347e57632e7eb03e9a8c1f3b4 to your computer and use it in GitHub Desktop.
Save midsonlajeanty/42a0552347e57632e7eb03e9a8c1f3b4 to your computer and use it in GitHub Desktop.
Tetris Simulator - Python | L4 | ESIH
import os
import time
import random
BLANK_CASE:str = ' '
FILLED_CASE:str = '🧱'
BOARD_SIZE: int = 6
clear = lambda: os.system('clear')
class Point:
def __init__(self, base:int):
self.x: int = base
self.y: int = 0
self.attached: bool = False
def attach(self) -> None:
self.attached = True
def can_go_down(self) -> bool:
return self.attached == False
def go_down(self) -> None:
if not self.attached:
self.y += 1
class Board:
def __init__(self, size: int=BOARD_SIZE):
self.size: int = size
self.points: list[Point] = []
self.grid: list[list[str]] = []
def init_grid(self) -> None:
self.grid = []
for i in range(self.size):
self.grid.append([])
for j in range(self.size):
self.grid[i].append(BLANK_CASE)
def is_filled(self, x: int, y: int) -> bool:
return self.grid[y][x] == FILLED_CASE
def render(self) -> None:
clear()
self.init_grid()
# Fill Points
for point in self.points:
self.grid[point.y][point.x] = FILLED_CASE
# Render Grid
def print_line():
for i in range(self.size):
print('-----', end='')
print('-')
for i in range(self.size):
print_line()
for j in range(self.size):
filled = self.is_filled(j, i)
print('|', self.grid[i][j], end=' ' if filled else ' ')
print("|")
print_line()
def update(self, point: Point):
if point not in self.points:
self.points.append(point)
self.render()
def attached_point(self, point: Point):
for i in range(self.size):
self.update(point)
if self.is_filled(point.x, point.y + 1):
point.attach()
break
if point.can_go_down():
point.go_down()
time.sleep(0.5)
if point.y == self.size - 1:
point.attach()
break
class Game:
def __init__(self, *args, **kwargs):
self.board: Board = Board(*args, **kwargs)
self.steps: int = 0
def get_random_point(self) -> Point:
return Point(random.randint(0, self.board.size - 1))
def game_over(self) -> bool:
for point in self.board.points:
if point.y == 0:
return True
return False
def start(self) -> None:
self.board.init_grid()
while not self.game_over():
point = self.get_random_point()
self.board.attached_point(point)
self.steps += 1
print(f'Game Over! Steps: {self.steps}')
if __name__ == '__main__':
game = Game()
game.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment