Write the game tetris
- User
Write the game tetris
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Write the game tetris
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Certainly! Let's create a simple version of Tetris using Python and the Pygame library. Tetris is a classic puzzle game where players rotate and place falling shapes (tetrominoes) to complete horizontal lines, which are then cleared from the game board.
Below is a step-by-step guide to building the game. We'll start by setting up the game window, defining the shapes, and then implementing the game logic.
Make sure you have Python 3 installed on your system. You'll also need to install the pygame library:
pip install pygame
First, import the necessary modules and define some constants for screen dimensions, grid size, and colors.
import pygame
import random
# Initialize Pygame
pygame.init()
# Screen dimensions
SCREEN_WIDTH = 300
SCREEN_HEIGHT = 600
BLOCK_SIZE = 30
# Grid dimensions
GRID_WIDTH = SCREEN_WIDTH // BLOCK_SIZE
GRID_HEIGHT = SCREEN_HEIGHT // BLOCK_SIZE
# Define colors (R, G, B)
BLACK = (0, 0, 0)
GRAY = (128, 128, 128)
COLORS = [
(0, 240, 240), # Cyan
(0, 0, 240), # Blue
(240, 160, 0), # Orange
(240, 240, 0), # Yellow
(0, 240, 0), # Green
(160, 0, 240), # Purple
(240, 0, 0), # Red
]
Define the shapes of the tetrominoes and their rotations using multi-dimensional lists.
# Shape formats
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.']]
SHAPES = [S, Z, I, O, J, L, T]
Create a class to represent each falling piece.
class Piece:
def __init__(self, x, y, shape):
self.x = x # X position on the grid
self.y = y # Y position on the grid
self.shape = shape
self.color = random.choice(COLORS)
self.rotation = 0 # Initial rotation
Define a function to create the grid and another to convert the shape formats.
def create_grid(locked_positions={}):
grid = [[BLACK for _ in range(GRID_WIDTH)] for _ in range(GRID_HEIGHT)]
for i in range(GRID_HEIGHT):
for j in range(GRID_WIDTH):
if (j, i) in locked_positions:
grid[i][j] = locked_positions[(j, i)]
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, piece.y + i))
# Adjust positions
positions = [(x - 2, y - 4) for x, y in positions]
return positions
Check if the current position of the piece is valid (not colliding with locked positions or walls).
def valid_space(piece, grid):
accepted_positions = [[(j, i) for j in range(GRID_WIDTH) if grid[i][j] == BLACK] for i in range(GRID_HEIGHT)]
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
Remove complete rows and shift everything above down.
def clear_rows(grid, locked):
full_rows = 0
for i in range(len(grid)-1, -1, -1):
row = grid[i]
if BLACK not in row:
full_rows += 1
ind = i
for j in range(len(row)):
try:
del locked[(j, i)]
except:
continue
if full_rows > 0:
for key in sorted(locked, key=lambda x: x[1])[::-1]:
x, y = key
if y < ind:
newKey = (x, y + full_rows)
locked[newKey] = locked.pop(key)
Create a function to draw the game window, including the grid and current piece.
def draw_window(surface, grid):
surface.fill(BLACK)
# Draw title
pygame.font.init()
font = pygame.font.SysFont('comicsans', 60)
label = font.render('Tetris', True, GRAY)
surface.blit(label, (SCREEN_WIDTH / 2 - label.get_width() / 2, 30))
# Draw grid
for i in range(len(grid)):
for j in range(len(grid[i])):
pygame.draw.rect(surface, grid[i][j],
(j * BLOCK_SIZE, i * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)
# Draw grid lines
draw_grid(surface)
pygame.display.update()
def draw_grid(surface):
for i in range(GRID_HEIGHT):
pygame.draw.line(surface, GRAY, (0, i * BLOCK_SIZE), (SCREEN_WIDTH, i * BLOCK_SIZE))
for j in range(GRID_WIDTH):
pygame.draw.line(surface, GRAY, (j * BLOCK_SIZE, 0), (j * BLOCK_SIZE, SCREEN_HEIGHT))
Implement the main function that contains the game loop.
def main():
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Tetris')
clock = pygame.time.Clock()
locked_positions = {}
grid = create_grid(locked_positions)
change_piece = False
run = True
current_piece = get_new_piece()
next_piece = get_new_piece()
fall_time = 0
fall_speed = 0.5 # Adjust to control how fast the pieces fall
while run:
grid = create_grid(locked_positions)
fall_time += clock.get_rawtime()
clock.tick()
# Piece falling logic
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:
# Move left
if event.key == pygame.K_LEFT:
current_piece.x -= 1
if not valid_space(current_piece, grid):
current_piece.x += 1
# Move right
elif event.key == pygame.K_RIGHT:
current_piece.x += 1
if not valid_space(current_piece, grid):
current_piece.x -= 1
# Rotate
elif event.key == pygame.K_UP:
current_piece.rotation += 1
if not valid_space(current_piece, grid):
current_piece.rotation -= 1
# Move down (accelerate)
elif event.key == pygame.K_DOWN:
current_piece.y += 1
if not valid_space(current_piece, grid):
current_piece.y -= 1
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
# Piece hit the ground
if change_piece:
for pos in shape_pos:
locked_positions[(pos[0], pos[1])] = current_piece.color
current_piece = next_piece
next_piece = get_new_piece()
change_piece = False
clear_rows(grid, locked_positions)
draw_window(screen, grid)
def get_new_piece():
return Piece(GRID_WIDTH // 2 - 2, 0, random.choice(SHAPES))
Finally, add the code to run the game when the script is executed.
if __name__ == '__main__':
main()
Putting it all together, here's the complete code for a basic Tetris game:
[Full code is an amalgamation of the snippets above. Please ensure to combine them properly when implementing.]
Feel free to ask if you have questions or need further assistance with specific parts of the code!
Not yet included in a published release.