Make the game tetris in python, make sure it looks good with a nice ui and the game is…
- User
Make the game tetris in python, make sure it looks good with a nice ui and the game is functionally
- Assistant
Make the game tetris in python, make sure it looks good with a nice ui and the game is functionally
Certainly! Let's create a functional Tetris game in Python with a nice user interface using the pygame library. Below is the complete code for the game, along with instructions on how to run it.
This Tetris game features:
Python 3 installed on your system.
Pygame library installed. You can install it via pip:
pip install pygame
Save the following code in a file named tetris.py:
import pygame
import random
import sys
# Initialize Pygame
pygame.init()
# Screen dimensions
SCREEN_WIDTH = 300
SCREEN_HEIGHT = 600
GAME_WIDTH = 200 # Width of the gameplay area
GAME_HEIGHT = 600 # Height of the gameplay area
BLOCK_SIZE = 20 # Size of the blocks
BOARD_WIDTH = GAME_WIDTH // BLOCK_SIZE
BOARD_HEIGHT = GAME_HEIGHT // BLOCK_SIZE
# Colors
BLACK = (0, 0, 0)
GRAY = (128, 128, 128)
DARK_GRAY = (50, 50, 50)
WHITE = (255, 255, 255)
COLORS = [
(0, 255, 255), # Cyan
(0, 0, 255), # Blue
(255, 165, 0), # Orange
(255, 255, 0), # Yellow
(0, 255, 0), # Green
(128, 0, 128), # Purple
(255, 0, 0), # Red
]
# Define the shapes of the single parts
SHAPES = [
[[1, 1, 1, 1]], # I
[[2, 0, 0],
[2, 2, 2]], # J
[[0, 0, 3],
[3, 3, 3]], # L
[[4, 4],
[4, 4]], # O
[[0, 5, 5],
[5, 5, 0]], # S
[[0, 6, 0],
[6, 6, 6]], # T
[[7, 7, 0],
[0, 7, 7]], # Z
]
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 = COLORS[SHAPES.index(shape)]
self.rotation = 0
def image(self):
return self.shape[self.rotation % len(self.shape)]
def create_grid(locked_positions={}):
grid = [[(0, BLACK) for _ in range(BOARD_WIDTH)] for _ in range(BOARD_HEIGHT)]
for i in range(BOARD_HEIGHT):
for j in range(BOARD_WIDTH):
if (j, i) in locked_positions:
c = locked_positions[(j, i)]
grid[i][j] = (0, c)
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:
positions.append((piece.x + j, piece.y + i))
return positions
def valid_space(piece, grid):
accepted_positions = [[(j, i) for j in range(BOARD_WIDTH) if grid[i][j][0] == 0] for i in range(BOARD_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
def check_lost(positions):
for pos in positions:
x, y = pos
if y < 1:
return True
return False
def get_shape():
return Piece(BOARD_WIDTH // 2 - 2, 0, random.choice(SHAPES))
def draw_text_middle(surface, text, size, color):
font = pygame.font.SysFont('Calibri', 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))
def clear_rows(grid, locked):
increment = 0
for i in range(BOARD_HEIGHT -1, -1, -1):
row = grid[i]
if (0, BLACK) not in row:
increment += 1
ind = i
for j in range(BOARD_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:
newKey = (x, y + increment)
locked[newKey] = locked.pop(key)
return increment
def draw_grid(surface, grid):
sx = (SCREEN_WIDTH - GAME_WIDTH) // 2
sy = 0
for i in range(BOARD_HEIGHT):
pygame.draw.line(surface, DARK_GRAY, (sx, sy + i*BLOCK_SIZE), (sx + GAME_WIDTH, sy + i*BLOCK_SIZE))
for j in range(BOARD_WIDTH):
pygame.draw.line(surface, DARK_GRAY, (sx + j*BLOCK_SIZE, sy), (sx + j*BLOCK_SIZE, sy + GAME_HEIGHT))
def draw_window(surface, grid, score):
surface.fill(BLACK)
pygame.font.init()
font = pygame.font.SysFont('Calibri', 30)
label = font.render('TETRIS', True, WHITE)
surface.blit(label, (SCREEN_WIDTH // 2 - label.get_width() // 2, 30))
# Current Score
label = font.render(f'Score: {score}', True, WHITE)
surface.blit(label, (SCREEN_WIDTH - 150, SCREEN_HEIGHT // 2 - 100))
sx = (SCREEN_WIDTH - GAME_WIDTH) // 2
sy = 0
for i in range(BOARD_HEIGHT):
for j in range(BOARD_WIDTH):
pygame.draw.rect(surface, grid[i][j][1], (sx + j*BLOCK_SIZE, sy + i*BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)
draw_grid(surface, grid)
pygame.draw.rect(surface, GRAY, (sx, sy, GAME_WIDTH, GAME_HEIGHT), 5)
def main():
global SCREEN
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
score = 0
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
# Event handling
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
shape_pos = convert_shape_format(current_piece)
# Add piece to the grid for drawing
for i in range(len(shape_pos)):
x, y = shape_pos[i]
if y > -1:
grid[y][x] = (0, 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_shape()
change_piece = False
# Clear rows
score += clear_rows(grid, locked_positions) * 10
draw_window(SCREEN, grid, score)
pygame.display.update()
# Check if user lost
if check_lost(locked_positions):
run = False
draw_text_middle(SCREEN, "GAME OVER", 40, WHITE)
pygame.display.update()
pygame.time.delay(2000)
def main_menu():
global SCREEN
SCREEN = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Tetris')
run = True
while run:
SCREEN.fill(BLACK)
draw_text_middle(SCREEN, 'Press Any Key To Play', 30, 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()
Save the Code: Copy the code above into a file named tetris.py.
Install Pygame: If you haven't installed Pygame, install it using pip:
pip install pygame
Run the Game: Open a terminal in the directory where tetris.py is saved and run:
python tetris.py
You can customize the game by modifying:
COLORS list to customize Tetromino colors.SHAPES list defines the shapes of Tetrominoes.fall_speed variable to change how fast the pieces fall.Enjoy your game of Tetris! If you have any questions or need further assistance, feel free to ask.
Not yet included in a published release.