use python to write a Tetris. pay attention to it ui design
- User
use python to write a Tetris. pay attention to it ui design
Assistant
Creating a Tetris game in Python with a good UI design involves several steps. We'll use the
pygamelibrary for rendering graphics and handling user input, as it's well-suited for 2D games like Tetris.Steps to Build Tetris:
- Setup: Install
pygameand set up the basic game structure. - Game Logic: Implement Tetris mechanics such as piece movement, rotation, line clearing, and game-over detection.
- UI Design: Design the game grid, pieces, score display, and other visual elements.
- User Interaction: Handle key presses for moving and rotating the pieces.
Full Code Implementation
import pygame import random # Initialize pygame pygame.init() # Screen dimensions SCREEN_WIDTH = 300 SCREEN_HEIGHT = 600 BLOCK_SIZE = 30 # Colors BLACK = (0, 0, 0) WHITE = (255, 255, 255) GRAY = (50, 50, 50) COLORS = [ (0, 255, 255), # Cyan (255, 255, 0), # Yellow (255, 165, 0), # Orange (0, 0, 255), # Blue (0, 255, 0), # Green (255, 0, 0), # Red (128, 0, 128) # Purple ] # Shapes and their rotations SHAPES = [ [[1, 1, 1, 1]], # I [[1, 1], [1, 1]], # O [[0, 1, 0], [1, 1, 1]], # T [[1, 1, 0], [0, 1, 1]], # S [[0, 1, 1], [1, 1, 0]], # Z [[1, 1, 1], [1, 0, 0]], # L [[1, 1, 1], [0, 0, 1]] # J ] class Tetris: def __init__(self, width, height): self.width = width self.height = height self.grid = [[0 for _ in range(width)] for _ in range(height)] self.current_piece = self.new_piece() self.game_over = False self.score = 0 def new_piece(self): shape = random.choice(SHAPES) color = random.choice(COLORS) return {'shape': shape, 'color': color, 'x': self.width // 2 - len(shape[0]) // 2, 'y': 0} def valid_move(self, piece, offset_x, offset_y): for y, row in enumerate(piece['shape']): for x, cell in enumerate(row): if cell: new_x = piece['x'] + x + offset_x new_y = piece['y'] + y + offset_y if new_x < 0 or new_x >= self.width or new_y >= self.height or (new_y >= 0 and self.grid[new_y][new_x]): return False return True def place_piece(self): for y, row in enumerate(self.current_piece['shape']): for x, cell in enumerate(row): if cell: self.grid[self.current_piece['y'] + y][self.current_piece['x'] + x] = self.current_piece['color'] self.clear_lines() self.current_piece = self.new_piece() if not self.valid_move(self.current_piece, 0, 0): self.game_over = True def clear_lines(self): full_rows = [i for i, row in enumerate(self.grid) if all(row)] for i in full_rows: del self.grid[i] self.grid.insert(0, [0 for _ in range(self.width)]) self.score += len(full_rows) ** 2 def draw_grid(screen, game): for y in range(game.height): for x in range(game.width): if game.grid[y][x]: pygame.draw.rect(screen, game.grid[y][x], (x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0) pygame.draw.rect(screen, GRAY, (0, 0, SCREEN_WIDTH, SCREEN_HEIGHT), 1) def draw_piece(screen, piece): for y, row in enumerate(piece['shape']): for x, cell in enumerate(row): if cell: pygame.draw.rect(screen, piece['color'], ((piece['x'] + x) * BLOCK_SIZE, (piece['y'] + y) * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0) def draw_score(screen, score): font = pygame.font.SysFont('Arial', 20) text = font.render(f'Score: {score}', True, WHITE) screen.blit(text, (10, SCREEN_HEIGHT + 10)) def main(): screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT + 50)) pygame.display.set_caption("Tetris") clock = pygame.time.Clock() game = Tetris(SCREEN_WIDTH // BLOCK_SIZE, SCREEN_HEIGHT // BLOCK_SIZE) fall_time = 0 fall_speed = 500 # milliseconds running = True while running: screen.fill(BLACK) fall_time += clock.get_rawtime() clock.tick() for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT and game.valid_move(game.current_piece, -1, 0): game.current_piece['x'] -= 1 if event.key == pygame.K_RIGHT and game.valid_move(game.current_piece, 1, 0): game.current_piece['x'] += 1 if event.key == pygame.K_DOWN and game.valid_move(game.current_piece, 0, 1): game.current_piece['y'] += 1 if event.key == pygame.K_UP: rotated = list(zip(*game.current_piece['shape'][::-1])) if game.valid_move({'shape': rotated, 'color': game.current_piece['color'], 'x': game.current_piece['x'], 'y': game.current_piece['y']}, 0, 0): game.current_piece['shape'] = rotated if fall_time > fall_speed: fall_time = 0 if game.valid_move(game.current_piece, 0, 1): game.current_piece['y'] += 1 else: game.place_piece() draw_grid(screen, game) draw_piece(screen, game.current_piece) draw_score(screen, game.score) if game.game_over: font = pygame.font.SysFont('Arial', 40) text = font.render('Game Over', True, WHITE) screen.blit(text, (SCREEN_WIDTH // 2 - text.get_width() // 2, SCREEN_HEIGHT // 2 - text.get_height() // 2)) pygame.display.flip() pygame.time.wait(2000) running = False pygame.display.flip() pygame.quit() if __name__ == "__main__": main()
Explanation of the Code
-
Game Initialization:
- The
Tetrisclass manages the game state, including the grid, current piece, and score. - The
new_piecemethod generates a random Tetris piece with a random color.
- The
-
Movement and Rotation:
- The
valid_movemethod checks if a piece can move or rotate without colliding with the grid boundaries or other pieces. - Keyboard events handle left, right, down, and up (rotation) movements.
- The
-
Line Clearing:
- The
clear_linesmethod removes full rows from the grid and shifts everything above them down.
- The
-
Rendering:
- The
draw_gridfunction renders the static blocks on the grid. - The
draw_piecefunction renders the currently falling piece. - The
draw_scorefunction displays the player's score.
- The
-
Game Loop:
- The main loop handles events, updates the game state, and redraws the screen at a consistent frame rate.
UI Design Notes
- The grid is rendered using
pygame.draw.rect, with each block sizedBLOCK_SIZE. - A gray border surrounds the grid for better visibility.
- The score is displayed below the grid.
- Game over is indicated with a large "Game Over" message in the center of the screen.
How to Run
- Install
pygameif you don't already have it:pip install pygame - Save the code to a file (e.g.,
tetris.py). - Run the file:
python tetris.py
This implementation provides a clean and functional Tetris game with a visually appealing UI. You can further enhance it by adding features like a pause menu, level progression, or sound effects.
- Setup: Install
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.