Make a python tetris game and where to run it online
- User
Make a python tetris game and where to run it online
- Assistant
Make a python tetris game and where to run it online
Creating a Tetris game in Python is a fun and educational project that can help you understand game development fundamentals. Below, I'll guide you through building a simple Tetris game using the pygame library and explain how to run it online using Replit, an online IDE that supports Python and pygame.
Before you begin, ensure you have a basic understanding of Python programming. Familiarity with libraries like pygame will be beneficial but not strictly necessary as this guide provides step-by-step instructions.
Create a New Repl:
pygame manually.Install Pygame (If Necessary):
pygame.pip install pygame
Prepare the File Structure:
main.py file for your game code.Below is a simplified version of a Tetris game using pygame. This code covers the basic functionalities: creating tetrominoes, moving them, rotating, collision detection, and clearing lines.
Note: Tetris is a moderately complex game. This implementation aims to be as simple as possible while retaining core functionalities.
main.py Codeimport pygame
import random
# Initialize Pygame
pygame.init()
# Screen dimensions
SCREEN_WIDTH = 300
SCREEN_HEIGHT = 600
BLOCK_SIZE = 30
# Define the play area dimensions
PLAY_WIDTH = 10 # 10 blocks wide
PLAY_HEIGHT = 20 # 20 blocks high
# Define shapes
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), (255, 0, 0), (0, 255, 255),
(255, 255, 0), (255, 165, 0), (0, 0, 255), (128, 0, 128)]
# Define the font
FONT = pygame.font.SysFont('comicsans', 30)
class Piece(object):
def __init__(self, x, y, shape):
self.x = x # Horizontal position on the grid
self.y = y # Vertical position on the grid
self.shape = shape
self.color = SHAPE_COLORS[SHAPES.index(shape)]
self.rotation = 0 # Number from 0- (len(shape) -1)
def create_grid(locked_positions={}):
grid = [[(0,0,0) for _ in range(10)] for _ in range(20)]
for i in range(len(grid)):
for j in range(len(grid[i])):
if (j,i) in locked_positions:
c = locked_positions[(j,i)]
grid[i][j] = c
return grid
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))
# Adjust positions to be within grid
for i, pos in enumerate(positions):
positions[i] = (pos[0], pos[1])
return positions
def valid_space(shape, grid):
accepted_positions = [[(j, i) for j in range(10) if grid[i][j] == (0,0,0)] for i in range(20)]
accepted_positions = [j for sub in accepted_positions for j in sub]
formatted = convert_shape_format(shape)
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(text, size, color, surface):
font = pygame.font.SysFont("comicsans", size, bold=True)
label = font.render(text, 1, color)
surface.blit(label, (SCREEN_WIDTH/2 - (label.get_width()/2), SCREEN_HEIGHT/2 - label.get_height()/2))
def draw_grid(surface, grid):
sx = (SCREEN_WIDTH - PLAY_WIDTH * BLOCK_SIZE) // 2
sy = SCREEN_HEIGHT - PLAY_HEIGHT * BLOCK_SIZE
for i in range(len(grid)):
pygame.draw.line(surface, (128,128,128), (sx, sy + i*BLOCK_SIZE),
(sx + PLAY_WIDTH * BLOCK_SIZE, sy + i * BLOCK_SIZE)) # horizontal lines
for j in range(len(grid[i])):
pygame.draw.line(surface, (128,128,128), (sx + j*BLOCK_SIZE, sy),
(sx + j*BLOCK_SIZE, sy + PLAY_HEIGHT * BLOCK_SIZE)) # vertical lines
def clear_rows(grid, locked):
# Need to check if row is clear then shift every other row above down
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:
newKey = (x, y + increment)
locked[newKey] = locked.pop(key)
return increment
def draw_next_shape(shape, surface):
font = pygame.font.SysFont('comicsans', 30)
label = font.render('Next Shape', 1, (255,255,255))
sx = SCREEN_WIDTH - 200
sy = SCREEN_HEIGHT/2 - 100
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':
pygame.draw.rect(surface, shape.color, (sx + j*BLOCK_SIZE, sy + i*BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)
surface.blit(label, (sx + 10, sy - 30))
def update_score(n):
pass # Placeholder for score updating
def draw_window(surface, grid, score=0):
surface.fill((0,0,0))
# Tetris Title
font = pygame.font.SysFont('comicsans', 60)
label = font.render('Tetris', 1, (255,255,255))
surface.blit(label, ((SCREEN_WIDTH - label.get_width())//2, 30))
# Current Score
font = pygame.font.SysFont('comicsans', 30)
label = font.render(f'Score: {score}', 1, (255,255,255))
sx = (SCREEN_WIDTH - PLAY_WIDTH * BLOCK_SIZE) // 2
sy = SCREEN_HEIGHT - PLAY_HEIGHT * BLOCK_SIZE
surface.blit(label, (sx, sy - 40))
for i in range(len(grid)):
for j in range(len(grid[i])):
pygame.draw.rect(surface, grid[i][j],
( (SCREEN_WIDTH - PLAY_WIDTH * BLOCK_SIZE) //2 + j*BLOCK_SIZE,
sy + i*BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)
draw_grid(surface, grid)
pygame.display.update()
def main():
global SCREEN_WIDTH, SCREEN_HEIGHT
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Tetris')
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
level_time = 0
score = 0
while run:
grid = create_grid(locked_positions)
fall_time += clock.get_rawtime()
level_time += clock.get_rawtime()
clock.tick()
# Increase speed as time passes
if level_time/1000 > 5:
level_time = 0
if fall_speed > 0.12:
fall_speed -= 0.005
# Falling mechanism
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
# Event handling
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)
# Lock piece and generate new one
shape_pos = convert_shape_format(current_piece)
for pos in shape_pos:
x, y = pos
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
score += clear_rows(grid, locked_positions) * 10
draw_window(screen, grid, score)
draw_next_shape(next_piece, screen)
pygame.display.update()
if check_lost(locked_positions):
draw_text_middle("YOU LOST!", 80, (255,255,255), screen)
pygame.display.update()
pygame.time.delay(2000)
run = False
pygame.quit()
def main_menu():
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Tetris')
run = True
while run:
screen.fill((0,0,0))
draw_text_middle('Press Any Key To Play', 60, (255,255,255), screen)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
main()
pygame.quit()
main_menu()
Imports and Initialization:
pygame for game development, random for randomizing tetrominoes.pygame and sets up screen dimensions and colors.Defining Tetrominoes:
Piece Class:
Grid Creation and Management:
create_grid: Creates the game grid and populates it with locked positions.convert_shape_format: Converts the shape's rotation into grid positions.valid_space: Checks if the current position is valid (no collision).check_lost: Determines if the game is over.Drawing Functions:
draw_window: Renders the game window, including the grid and current score.draw_next_shape: Shows the next tetromino.draw_grid: Draws the grid lines.Game Mechanics:
Main Game Loop:
Main Menu:
Paste the Code:
main.py with the code provided above.Run the Repl:
Interact with the Game:
Playing Online:
Enjoy building and playing your Python Tetris game! If you encounter any issues or have questions, feel free to ask.
Not yet included in a published release.