俄罗斯方块游戏的Python代码示例

import pygame
from pygame.locals import *
import random

# 定义方块的形状
shapes = [
    [[1, 1, 1, 1]],
    [[1, 1],
     [1, 1]],
    [[1, 1, 0],
     [0, 1, 1]],
    [[0, 1, 1],
     [1, 1, 0]],
    [[1, 1, 1],
     [0, 1, 0]],
    [[1, 1, 1],
     [1, 0, 0]],
    [[1, 1, 1],
     [0, 0, 1]]
]

# 初始化游戏
pygame.init()
WIDTH, HEIGHT = 300, 600
WIN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("俄罗斯方块")

# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
CYAN = (0, 255, 255)
ORANGE = (255, 165, 0)
PURPLE = (128, 0, 128)

# 定义方块的大小和位置
BLOCK_SIZE = 30
GRID_WIDTH, GRID_HEIGHT = WIDTH // BLOCK_SIZE, HEIGHT // BLOCK_SIZE

# 游戏循环
def game_loop():
    grid = [[BLACK] * GRID_WIDTH for _ in range(GRID_HEIGHT)]  # 初始化游戏网格

    # 创建一个随机方块
    shape = random.choice(shapes)
    current_x = GRID_WIDTH // 2 - len(shape[0]) // 2
    current_y = 0

    clock = pygame.time.Clock()
    game_over = False
    while not game_over:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                return

            if event.type == KEYDOWN:
                if event.key == K_LEFT:
                    current_x -= 1
                    if not check_collision(shape, current_x, current_y, grid):
                        current_x += 1
                elif event.key == K_RIGHT:
                    current_x += 1
                    if not check_collision(shape, current_x, current_y, grid):
                        current_x -= 1
                elif event.key == K_DOWN:
                    current_y += 1
                    if not check_collision(shape, current_x, current_y, grid):
                        current_y -= 1
                elif event.key == K_SPACE:
                    shape = rotate(shape)
                    if not check_collision(shape, current_x, current_y, grid):
                        shape = rotate(shape, rotate_counterclockwise=True)

        if not check_collision(shape, current_x, current_y, grid):
            current_y += 1

        if check_game_over(shape, current_x, current_y, grid):
            game_over = True

        # 更新游戏网格
        update_grid(shape, current_x, current_y, grid)

        # 消除满行
        clear_lines(grid)

        # 画出游戏界面
        draw_grid(grid)
        draw_shape(shape, current_x, current_y)

        pygame.display.flip()
        clock.tick(5)

# 检查方块是否与游戏网格发生碰撞
def check_collision(shape, x, y, grid):
    for row in range(len(shape)):
        for col in range(len(shape[row])):
            if shape[row][col] == 1:
                if (y + row >= GRID_HEIGHT or x + col < 0 or x + col >= GRID_WIDTH or 
                    grid[y + row][x + col] != BLACK):
                    return True
    return False

# 检查游戏是否结束
def check_game_over(shape, x, y, grid):
    for row in range(len(shape)):
        for col in range(len(shape[row])):
            if shape[row][col] == 1 and y + row < 0:
                return True
    return False

# 更新游戏网格
def update_grid(shape, x, y, grid):
    for row in range(len(shape)):
        for col in range(len(shape[row])):
            if shape[row][col] == 1:
                grid[y + row][x + col] = current_color

# 消除满行
def clear_lines(grid):
    for row in range(GRID_HEIGHT):
        if all(cell != BLACK for cell in grid[row]):
            del grid[row]
            grid.insert(0, [BLACK] * GRID_WIDTH)

# 旋转方块
def rotate(shape, rotate_counterclockwise=False):
    if rotate_counterclockwise:
        return [[shape[col][len(shape) - 1 - row] for col in range(len(shape))] 
                for row in range(len(shape[0]))]
    else:
        return [[shape[len(shape) - 1 - col][row] for col in range(len(shape))] 
                for row in range(len(shape[0]))]

