Certainly! Below is a Python program that implements the Tetris game with the features you've requested. This program uses the Pygame library for graphics and input handling.
Before running the code, make sure you have Pygame installed:
pip install pygame
Here's the code:
import pygame
import random
import sys
# Initialize Pygame
pygame.init()
# Get the current screen resolution for fullscreen
infoObject = pygame.display.Info()
SCREEN_WIDTH = infoObject.current_w
SCREEN_HEIGHT = infoObject.current_h
SCREEN = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.FULLSCREEN)
pygame.display.set_caption('Split-Screen Tetris')
# Define constants
BLOCK_SIZE = 30 # Size of the tetromino blocks
COLUMNS = 10 # Standard Tetris width
ROWS = SCREEN_HEIGHT // BLOCK_SIZE # Max height based on screen size
TOP_LEFT_X = (SCREEN_WIDTH // 4) - (COLUMNS * BLOCK_SIZE) // 2
TOP_LEFT_Y = 0
# Colors
BLACK = (0, 0, 0)
GRAY = (128, 128, 128)
BORDER_COLOR = (200, 200, 200)
WHITE = (255, 255, 255)
# Tetromino shapes
SHAPES = [
[['.....',
'.....',
'..O..',
'..O..',
'..O..',
'..O..',
'.....'],
['.....',
'.....',
'.....',
'OOOO',
'.....',
'.....',
'.....']],
[['.....',
'.....',
'..O..',
'.OOO.',
'.....',
'.....',
'.....'],
['.....',
'...O.',
'..OO.',
'...O.',
'.....',
'.....',
'.....'],
['.....',
'.....',
'.OOO.',
'..O..',
'.....',
'.....',
'.....'],
['.....',
'..O..',
'.OO..',
'..O..',
'.....',
'.....',
'.....']],
[['.....',
'.....',
'.OO..',
'.OO..',
'.....',
'.....',
'.....']],
[['.....',
'.....',
'..OO.',
'.OO..',
'.....',
'.....',
'.....'],
['.....',
'...O.',
'..OO.',
'..O..',
'.....',
'.....',
'.....']],
[['.....',
'.....',
'.OO..',
'..OO.',
'.....',
'.....',
'.....'],
['.....',
'..O..',
'.OO..',
'.O...',
'.....',
'.....',
'.....']],
[['.....',
'.....',
'.O...',
'.OOO.',
'.....',
'.....',
'.....'],
['.....',
'..OO.',
'..O..',
'..O..',
'.....',
'.....',
'.....'],
['.....',
'.....',
'.OOO.',
'...O.',
'.....',
'.....',
'.....'],
['.....',
'..O..',
'..O..',
'.OO..',
'.....',
'.....',
'.....']],
[['.....',
'.....',
'...O.',
'.OOO.',
'.....',
'.....',
'.....'],
['.....',
'..O..',
'..O..',
'..OO.',
'.....',
'.....',
'.....'],
['.....',
'.....',
'.OOO.',
'.O...',
'.....',
'.....',
'.....'],
['.....',
'.OO..',
'..O..',
'..O..',
'.....',
'.....',
'.....']]
]
SHAPE_COLORS = [
(0, 255, 255), # Cyan
(255, 165, 0), # Orange
(255, 255, 0), # Yellow
(0, 255, 0), # Green
(255, 0, 0), # Red
(0, 0, 255), # Blue
(128, 0, 128) # Purple
]
# Define the Piece class
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(COLUMNS)] for _ in range(ROWS)]
for i in range(ROWS):
for j in range(COLUMNS):
if (j, i) in locked_positions:
grid[i][j] = locked_positions[(j,i)]
return grid
def convert_shape_format(piece):
positions = []
shape = piece.shape[piece.rotation % len(piece.shape)]
for i, line in enumerate(shape):
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 i in range(ROWS) for j in range(COLUMNS) if grid[i][j] == BLACK]
formatted = convert_shape_format(piece)
for pos in formatted:
if pos not in accepted_positions and 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(COLUMNS // 2, 0, random.choice(SHAPES))
def draw_text_middle(text, size, color, surface, x_offset=0):
font = pygame.font.SysFont('comicsans', size, bold=True)
label = font.render(text, True, color)
surface.blit(label, (
TOP_LEFT_X + x_offset + COLUMNS * BLOCK_SIZE // 2 - (label.get_width() // 2),
TOP_LEFT_Y + ROWS * BLOCK_SIZE // 2 - label.get_height() // 2))
def draw_grid(surface, grid, x_offset=0):
for i in range(ROWS):
for j in range(COLUMNS):
pygame.draw.rect(surface, grid[i][j],
(TOP_LEFT_X + x_offset + j*BLOCK_SIZE,
TOP_LEFT_Y + i*BLOCK_SIZE,
BLOCK_SIZE, BLOCK_SIZE), 0)
# Draw Grid Lines
for i in range(ROWS):
pygame.draw.line(surface, GRAY, (TOP_LEFT_X + x_offset, TOP_LEFT_Y + i*BLOCK_SIZE),
(TOP_LEFT_X + x_offset + COLUMNS*BLOCK_SIZE, TOP_LEFT_Y + i*BLOCK_SIZE))
for j in range(COLUMNS):
pygame.draw.line(surface, GRAY, (TOP_LEFT_X + x_offset + j*BLOCK_SIZE, TOP_LEFT_Y),
(TOP_LEFT_X + x_offset + j*BLOCK_SIZE, TOP_LEFT_Y + ROWS*BLOCK_SIZE))
# Draw Border
pygame.draw.rect(surface, BORDER_COLOR, (TOP_LEFT_X + x_offset, TOP_LEFT_Y, COLUMNS*BLOCK_SIZE, ROWS*BLOCK_SIZE), 5)
def clear_rows(grid, locked):
inc = 0
for i in range(ROWS-1, -1, -1):
row = grid[i]
if BLACK not in row:
inc += 1
ind = i
for j in range(COLUMNS):
try:
del locked[(j, i)]
except:
continue
if inc > 0:
for key in sorted(list(locked), key=lambda x: x[1])[::-1]:
x, y = key
if y < ind:
newKey = (x, y + inc)
locked[newKey] = locked.pop(key)
return inc
def draw_next_shape(piece, surface, x_offset=0):
font = pygame.font.SysFont('comicsans', 30)
label = font.render('Next Shape', True, WHITE)
start_x = TOP_LEFT_X + x_offset + COLUMNS * BLOCK_SIZE + 50
start_y = TOP_LEFT_Y + (ROWS // 2 - 5) * BLOCK_SIZE
surface.blit(label, (start_x - 10, start_y - 30))
shape = piece.shape[0]
for i, line in enumerate(shape):
row = list(line)
for j, column in enumerate(row):
if column == 'O':
pygame.draw.rect(surface, piece.color,
(start_x + j*BLOCK_SIZE, start_y + i*BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)
def update_score(n, score):
scores = [0, 40, 100, 300, 1200] # Standard Tetris scoring
return score + scores[n]
def draw_window(surface, player_grid, player_locked, player_piece, player_next_piece, player_score,
computer_grid, computer_locked, computer_piece, computer_next_piece, computer_score):
surface.fill(BLACK)
# Draw grids
draw_grid(surface, player_grid)
draw_grid(surface, computer_grid, x_offset=SCREEN_WIDTH // 2)
# Draw current pieces
for pos in convert_shape_format(player_piece):
x, y = pos
if y > -1:
pygame.draw.rect(surface, player_piece.color,
(TOP_LEFT_X + x*BLOCK_SIZE, TOP_LEFT_Y + y*BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)
for pos in convert_shape_format(computer_piece):
x, y = pos
if y > -1:
pygame.draw.rect(surface, computer_piece.color,
(TOP_LEFT_X + SCREEN_WIDTH // 2 + x*BLOCK_SIZE, TOP_LEFT_Y + y*BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)
# Draw locked positions
for i in range(ROWS):
for j in range(COLUMNS):
if (j, i) in player_locked:
pygame.draw.rect(surface, player_locked[(j, i)],
(TOP_LEFT_X + j*BLOCK_SIZE, TOP_LEFT_Y + i*BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)
if (j, i) in computer_locked:
pygame.draw.rect(surface, computer_locked[(j, i)],
(TOP_LEFT_X + SCREEN_WIDTH // 2 + j*BLOCK_SIZE, TOP_LEFT_Y + i*BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 0)
# Draw next shapes
draw_next_shape(player_next_piece, surface)
draw_next_shape(computer_next_piece, surface, x_offset=SCREEN_WIDTH // 2)
# Draw scores
font = pygame.font.SysFont('comicsans', 30)
player_label = font.render(f'Score: {player_score}', True, WHITE)
computer_label = font.render(f'Score: {computer_score}', True, WHITE)
surface.blit(player_label, (TOP_LEFT_X + COLUMNS * BLOCK_SIZE + 50, TOP_LEFT_Y + 20))
surface.blit(computer_label, (TOP_LEFT_X + SCREEN_WIDTH // 2 + COLUMNS * BLOCK_SIZE + 50, TOP_LEFT_Y + 20))
pygame.display.update()
def simulate_computer_move(piece, grid):
# Simple AI that tries to place the piece in the best position
# Prioritize not losing and clearing lines
# For simplicity, we'll make the computer drop the piece straight down
# Implement a basic AI algorithm to decide the best rotation and position
best_score = None
best_position = None
best_rotation = None
for rotation in range(len(piece.shape)):
piece.rotation = rotation
positions = []
for x_pos in range(-2, COLUMNS + 2): # Allowing some buffer for piece width
piece.x = x_pos
piece.y = 0
while valid_space(piece, grid) and piece.y < ROWS:
piece.y += 1
piece.y -= 1 # Move back up to last valid position
if not valid_space(piece, grid):
continue
positions.append((piece.x, piece.y, rotation))
# Simple scoring: lower y position is better
score = piece.y
if best_score is None or score > best_score:
best_score = score
best_position = (piece.x, piece.y)
best_rotation = rotation
if best_position is not None:
piece.x, piece.y = best_position
piece.rotation = best_rotation
def main():
player_locked_positions = {}
computer_locked_positions = {}
player_grid = create_grid(player_locked_positions)
computer_grid = create_grid(computer_locked_positions)
change_player_piece = False
change_computer_piece = False
run = True
player_current_piece = get_shape()
computer_current_piece = get_shape()
player_next_piece = get_shape()
computer_next_piece = get_shape()
clock = pygame.time.Clock()
fall_time = 0
fall_speed = 0.27
player_score = 0
computer_score = 0
while run:
fall_time += clock.get_rawtime()
clock.tick()
if fall_time / 1000 >= fall_speed:
fall_time = 0
player_current_piece.y += 1
if not(valid_space(player_current_piece, player_grid)) and player_current_piece.y > 0:
player_current_piece.y -= 1
change_player_piece = True
computer_current_piece.y += 1
if not(valid_space(computer_current_piece, computer_grid)) and computer_current_piece.y > 0:
computer_current_piece.y -= 1
change_computer_piece = True
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_ESCAPE:
run = False
pygame.display.quit()
sys.exit()
# Player controls
if event.key == pygame.K_LEFT:
player_current_piece.x -= 1
if not valid_space(player_current_piece, player_grid):
player_current_piece.x += 1
if event.key == pygame.K_RIGHT:
player_current_piece.x += 1
if not valid_space(player_current_piece, player_grid):
player_current_piece.x -= 1
if event.key == pygame.K_DOWN:
player_current_piece.y += 1
if not valid_space(player_current_piece, player_grid):
player_current_piece.y -= 1
if event.key == pygame.K_UP:
player_current_piece.rotation += 1
if not valid_space(player_current_piece, player_grid):
player_current_piece.rotation -= 1
if event.key == pygame.K_SPACE or event.key == pygame.K_RETURN:
# Drop piece
while valid_space(player_current_piece, player_grid):
player_current_piece.y +=1
player_current_piece.y -=1
change_player_piece = True
# Computer move
simulate_computer_move(computer_current_piece, computer_grid)
while valid_space(computer_current_piece, computer_grid):
computer_current_piece.y +=1
computer_current_piece.y -=1
change_computer_piece = True
piece_pos = convert_shape_format(player_current_piece)
for i in range(len(piece_pos)):
x, y = piece_pos[i]
if y > -1:
player_grid[y][x] = player_current_piece.color
if change_player_piece:
for pos in piece_pos:
p = (pos[0], pos[1])
player_locked_positions[p] = player_current_piece.color
player_current_piece = player_next_piece
player_next_piece = get_shape()
change_player_piece = False
cleared = clear_rows(player_grid, player_locked_positions)
player_score = update_score(cleared, player_score)
player_grid = create_grid(player_locked_positions)
piece_pos = convert_shape_format(computer_current_piece)
for i in range(len(piece_pos)):
x, y = piece_pos[i]
if y > -1:
computer_grid[y][x] = computer_current_piece.color
if change_computer_piece:
for pos in piece_pos:
p = (pos[0], pos[1])
computer_locked_positions[p] = computer_current_piece.color
computer_current_piece = computer_next_piece
computer_next_piece = get_shape()
change_computer_piece = False
cleared = clear_rows(computer_grid, computer_locked_positions)
computer_score = update_score(cleared, computer_score)
computer_grid = create_grid(computer_locked_positions)
draw_window(SCREEN, player_grid, player_locked_positions, player_current_piece, player_next_piece, player_score,
computer_grid, computer_locked_positions, computer_current_piece, computer_next_piece, computer_score)
if check_lost(player_locked_positions):
draw_text_middle("You Lost!", 80, WHITE, SCREEN)
pygame.display.update()
pygame.time.delay(2000)
run = False
if check_lost(computer_locked_positions):
draw_text_middle("Computer Lost!", 80, WHITE, SCREEN, x_offset=SCREEN_WIDTH // 2)
pygame.display.update()
pygame.time.delay(2000)
run = False
pygame.display.quit()
sys.exit()
if __name__ == '__main__':
main()
Explanation:
- Fullscreen Mode: The game uses the full screen resolution for the display.
- Quit with [Escape]: Pressing the Escape key exits the game.
- Split-Screen: The screen is split into two halves; the left side is for the human player, and the right side is for the computer player.
- Player Controls:
- Left/Right arrows to move the piece horizontally.
- Up arrow to rotate the piece.
- Down arrow to move the piece down faster.
- Space or Return key to drop the piece instantly.
- Standard Tetris Scores: The game uses standard Tetris scoring for line clears.
- Game Grid: The grid has a standard width of 10 blocks and a height that fits the full screen.
- Losing Condition: A player loses when a new piece cannot spawn due to blocks reaching the top of the grid.
- Score and Next Piece Preview: Each side displays the current score and a preview of the next piece.
- Computer Player: The AI tries to survive indefinitely by placing pieces in the best position. It uses a simple heuristic to choose the position that allows it to survive and clear lines effectively.
Note: This AI is relatively simple and may not play perfectly. For a more advanced AI, you can implement algorithms like the Tetris AI using the Tetris Agent or more sophisticated heuristics.
Running the Game:
- Ensure Pygame is installed.
- Run the script.
- Enjoy playing Tetris against the computer!