Advertisement
EdmundC

tetrissubsoft

Sep 30th, 2024 (edited)
15
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.93 KB | None | 0 0
  1. import os
  2. import random
  3. import sys
  4. import time
  5. import subprocess
  6.  
  7. # Check and install required libraries
  8. try:
  9.     import keyboard
  10. except ImportError:
  11.     print("keyboard library not found. Installing...")
  12.     subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'keyboard'])
  13.     import keyboard  # Try importing again
  14.  
  15. # Define constants
  16. WIDTH = 10
  17. HEIGHT = 20
  18. BLOCK = "[]"
  19. EMPTY = "  "
  20. TICK_INTERVAL = 1 / 30  # 30 FPS
  21.  
  22. # Define Tetris shapes (O, I, S, Z, L, J, T)
  23. SHAPES = [
  24.     [[1, 1], [1, 1]],  # O shape
  25.     [[1, 1, 1, 1]],    # I shape
  26.     [[0, 1, 1], [1, 1, 0]],  # S shape
  27.     [[1, 1, 0], [0, 1, 1]],  # Z shape
  28.     [[1, 0, 0], [1, 1, 1]],  # L shape
  29.     [[0, 0, 1], [1, 1, 1]],  # J shape
  30.     [[0, 1, 0], [1, 1, 1]],  # T shape
  31. ]
  32.  
  33. class Tetris:
  34.     def __init__(self):
  35.         self.board = [[0] * WIDTH for _ in range(HEIGHT)]
  36.         self.current_piece = self.new_piece()
  37.         self.current_x = WIDTH // 2 - len(self.current_piece[0]) // 2
  38.         self.current_y = 0
  39.         self.game_over = False
  40.  
  41.     def new_piece(self):
  42.         return random.choice(SHAPES)
  43.  
  44.     def rotate_piece(self):
  45.         self.current_piece = [list(row)[::-1] for row in zip(*self.current_piece)]
  46.  
  47.     def valid_position(self, offset_x=0, offset_y=0):
  48.         for y, row in enumerate(self.current_piece):
  49.             for x, cell in enumerate(row):
  50.                 if cell:
  51.                     new_x = x + self.current_x + offset_x
  52.                     new_y = y + self.current_y + offset_y
  53.                     if new_x < 0 or new_x >= WIDTH or new_y >= HEIGHT or (new_y >= 0 and self.board[new_y][new_x]):
  54.                         return False
  55.         return True
  56.  
  57.     def lock_piece(self):
  58.         for y, row in enumerate(self.current_piece):
  59.             for x, cell in enumerate(row):
  60.                 if cell:
  61.                     self.board[y + self.current_y][x + self.current_x] = 1
  62.         self.clear_lines()
  63.         self.current_piece = self.new_piece()
  64.         self.current_x = WIDTH // 2 - len(self.current_piece[0]) // 2
  65.         self.current_y = 0
  66.         if not self.valid_position():
  67.             self.game_over = True
  68.  
  69.     def clear_lines(self):
  70.         lines_to_clear = [i for i in range(HEIGHT) if all(self.board[i])]
  71.         for i in lines_to_clear:
  72.             del self.board[i]
  73.             self.board.insert(0, [0] * WIDTH)
  74.  
  75.     def drop_piece(self):
  76.         if self.valid_position(offset_y=1):
  77.             self.current_y += 1
  78.         else:
  79.             self.lock_piece()
  80.  
  81.     def move_piece(self, dx):
  82.         if self.valid_position(offset_x=dx):
  83.             self.current_x += dx
  84.  
  85.     def update(self):
  86.         self.drop_piece()
  87.  
  88.     def draw_board(self):
  89.         os.system('cls' if os.name == 'nt' else 'clear')
  90.         # Draw the board
  91.         for y in range(HEIGHT):
  92.             for x in range(WIDTH):
  93.                 if self.board[y][x]:
  94.                     print(BLOCK, end="")
  95.                 else:
  96.                     print(EMPTY, end="")
  97.             print()
  98.         # Draw the current piece
  99.         for y, row in enumerate(self.current_piece):
  100.             for x, cell in enumerate(row):
  101.                 if cell:
  102.                     print("\033[{0};{1}H{2}".format(self.current_y + y + 1, self.current_x + x + 1, BLOCK), end="")
  103.         print("\033[{0};{1}HScore: {2}".format(HEIGHT + 1, 0, sum(row.count(1) for row in self.board)))
  104.  
  105. def main():
  106.     tetris = Tetris()
  107.  
  108.     while not tetris.game_over:
  109.         tetris.update()
  110.         tetris.draw_board()
  111.  
  112.         # Handle input
  113.         if keyboard.is_pressed('left'):
  114.             tetris.move_piece(-1)
  115.         elif keyboard.is_pressed('right'):
  116.             tetris.move_piece(1)
  117.         elif keyboard.is_pressed('down'):
  118.             tetris.drop_piece()
  119.         elif keyboard.is_pressed('up'):
  120.             tetris.rotate_piece()
  121.  
  122.         time.sleep(TICK_INTERVAL)
  123.  
  124.     print("Game Over!")
  125.  
  126. if __name__ == "__main__":
  127.     main()
  128.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement