Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import random
- import sys
- import time
- import subprocess
- # Check and install required libraries
- try:
- import keyboard
- except ImportError:
- print("keyboard library not found. Installing...")
- subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'keyboard'])
- import keyboard # Try importing again
- # Define constants
- WIDTH = 10
- HEIGHT = 20
- BLOCK = "[]"
- EMPTY = " "
- TICK_INTERVAL = 1 / 30 # 30 FPS
- # Define Tetris shapes (O, I, S, Z, L, J, T)
- SHAPES = [
- [[1, 1], [1, 1]], # O shape
- [[1, 1, 1, 1]], # I shape
- [[0, 1, 1], [1, 1, 0]], # S shape
- [[1, 1, 0], [0, 1, 1]], # Z shape
- [[1, 0, 0], [1, 1, 1]], # L shape
- [[0, 0, 1], [1, 1, 1]], # J shape
- [[0, 1, 0], [1, 1, 1]], # T shape
- ]
- class Tetris:
- def __init__(self):
- self.board = [[0] * WIDTH for _ in range(HEIGHT)]
- self.current_piece = self.new_piece()
- self.current_x = WIDTH // 2 - len(self.current_piece[0]) // 2
- self.current_y = 0
- self.game_over = False
- def new_piece(self):
- return random.choice(SHAPES)
- def rotate_piece(self):
- self.current_piece = [list(row)[::-1] for row in zip(*self.current_piece)]
- def valid_position(self, offset_x=0, offset_y=0):
- for y, row in enumerate(self.current_piece):
- for x, cell in enumerate(row):
- if cell:
- new_x = x + self.current_x + offset_x
- new_y = y + self.current_y + offset_y
- if new_x < 0 or new_x >= WIDTH or new_y >= HEIGHT or (new_y >= 0 and self.board[new_y][new_x]):
- return False
- return True
- def lock_piece(self):
- for y, row in enumerate(self.current_piece):
- for x, cell in enumerate(row):
- if cell:
- self.board[y + self.current_y][x + self.current_x] = 1
- self.clear_lines()
- self.current_piece = self.new_piece()
- self.current_x = WIDTH // 2 - len(self.current_piece[0]) // 2
- self.current_y = 0
- if not self.valid_position():
- self.game_over = True
- def clear_lines(self):
- lines_to_clear = [i for i in range(HEIGHT) if all(self.board[i])]
- for i in lines_to_clear:
- del self.board[i]
- self.board.insert(0, [0] * WIDTH)
- def drop_piece(self):
- if self.valid_position(offset_y=1):
- self.current_y += 1
- else:
- self.lock_piece()
- def move_piece(self, dx):
- if self.valid_position(offset_x=dx):
- self.current_x += dx
- def update(self):
- self.drop_piece()
- def draw_board(self):
- os.system('cls' if os.name == 'nt' else 'clear')
- # Draw the board
- for y in range(HEIGHT):
- for x in range(WIDTH):
- if self.board[y][x]:
- print(BLOCK, end="")
- else:
- print(EMPTY, end="")
- print()
- # Draw the current piece
- for y, row in enumerate(self.current_piece):
- for x, cell in enumerate(row):
- if cell:
- print("\033[{0};{1}H{2}".format(self.current_y + y + 1, self.current_x + x + 1, BLOCK), end="")
- print("\033[{0};{1}HScore: {2}".format(HEIGHT + 1, 0, sum(row.count(1) for row in self.board)))
- def main():
- tetris = Tetris()
- while not tetris.game_over:
- tetris.update()
- tetris.draw_board()
- # Handle input
- if keyboard.is_pressed('left'):
- tetris.move_piece(-1)
- elif keyboard.is_pressed('right'):
- tetris.move_piece(1)
- elif keyboard.is_pressed('down'):
- tetris.drop_piece()
- elif keyboard.is_pressed('up'):
- tetris.rotate_piece()
- time.sleep(TICK_INTERVAL)
- print("Game Over!")
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement