Untitled
unknown
plain_text
a year ago
2.1 kB
7
Indexable
import os
import random
import time
# Set up the game board
width = 10
height = 20
board = [[' ' for _ in range(width)] for _ in range(height)]
def print_board():
os.system('cls' if os.name == 'nt' else 'clear')
for row in board:
print(''.join(row))
def check_collision(piece, x, y):
for i in range(len(piece)):
for j in range(len(piece[0])):
if piece[i][j] == '[]' and (y + i >= height or x + j < 0 or x + j >= width or board[y + i][x + j] != ' '):
return True
return False
def merge_piece(piece, x, y):
for i in range(len(piece)):
for j in range(len(piece[0])):
if piece[i][j] == '[]':
board[y + i][x + j] = piece[i][j]
def clear_lines():
global board
new_board = [row for row in board if ' ' in row]
lines_cleared = height - len(new_board)
board = [[' ' for _ in range(width)] for _ in range(lines_cleared)] + new_board
def get_random_piece():
pieces = [
[['[]', '[]'], ['[]', '[]']],
[['[]', '[]', '[]'], [' ', '[]', ' ']],
[[' ', '[]', ' '], ['[]', '[]', '[]']],
[['[]', ' ', ' '], ['[]', '[]', '[]']],
[[' ', '[]'], ['[]', '[]'], ['[]', ' ']],
[['[]', ' '], ['[]', '[]'], [' ', '[]']],
[[' ', ' ', '[][]'], [' ', '[][]', ' ']],
]
return random.choice(pieces)
def rotate_piece(piece):
return [list(row) for row in zip(*piece[::-1])]
def main():
current_piece = get_random_piece()
x, y = width // 2 - len(current_piece[0]) // 2, 0
while True:
print_board()
time.sleep(0.5)
new_x, new_y = x, y + 1
if not check_collision(current_piece, new_x, new_y):
x, y = new_x, new_y
else:
merge_piece(current_piece, x, y)
clear_lines()
current_piece = get_random_piece()
x, y = width // 2 - len(current_piece[0]) // 2, 0
if check_collision(current_piece, x, y):
print_board()
print("Game Over!")
break
if __name__ == '__main__':
main()Editor is loading...
Leave a Comment