write a python code run terris game
- User
write a python code run terris game
- Assistant
write a python code run terris game
Certainly! Below is a Python code for a basic Tetris game using the pygame library. This code implements the core functionality of Tetris, including moving and rotating pieces, clearing lines, and tracking the score.
Make sure you have Python 3 installed on your system. You'll also need to install the pygame library if you haven't already. You can install it using pip:
pip install pygame
import pygame
import random
pygame.init()
# Screen dimensions
SCREEN_WIDTH = 400
SCREEN_HEIGHT = 500
BLOCK_SIZE = 20
# Playable grid dimensions
GRID_WIDTH = SCREEN_WIDTH // BLOCK_SIZE
GRID_HEIGHT = SCREEN_HEIGHT // BLOCK_SIZE
# Colors (R, G, B)
BLACK = (0, 0, 0)
GRAY = (128, 128, 128)
# Define shapes and their rotations
SHAPES = [
[['.....',
'.....',
'..O..',
'..O..',
'..O..'],
['.....',
'..OO.',
'..O..',
'.....',
'.....']],
[['.....',
'..O..',
'..O..',
'..OO.',
'.....'],
['.....',
'.....',
'..OO.',
'..O..',
'..O..']],
[['.....',
'.....',
'..OO.',
'..OO.',
'.....']],
[['.....',
'..O..',
'..OO.',
'...O.',
'.....'],
['.....',
'.....',
'..OO.',
'.OO..',
'.....']],
[['.....',
'...O.',
'..OO.',
'..O..',
'.....'],
['.....',
'.....',
'.OO..',
'..OO.',
'.....']],
[['.....',
'..O..',
'..O..',
'..O..',
'.....'],
['.....',
'.....',
'OOO..',
'.....',
'.....']],
[['.....',
'.....',
'..O..',
'..O..',
'.....']]
]
# Assign colors to shapes
SHAPE_COLORS = [
(0, 255, 255), # Cyan
(255, 165, 0), # Orange
(0, 0, 255), # Blue
(255, 255, 0), # Yellow
(0, 255, 0), # Green
(128, 0, 128), # Purple
(255, 0, 0) # Red
]
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
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:
c = locked_positions[(j, i)]
grid[i][j] = c
return grid
def convert_shape_format(piece):
positions = []
shape_format = piece.shape[piece.rotation % len(piece.shape)]
for i, line in enumerate(shape_format):
row = list(line)
for j, column in enumerate(row):
if column == 'O':
positions.append((piece.x + j - 2, piece.y + i - 4))
return positions
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
def check_lost(positions):
for pos in positions:
x, y = pos
if y < 1:
return True
return False
def get_shape():
return Piece(GRID_WIDTH // 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 draw_grid(surface, grid):
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))
def clear_rows(grid, locked):
increment = 0
for i in range(len(grid)-1, -1, -1):
row = grid[i]
if BLACK 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('Calibri', 20)
label = font.render('Next Shape', True, (255, 255, 255))
sx = SCREEN_WIDTH + 50
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 == 'O':
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 draw_window(surface, grid, score=0):
surface.fill(BLACK)
font = pygame.font.SysFont('Calibri', 40)
label = font.render('Tetris', True, (255, 255, 255))
surface.blit(label, (SCREEN_WIDTH / 2 - label.get_width() / 2, 30))
# Current Score
font = pygame.font.SysFont('Calibri', 20)
label = font.render('Score: ' + str(score), True, (255, 255, 255))
sx = SCREEN_WIDTH + 50
sy = SCREEN_HEIGHT / 2 - 100
surface.blit(label, (sx + 20, sy + 160))
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 and border
draw_grid(surface, grid)
pygame.draw.rect(surface, (255, 0, 0), (0, 0, SCREEN_WIDTH, SCREEN_HEIGHT), 5)
def main():
global SCREEN_WIDTH, SCREEN_HEIGHT
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
screen = pygame.display.set_mode((SCREEN_WIDTH + 200, SCREEN_HEIGHT))
pygame.display.set_caption('Tetris')
while run:
grid = create_grid(locked_positions)
fall_time += clock.get_rawtime()
level_time += clock.get_rawtime()
clock.tick()
# Increase speed every 5 seconds
if level_time / 1000 > 5:
level_time = 0
if fall_speed > 0.12:
fall_speed -= 0.005
# Piece falling
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
# Events 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 += 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 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:
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()
# Check if user lost
if check_lost(locked_positions):
draw_text_middle(screen, "Game Over", 80, (255, 255, 255))
pygame.display.update()
pygame.time.delay(2000)
run = False
def main_menu():
run = True
screen = pygame.display.set_mode((SCREEN_WIDTH + 200, SCREEN_HEIGHT))
pygame.display.set_caption('Tetris')
while run:
screen.fill(BLACK)
draw_text_middle(screen, 'Press Any Key To Play', 60, (255, 255, 255))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
main()
if event.type == pygame.QUIT:
run = False
pygame.quit()
if __name__ == '__main__':
main_menu()
Save the Code: Copy the code above and save it into a file named tetris.py.
Install Pygame: Ensure that pygame is installed. If not, install it using:
pip install pygame
Run the Game: Execute the script using the command:
python tetris.py
Controls:
Objective: Fill horizontal lines with blocks to clear them and earn points. The game ends when the pieces stack up to the top of the screen.
Importing Modules: The game uses the pygame library for graphics and random for randomizing the shapes.
Constants: Variables like SCREEN_WIDTH, SCREEN_HEIGHT, and BLOCK_SIZE define the size of the game window and blocks.
Shapes Definition: The SHAPES list contains the Tetris shapes represented as 2D arrays of strings.
Piece Class: Represents each falling piece, including its position, shape, color, and rotation.
Grid Creation: The create_grid function generates the game's grid, which is updated as pieces move.
Collision and Movement: Functions like valid_space and convert_shape_format handle piece movement and collision detection.
Drawing Functions: Functions like draw_window, draw_grid, and draw_next_shape handle all the rendering of game elements.
Game Loop: The main function contains the game loop, handling input, updating the game state, and rendering graphics every frame.
Game Over: The game checks for loss conditions and displays "Game Over" when the player loses.
Enjoy playing your own Tetris game! If you have any questions or need further assistance, feel free to ask.
Not yet included in a published release.