# 画出游戏网格
def draw_grid(grid):
    for row in range(GRID_HEIGHT):
        for col in range(GRID_WIDTH):
            pygame.draw.rect(WIN, grid[row][col], 
                             (col * BLOCK_SIZE, row * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE))
            pygame.draw.rect(WIN, WHITE, 
                             (col * BLOCK_SIZE, row * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 1)

# 画出方块
def draw_shape(shape, x, y):
    for row in range(len(shape)):
        for col in range(len(shape[row])):
            if shape[row][col] == 1:
                pygame.draw.rect(WIN, current_color, 
                                 ((x + col) * BLOCK_SIZE, (y + row) * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE))
                pygame.draw.rect(WIN, WHITE, 
                                 ((x + col) * BLOCK_SIZE, (y + row) * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE), 1)

# 游戏开始
game_loop()
 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个用 PythonPygame 实现的俄罗斯方块游戏代码示例。该代码实现了基本的游戏逻辑和图形界面。您可以根据自己的需要进行修改和优化。 ```python import pygame import random # 游戏区域宽度和高度 WIDTH = 300 HEIGHT = 600 # 方块大小 BLOCK_SIZE = 30 # 方块种类和颜色 SHAPES = [ [[1, 1, 1], [0, 1, 0]], [[0, 2, 2], [2, 2, 0]], [[3, 3, 0], [0, 3, 3]], [[4, 0, 0], [4, 4, 4]], [[0, 0, 5], [5, 5, 5]], [[6, 6, 6, 6]], [[7, 7], [7, 7]] ] COLORS = [(0, 0, 0), (255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (255, 0, 255), (0, 255, 255), (128, 128, 128)] # 初始化 Pygame pygame.init() # 创建游戏窗口 screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('Tetris') # 绘制方块 def draw_block(x, y, color): pygame.draw.rect(screen, COLORS[color], [BLOCK_SIZE * x, BLOCK_SIZE * y, BLOCK_SIZE, BLOCK_SIZE]) # 绘制游戏区域 def draw_board(board): for y, row in enumerate(board): for x, color in enumerate(row): if color: draw_block(x, y, color) # 创建新的方块 def new_block(): shape = random.choice(SHAPES) block = {'shape': shape, 'x': int(WIDTH / BLOCK_SIZE / 2) - int(len(shape[0]) / 2), 'y': 0, 'color': random.randint(1, len(COLORS) - 1)} return block # 检查方块是否碰撞 def check_collision(board, block, offset): off_x, off_y = offset for y, row in enumerate(block['shape']): for x, val in enumerate(row): if val and board[y + block['y'] + off_y][x + block['x'] + off_x]: return True return False # 将方块放到游戏区域中 def place_block(board, block): for y, row in enumerate(block['shape']): for x, val in enumerate(row): if val: board[y + block['y']][x + block['x']] = block['color'] # 移除已满的行 def remove_rows(board): num_removed = 0 y = len(board) - 1 while y >= 0: if all(board[y]): del board[y] num_removed += 1 else: y -= 1 for i in range(num_removed): board.insert(0, [0] * (WIDTH // BLOCK_SIZE)) return num_removed # 游戏主循环 def main(): # 初始化游戏区域 board = [[0] * (WIDTH // BLOCK_SIZE) for _ in range(HEIGHT // BLOCK_SIZE)] # 初始化分数和速度 score = 0 speed = 1 # 创建第一个方块 block = new_block() # 游戏主循环 while True: # 处理事件 for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() return # 处理方块移动和旋转 keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: if not check_collision(board, block, (-1, 0)): block['x'] -= 1 if keys[pygame.K_RIGHT]: if not check_collision(board, block, (1, 0)): block['x'] += 1 if keys[pygame.K_DOWN]: if not check_collision(board, block, (0, 1)): block['y'] += 1 if keys[pygame.K_UP]: old_shape = block['shape'] block['shape'] = [list(reversed(x)) for x in zip(*block['shape'])] if check_collision(board, block, (0, 0)): block['shape'] = old_shape if keys[pygame.K_SPACE]: while not check_collision(board, block, (0, 1)): block['y'] += 1 # 处理方块下落 if check_collision(board, block, (0, 1)): place_block(board, block) num_rows = remove_rows(board) score += 10 * num_rows speed = 1 + score // 1000 block = new_block() if check_collision(board, block, (0, 0)): pygame.quit() return # 绘制游戏界面 screen.fill(COLORS[0]) draw_board(board) for y, row in enumerate(block['shape']): for x, val in enumerate(row): if val: draw_block(block['x'] + x, block['y'] + y, block['color']) pygame.display.update() # 控制游戏速度 pygame.time.wait(1000 // speed) if __name__ == '__main__': main() ``` 希望这段代码能够对您有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值