Please provide a Python script for the following request: create the tetris game in…
- User
Please provide a Python script for the following request: create the tetris game in python.
- Assistant
Creating a Tetris game in Python is a fun project that can help you understand game development concepts such as rendering graphics, handling user input, and managing game states. We'll use the
pygamelibrary, which is a popular choice for building games in Python.Below is a complete implementation of Tetris using
pygame. Follow the steps below to run the game on your machine.Prerequisites
-
Python Installed: Ensure you have Python 3.x installed on your system. You can download it from python.org.
-
Install Pygame: Install the
pygamelibrary usingpipif you haven't already.pip install pygame
Complete Tetris Game Code
import pygame import random # Initialize Pygame pygame.init() # Game Constants SCREEN_WIDTH = 300 SCREEN_HEIGHT = 600 BLOCK_SIZE = 30 PLAY_WIDTH = 10 * BLOCK_SIZE # 300 PLAY_HEIGHT = 20 * BLOCK_SIZE # 600 TOP_LEFT_X = (SCREEN_WIDTH - PLAY_WIDTH) // 2 TOP_LEFT_Y = SCREEN_HEIGHT - PLAY_HEIGHT # Define Colors BLACK = (0, 0, 0) GRAY = (128, 128, 128) WHITE = (255, 255, 255) # Define the shapes and their rotations S = [['.....', '.....', '..00.', '.00..', '.....'], ['.....', '..0..', '..00.', '...0.', '.....']] Z = [['.....', '.....', '.00..', '..00.', '.....'], ['.....', '..0..', '.00..', '.0...', '.....']] I = [['..0..', '..0..', '..0..', '..0..', '.....'], ['.....', '0000.', '.....', '.....', '.....']] O = [['.....', '.....', '.00..', '.00..', '.....']] J = [['.....', '.0...', '.000.', '.....', '.....'], ['.....', '..00.', '..0..', '..0..', '.....'], ['.....', '.....', '.000.', '...0.', '.....'], ['.....', '..0..', '..0..', '.00..', '.....']] L = [['.....', '...0.', '.000.', '.....', '.....'], ['.....', '..0..', '..0..', '..00.', '.....'], ['.....', '.....', '.000.', '.0...', '.....'], ['.....', '.00..', '..0..', '..0..', '.....']] T = [['.....', '..0..', '.000.', '.....', '.....'], ['.....', '..0..', '..00.', '..0..', '.....'], ['.....', '.....', '.000.', '..0..', '.....'], ['.....', '..0..', '.00..', '..0..', '.....']] # List of shapes SHAPES = [S, Z, I, O, J, L, T] SHAPE_COLORS = [ (0, 255, 0), # S (255, 0, 0), # Z (0, 255, 255), # I (255, 255, 0), # O (255, 165, 0), # J (0, 0, 255), # L (128, 0, 128) # T ] class Piece: def __init__(self, x, y, shape): self.x = x # Position on the grid (not pixels) self.y = y self.shape = shape self.color = SHAPE_COLORS[SHAPES.index(shape)] self.rotation = 0 # Number of times shape has been rotated def create_grid(locked_positions={}): grid = [[BLACK for _ in range(10)] for _ in range(20)] for (x, y), color in locked_positions.items(): grid[y][x] = color return grid def convert_shape_format(piece): positions = [] format = piece.shape[piece.rotation % len(piece.shape)] for i, line in enumerate(format): row = list(line) for j, column in enumerate(row): if column == '0': positions.append((piece.x + j - 2, piece.y + i - 4)) return positions def valid_space(piece, grid): accepted_positions = [[(j, i) for j in range(10) if grid[i][j] == BLACK] for i in range(20)] accepted_positions = [j for sub in accepted_positions for j in sub] formatted = convert_shape_format(piece) for pos in formatted: if pos not in accepted_positions: if pos[1] > -1: return False return True def check_lost(positions): for pos in positions: x, y = pos if y < 1: return True return False def get_shape(): return Piece(5, 0, random.choice(SHAPES)) def draw_text_middle(surface, text, size, color): font = pygame.font.SysFont('comicsans', size, bold=True) label = font.render(text, 1, color) surface.blit(label, ( TOP_LEFT_X + PLAY_WIDTH /2 - (label.get_width() /2), TOP_LEFT_Y + PLAY_HEIGHT /2 - label.get_height()/2 )) def draw_grid(surface, grid): sx = TOP_LEFT_X sy = TOP_LEFT_Y for i in range(len(grid)): pygame.draw.line(surface, GRAY, (sx, sy + i*BLOCK_SIZE), (sx + PLAY_WIDTH, sy + i * BLOCK_SIZE)) for j in range(len(grid[i])): pygame.draw.line(surface, GRAY, (sx + j*BLOCK_SIZE, sy), (sx + j*BLOCK_SIZE, sy + PLAY_HEIGHT)) def clear_rows(grid, locked): # Need to see if row is clear inc = 0 for i in range(len(grid)-1, -1, -1): row = grid[i] if BLACK not in row: inc += 1 ind = i for j in range(len(row)): try: del locked[(j, i)] except: continue if inc > 0: for key in sorted(list(locked), key=lambda x: x[1])[::-1]: x, y = key if y < ind: newKey = (x, y + inc) locked[newKey] = locked.pop(key) return inc def draw_next_shape(piece, surface): font = pygame.font.SysFont('comicsans', 30) label = font.render('Next Shape', 1, WHITE) sx = TOP_LEFT_X + PLAY_WIDTH + 50 sy = TOP_LEFT_Y + PLAY_HEIGHT/2 - 100 format = piece.shape[piece.rotation % len(piece.shape)] for i, line in enumerate(format): row = list(line) for j, column in enumerate(row): if column == '0': pygame.draw.rect(surface, piece.color, (sx + j*BLOCK_SIZE, sy + i*BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0) surface.blit(label, (sx + 10, sy - 30)) def draw_window(surface, grid, score=0): surface.fill(BLACK) # Title font = pygame.font.SysFont('comicsans', 60) label = font.render('Tetris', 1, WHITE) surface.blit(label, (TOP_LEFT_X + PLAY_WIDTH /2 - (label.get_width() /2), 30)) # Current Score font = pygame.font.SysFont('comicsans', 30) label = font.render(f'Score: {score}', 1, WHITE) sx = TOP_LEFT_X - 200 sy = TOP_LEFT_Y + PLAY_HEIGHT/2 - 100 surface.blit(label, (sx + 20, sy + 160)) for i in range(len(grid)): for j in range(len(grid[i])): pygame.draw.rect(surface, grid[i][j], (TOP_LEFT_X + j*BLOCK_SIZE, TOP_LEFT_Y + i*BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0) # Draw Grid and Border draw_grid(surface, grid) pygame.draw.rect(surface, (255, 0, 0), (TOP_LEFT_X, TOP_LEFT_Y, PLAY_WIDTH, PLAY_HEIGHT), 4) def main(): global SCREEN_HEIGHT, SCREEN_WIDTH screen = pygame.display.set_mode((SCREEN_WIDTH + 200, SCREEN_HEIGHT)) pygame.display.set_caption('Tetris') clock = pygame.time.Clock() grid = create_grid() change_piece = False run = True current_piece = get_shape() next_piece = get_shape() locked_positions = {} score = 0 fall_time = 0 fall_speed = 0.27 while run: grid = create_grid(locked_positions) fall_time += clock.get_rawtime() clock.tick() # Increase difficulty over time if fall_time / 1000 > fall_speed: fall_time = 0 current_piece.y +=1 if not(valid_space(current_piece, grid)) and current_piece.y > 0: current_piece.y -=1 change_piece = True for event in pygame.event.get(): if event.type == pygame.QUIT: run = False pygame.display.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: current_piece.x -=1 if not valid_space(current_piece, grid): current_piece.x +=1 elif event.key == pygame.K_RIGHT: current_piece.x +=1 if not valid_space(current_piece, grid): current_piece.x -=1 elif event.key == pygame.K_DOWN: current_piece.y +=1 if not valid_space(current_piece, grid): current_piece.y -=1 elif event.key == pygame.K_UP: current_piece.rotation = (current_piece.rotation + 1) % len(current_piece.shape) if not valid_space(current_piece, grid): current_piece.rotation = (current_piece.rotation -1 ) % len(current_piece.shape) shape_pos = convert_shape_format(current_piece) # Add piece to the grid for drawing for pos in shape_pos: x, y = pos if y > -1: grid[y][x] = current_piece.color # If piece hit the ground if change_piece: for pos in shape_pos: p = (pos[0], pos[1]) locked_positions[p] = current_piece.color current_piece = next_piece next_piece = get_shape() change_piece = False score += clear_rows(grid, locked_positions) * 10 draw_window(screen, grid, score) draw_next_shape(next_piece, screen) pygame.display.update() # Check if user lost if check_lost(locked_positions): run = False draw_text_middle(screen, "YOU LOST!", 80, WHITE) pygame.display.update() pygame.time.delay(2000) def main_menu(): screen = pygame.display.set_mode((SCREEN_WIDTH + 200, SCREEN_HEIGHT)) pygame.display.set_caption('Tetris') run = True while run: screen.fill(BLACK) draw_text_middle(screen, 'Press Any Key To Play', 60, WHITE) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: run= False if event.type == pygame.KEYDOWN: main() pygame.quit() if __name__ == "__main__": main_menu()Explanation of the Code
1. Importing Libraries and Initializing Pygame
import pygame import random pygame.init()pygame: Library used for creating video games.random: Used to select random shapes.
2. Defining Constants and Colors
Set up the screen dimensions, block size, play area, and colors used in the game.
3. Defining Shapes
Each Tetris piece (S, Z, I, O, J, L, T) is defined as a list of strings representing its rotation state. Each shape has multiple rotation states.
4. Piece Class
Represents a Tetris piece with its position, shape, color, and rotation.
class Piece: def __init__(self, x, y, shape): ...5. Grid Creation and Shape Conversion
- create_grid: Creates a 20x10 grid filled with black color, then fills in any locked positions.
- convert_shape_format: Converts the shape's string representation into grid coordinates based on its current rotation.
6. Collision and Game Over Checks
- valid_space: Checks if the current piece position is valid (no collision with other pieces or boundaries).
- check_lost: Determines if any locked positions are above the play area, signifying game over.
7. Shape Generation
- get_shape: Randomly selects a new shape to appear next.
8. Drawing Functions
- draw_text_middle: Renders text at the center of the screen.
- draw_grid: Draws grid lines on the play area.
- clear_rows: Checks and clears completed rows, updating the score accordingly.
- draw_next_shape: Displays the next shape in the queue.
- draw_window: Renders the entire game window including the grid, current score, and play area.
9. Main Game Loop
Handles the core game mechanics:
- Piece Movement: Handles user input for moving left, right, down, and rotating pieces.
- Piece Falling: Pieces automatically fall at a set speed, which can increase over time.
- Collision Handling: Prevents pieces from moving into invalid spaces and locks pieces in place when they land.
- Row Clearing: Clears completed rows and updates the score.
- Game Over: Detects when the game is over and displays a message.
10. Main Menu
Displays the main menu where the player can start the game.
Running the Game
-
Save the Code: Copy the above code into a file named
tetris.py. -
Run the Game:
python tetris.py -
Controls:
- Left Arrow: Move the piece left.
- Right Arrow: Move the piece right.
- Down Arrow: Move the piece down faster.
- Up Arrow: Rotate the piece.
-
Objective: Arrange the falling tetrominoes to form complete horizontal lines without gaps. Completed lines will clear, and you earn points. The game ends when the stack of tetrominoes reaches the top of the play area.
Customization and Extensions
Feel free to modify and enhance the game further:
- Add a Scoring System: Implement more sophisticated scoring based on multiple lines cleared simultaneously.
- Levels and Speed: Increase the falling speed as the player levels up.
- Sound Effects and Music: Add audio for actions like moving, rotating, clearing lines, and game over.
- Graphics Enhancements: Use images for blocks instead of plain colors.
- Pause Functionality: Allow the player to pause and resume the game.
Enjoy building and playing your own Tetris game!
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.