o1-preview-2024-09-12· OpenAI
WildChat-4.8M (AI2)
Write the game terris, full of features
- User
Write the game terris, full of features
- Assistant
Certainly! Below is a Python implementation of the classic game Tetris using the Pygame library. This version is enriched with additional features to enhance gameplay:
- Multiple Levels: The game speeds up as you clear more lines.
- Next Piece Preview: See which piece is coming next.
- Hold Functionality: Store a piece for later use.
- Scoring System: Earn points for clearing lines.
- Pause and Resume: Pause the game anytime.
- Game Over Screen: Displays your final score.
Note: Make sure you have Pygame installed. You can install it using:
bashpip install pygameHere's the code:
pythonimport pygame import random import sys # Initialize Pygame pygame.init() # Screen dimensions SCREEN_WIDTH = 600 SCREEN_HEIGHT = 700 GAME_WIDTH = 300 # Tetris game width (columns * block size) GAME_HEIGHT = 600 # Tetris game height (rows * block size) BLOCK_SIZE = 30 # Grid dimensions COLUMNS = GAME_WIDTH // BLOCK_SIZE ROWS = GAME_HEIGHT // BLOCK_SIZE # Coordinates for the play area TOP_LEFT_X = (SCREEN_WIDTH - GAME_WIDTH) // 2 TOP_LEFT_Y = SCREEN_HEIGHT - GAME_HEIGHT - 20 # Define shapes and their rotations SHAPES = [ [['.....', '.....', '..00.', '.00..', '.....'], ['.....', '..0..', '..00.', '...0.', '.....']], [['.....', '.....', '.00..', '..00.', '.....'], ['.....', '..0..', '.00..', '.0...', '.....']], [['..0..', '..0..', '..0..', '..0..', '.....'], ['.....', '0000.', '.....', '.....', '.....']], [['.....', '.....', '.00..', '.00..', '.....']], [['.....', '.0...', '.000.', '.....', '.....'], ['.....', '..00.', '..0..', '..0..', '.....'], ['.....', '.....', '.000.', '...0.', '.....'], ['.....', '..0..', '..0..', '.00..', '.....']], [['.....', '...0.', '.000.', '.....', '.....'], ['.....', '..0..', '..0..', '..00.', '.....'], ['.....', '.....', '.000.', '.0...', '.....'], ['.....', '.00..', '..0..', '..0..', '.....']], [['.....', '..0..', '.000.', '.....', '.....'], ['.....', '..0..', '..00.', '..0..', '.....'], ['.....', '.....', '.000.', '..0..', '.....'], ['.....', '..0..', '.00..', '..0..', '.....']] ] # Corresponding colors for each shape SHAPE_COLORS = [ (0, 255, 0), # S Shape (255, 0, 0), # Z Shape (0, 255, 255), # I Shape (255, 255, 0), # O Shape (255, 165, 0), # J Shape (0, 0, 255), # L Shape (128, 0, 128) # T Shape ] # Define the Piece class class Piece: def __init__(self, x, y, shape): self.x = x self.y = y self.shape = shape self.color = SHAPE_COLORS[SHAPES.index(shape)] self.rotation = 0 # Function to create the game grid def create_grid(locked_positions={}): grid = [[(0,0,0) for _ in range(COLUMNS)] for _ in range(ROWS)] for i in range(ROWS): for j in range(COLUMNS): if (j, i) in locked_positions: grid[i][j] = locked_positions[(j, i)] return grid # Function to convert shape format 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, col in enumerate(row): if col == '0': positions.append((piece.x + j - 2, piece.y + i - 4)) return positions # Check if the space is valid def valid_space(piece, grid): accepted_positions = [[(j, i) for j in range(COLUMNS) if grid[i][j] == (0,0,0)] for i in range(ROWS)] accepted_positions = [pos for sub in accepted_positions for pos in sub] formatted = convert_shape_format(piece) for pos in formatted: if pos not in accepted_positions and pos[1] > -1: return False return True # Check if the player has lost def check_lost(positions): for pos in positions: x, y = pos if y < 1: return True return False # Get a random shape def get_shape(): return Piece(COLUMNS // 2, 0, random.choice(SHAPES)) # Draw text in the middle of the screen def draw_text_middle(text, size, color, surface): font = pygame.font.SysFont('comicsans', size, bold=True) label = font.render(text, True, color) surface.blit(label, (SCREEN_WIDTH / 2 - label.get_width() / 2, SCREEN_HEIGHT / 2 - label.get_height() / 2)) # Draw the game grid def draw_grid(surface, grid): for i in range(len(grid)): pygame.draw.line(surface, (128,128,128), (TOP_LEFT_X, TOP_LEFT_Y + i*BLOCK_SIZE), (TOP_LEFT_X + GAME_WIDTH, TOP_LEFT_Y + i*BLOCK_SIZE)) for j in range(len(grid[i])): pygame.draw.line(surface, (128,128,128), (TOP_LEFT_X + j*BLOCK_SIZE, TOP_LEFT_Y), (TOP_LEFT_X + j*BLOCK_SIZE, TOP_LEFT_Y + GAME_HEIGHT)) # Clear completed rows def clear_rows(grid, locked): increment = 0 for i in range(len(grid)-1, -1, -1): row = grid[i] if (0,0,0) not in row: increment += 1 ind = i for j in range(len(row)): try: del locked[(j, i)] except: continue if increment > 0: for key in sorted(list(locked), key=lambda x: x[1])[::-1]: x, y = key if y < ind: locked[(x, y + increment)] = locked.pop(key) return increment # Draw next shape preview def draw_next_shape(piece, surface): font = pygame.font.SysFont('comicsans', 30) label = font.render('Next Shape', True, (255,255,255)) start_x = TOP_LEFT_X + GAME_WIDTH + 50 start_y = TOP_LEFT_Y + GAME_HEIGHT/2 - 100 format = piece.shape[piece.rotation % len(piece.shape)] for i, line in enumerate(format): row = list(line) for j, col in enumerate(row): if col == '0': pygame.draw.rect(surface, piece.color, (start_x + j*BLOCK_SIZE, start_y + i*BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0) surface.blit(label, (start_x + 10, start_y - 30)) # Draw hold shape def draw_hold_shape(piece, surface): font = pygame.font.SysFont('comicsans', 30) label = font.render('Hold', True, (255,255,255)) start_x = TOP_LEFT_X - 150 start_y = TOP_LEFT_Y + GAME_HEIGHT/2 - 100 if piece: format = piece.shape[piece.rotation % len(piece.shape)] for i, line in enumerate(format): row = list(line) for j, col in enumerate(row): if col == '0': pygame.draw.rect(surface, piece.color, (start_x + j*BLOCK_SIZE, start_y + i*BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0) surface.blit(label, (start_x + 20, start_y - 30)) # Draw the game window def draw_window(surface, grid, score=0, level=0): surface.fill((0,0,0)) pygame.font.init() font = pygame.font.SysFont('comicsans', 60) label = font.render('TETRIS', True, (255,255,255)) surface.blit(label, (TOP_LEFT_X + GAME_WIDTH / 2 - label.get_width() / 2, 30)) # Current score font = pygame.font.SysFont('comicsans', 30) label = font.render('Score: ' + str(score), True, (255,255,255)) start_x = TOP_LEFT_X + GAME_WIDTH + 50 start_y = TOP_LEFT_Y + GAME_HEIGHT/2 + 150 surface.blit(label, (start_x + 20, start_y + 50)) # Current level label = font.render('Level: ' + str(level), True, (255,255,255)) surface.blit(label, (start_x + 20, start_y + 80)) 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) pygame.draw.rect(surface, (255, 255, 255), (TOP_LEFT_X, TOP_LEFT_Y, GAME_WIDTH, GAME_HEIGHT), 5) draw_grid(surface, grid) # Main function def main(): global SCREEN_WIDTH, SCREEN_HEIGHT, BLOCK_SIZE, grid locked_positions = {} grid = create_grid(locked_positions) change_piece = False run = True current_piece = get_shape() next_piece = get_shape() hold_piece = None already_held = False clock = pygame.time.Clock() fall_time = 0 fall_speed = 0.3 level = 0 score = 0 lines_cleared = 0 pause = False # Set up the display win = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption('Tetris') while run: if not pause: fall_time += clock.get_rawtime() clock.tick() # Increase speed over time if lines_cleared >= 10: lines_cleared = 0 level += 1 if fall_speed > 0.1: fall_speed -= 0.02 # Piece falls faster 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() sys.exit() 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 += 1 if not valid_space(current_piece, grid): current_piece.rotation -= 1 elif event.key == pygame.K_SPACE: while valid_space(current_piece, grid): current_piece.y += 1 current_piece.y -= 1 elif event.key == pygame.K_c: if not already_held: if hold_piece is None: hold_piece = current_piece current_piece = next_piece next_piece = get_shape() else: hold_piece, current_piece = current_piece, hold_piece current_piece.x = COLUMNS // 2 current_piece.y = 0 current_piece.rotation = 0 already_held = True elif event.key == pygame.K_p: pause = True shape_pos = convert_shape_format(current_piece) # Add piece to the grid for i in range(len(shape_pos)): x, y = shape_pos[i] if y > -1: grid[y][x] = current_piece.color # If the 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 already_held = False # Check for cleared rows cleared = clear_rows(grid, locked_positions) if cleared > 0: score += cleared * 100 lines_cleared += cleared draw_window(win, grid, score, level) draw_next_shape(next_piece, win) draw_hold_shape(hold_piece, win) pygame.display.update() # Check if the player lost if check_lost(locked_positions): run = False else: draw_text_middle("Paused", 60, (255,255,255), win) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: run = False pygame.display.quit() sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_p: pause = False draw_text_middle("You Lost!", 80, (255,255,255), win) pygame.display.update() pygame.time.delay(2000) # Main menu function def main_menu(): run = True while run: win = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) draw_text_middle('Press Any Key To Play', 60, (255,255,255), win) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: run = False pygame.display.quit() sys.exit() if event.type == pygame.KEYDOWN: main() pygame.quit() if __name__ == '__main__': main_menu()Explanation of Features:
- Hold Functionality: Press 'C' to hold the current piece and retrieve it later.
- Pause and Resume: Press 'P' to pause or resume the game.
- Instant Drop: Press Spacebar to instantly drop the piece to the bottom.
- Levels and Speed Increase: The game speeds up every time you clear 10 lines.
- Scoring System: You receive points for each line cleared (100 points per line).
Controls:
- Left Arrow: Move piece left.
- Right Arrow: Move piece right.
- Down Arrow: Soft drop (move piece down faster).
- Up Arrow: Rotate piece.
- Spacebar: Hard drop (instantly drop piece to the bottom).
- 'C' Key: Hold piece.
- 'P' Key: Pause/Resume the game.
Additional Notes:
- Customize Graphics: You can customize the game's appearance by modifying colors, fonts, and adding images.
- Add Sound Effects: Integrate Pygame's
mixermodule to add sound effects and background music. - High Score Tracking: Implement file I/O to save and display high scores across game sessions.
- Enhancements: Consider adding more features like special blocks, multiplayer mode, or different game modes.
Enjoy your fully-featured Tetris game!