o1-preview-2024-09-12· OpenAI
WildChat-4.8M (AI2)
Write a code for Python that would generate a simple Tetris game for me
- User
Write a code for Python that would generate a simple Tetris game for me
- Assistant
Write a code for Python that would generate a simple Tetris game for me
Sure! Here's a simple implementation of a Tetris-like game using Python and the Pygame library. This code will create a basic version of Tetris where you can move and rotate tetrominoes as they fall.
First, make sure you have Pygame installed. You can install it using pip:
pip install pygame
Now, here's the code:
import pygame
import random
# Initialize Pygame
pygame.init()
# Set up display
WIDTH, HEIGHT = 300, 600
win = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Simple Tetris")
# Set up grid
BLOCK_SIZE = 30
GRID_WIDTH = WIDTH // BLOCK_SIZE
GRID_HEIGHT = HEIGHT // BLOCK_SIZE
# Define shapes (tetrominoes)
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]
SHAPE_COLORS = [
(48, 211, 56), # Green for S
(211, 56, 56), # Red for Z
(56, 184, 211), # Light Blue for I
(211, 211, 56), # Yellow for O
(56, 56, 211), # Blue for J
(211, 127, 56), # Orange for L
(128, 0, 128) # Purple for T
]
# Define the grid
def create_grid(locked_positions={}):
grid = [[(0, 0, 0) 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:
c = locked_positions[(j, i)]
grid[i][j] = c
return grid
# Convert shape format
def convert_shape_format(shape):
positions = []
format = shape.shape[shape.rotation % len(shape.shape)]
for i, line in enumerate(format):
row = list(line)
for j, column in enumerate(row):
if column == '0':
positions.append((shape.x + j - 2, shape.y + i - 4))
return positions
# Check if position is valid
def valid_space(shape, grid):
accepted_positions = [[(j, i) for j in range(GRID_WIDTH) if grid[i][j] == (0,0,0)] for i in range(GRID_HEIGHT)]
accepted_positions = [pos for sublist in accepted_positions for pos in sublist]
formatted = convert_shape_format(shape)
for pos in formatted:
if pos not in accepted_positions:
if pos[1] > -1:
return False
return True
# Check if game is 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(5, 0, random.choice(SHAPES))
# Draw text in the middle of the screen
def draw_text_middle(text, size, color, surface):
pass # For simplification, not implementing this function
# Clear complete rows
def clear_rows(grid, locked):
increment = 0
for i in range(GRID_HEIGHT-1, -1, -1):
row = grid[i]
if (0, 0, 0) not in row:
increment += 1
ind = i
for j in range(GRID_WIDTH):
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:
new_key = (x, y + increment)
locked[new_key] = locked.pop(key)
return increment
# Draw grid lines
def draw_grid(surface, grid):
for i in range(GRID_HEIGHT):
pygame.draw.line(surface, (128,128,128), (0, i*BLOCK_SIZE), (WIDTH, i*BLOCK_SIZE))
for j in range(GRID_WIDTH):
pygame.draw.line(surface, (128,128,128), (j*BLOCK_SIZE, 0), (j*BLOCK_SIZE, HEIGHT))
# Draw window
def draw_window(surface, grid):
surface.fill((0,0,0))
for i in range(GRID_HEIGHT):
for j in range(GRID_WIDTH):
pygame.draw.rect(surface, grid[i][j], (j*BLOCK_SIZE, i*BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)
draw_grid(surface, grid)
pygame.display.update()
# Main piece class
class Piece(object):
def __init__(self, column, row, shape):
self.x = column
self.y = row
self.shape = shape
self.color = SHAPE_COLORS[SHAPES.index(shape)]
self.rotation = 0
# Main function
def main():
locked_positions = {}
grid = create_grid(locked_positions)
change_piece = False
run = True
current_piece = get_shape()
next_piece = get_shape()
clock = pygame.time.Clock()
fall_time = 0
fall_speed = 0.27 # Adjust to make pieces fall faster or slower
while run:
fall_time += clock.get_rawtime()
clock.tick()
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()
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
shape_pos = convert_shape_format(current_piece)
for i in range(len(shape_pos)):
x, y = shape_pos[i]
if y > -1:
grid[y][x] = current_piece.color
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
clear_rows(grid, locked_positions)
draw_window(win, grid)
if check_lost(locked_positions):
run = False
pygame.display.quit()
if __name__ == "__main__":
main()
Explanation:
SHAPES list contains the standard Tetris pieces represented as 2D arrays for rotation.main function): Handles the main game logic, including piece movement, rotation, collision detection, and input handling.Instructions:
tetris.py.python tetris.py
Notes:
Dependencies:
If you encounter any issues or have questions about how the code works, feel free to ask!
Not yet included in a published release.