用python写一个俄罗斯方块程序

用python写一个俄罗斯方块程序

1.源代码

import pygame
import random

# 初始化游戏
pygame.init()

# 游戏窗口尺寸
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600

# 方块大小和颜色
BLOCK_SIZE = 30
COLORS = [
    (0, 0, 0),  # 黑色
    (255, 0, 0),  # 红色
    (0, 255, 0),  # 绿色
    (0, 0, 255),  # 蓝色
    (255, 255, 0),  # 黄色
    (255, 165, 0),  # 橙色
    (0, 255, 255),  # 青色
    (128, 0, 128)  # 紫色
]

# 初始化游戏窗口
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("俄罗斯方块")

# 定义游戏区域,使用二维列表表示,0代表空格
game_area = [[0] * (WINDOW_WIDTH // BLOCK_SIZE) for _ in range(WINDOW_HEIGHT // BLOCK_SIZE)]

# 定义各种形状的俄罗斯方块
tetriminos = [
    [[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]]
]

# 初始化当前俄罗斯方块的位置和形状
current_tetrimino = random.choice(tetriminos)
current_x = (WINDOW_WIDTH // BLOCK_SIZE) // 2 - len(current_tetrimino[0]) // 2
current_y = 0

# 定义函数:绘制游戏区域
def draw_game_area():
    for y in range(WINDOW_HEIGHT // BLOCK_SIZE):
        for x in range(WINDOW_WIDTH // BLOCK_SIZE):
            if game_area[y][x] != 0:
                pygame.draw.rect(window, COLORS[game_area[y][x]], (x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE))

# 定义函数:检查当前俄罗斯方块是否触底或碰撞到其他方块
def check_collision():
    for y in range(len(current_tetrimino)):
        for x in range(len(current_tetrimino[0])):
            if current_tetrimino[y][x] == 1:
                if current_y + y >= WINDOW_HEIGHT // BLOCK_SIZE or current_x + x < 0 or current_x + x >= WINDOW_WIDTH // BLOCK_SIZE or game_area[current_y + y][current_x + x] != 0:
                    return True
    return False

# 定义函数:将当前俄罗斯方块放置到游戏区域
def place_tetrimino():
    for y in range(len(current_tetrimino)):
        for x in range(len(current_tetrimino[0])):
            if current_tetrimino[y][x] == 1:
                game_area[current_y + y][current_x + x] = len(COLORS) - 1

# 定义函数:消除满行
def clear_lines():
    lines_cleared = 0
    y = WINDOW_HEIGHT // BLOCK_SIZE - 1
    while y >= 0:
        if all(game_area[y]):
            del game_area[y]
            game_area.insert(0, [0] * (WINDOW_WIDTH // BLOCK_SIZE))
            lines_cleared += 1
        else:
            y -= 1
    return lines_cleared

# 游戏循环
running = True
clock = pygame.time.Clock()
fall_timer = 0
fall_interval = 1000  # 方块下落间隔,单位毫秒
score = 0

while running:
    window.fill(0)
    draw_game_area()

    # 方块下落
    current_time = pygame.time.get_ticks()
    if current_time - fall_timer >= fall_interval:
        fall_timer = current_time
        current_y += 1
        if check_collision():
            current_y -= 1
            place_tetrimino()
            lines_cleared = clear_lines()
            score += lines_cleared
            if lines_cleared > 0:
                fall_interval = max(fall_interval - 50, 200)  # 加快方块下落速度
            current_tetrimino = random.choice(tetriminos)
            current_x = (WINDOW_WIDTH // BLOCK_SIZE) // 2 - len(current_tetrimino[0]) // 2
            current_y = 0
            if check_collision():
                running = False

    # 处理用户输入事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                current_x -= 1
                if check_collision():
                    current_x += 1
            elif event.key == pygame.K_RIGHT:
                current_x += 1
                if check_collision():
                    current_x -= 1
            elif event.key == pygame.K_DOWN:
                current_y += 1
                if check_collision():
                    current_y -= 1
            elif event.key == pygame.K_UP:
                # 旋转方块
                rotated_tetrimino = []
                for i in range(len(current_tetrimino[0])):
                    rotated_row = [current_tetrimino[j][i] for j in range(len(current_tetrimino) - 1, -1, -1)]
                    rotated_tetrimino.append(rotated_row)
                if not check_collision():
                    current_tetrimino = rotated_tetrimino

    # 绘制当前俄罗斯方块
    for y in range(len(current_tetrimino)):
        for x in range(len(current_tetrimino[0])):
            if current_tetrimino[y][x] == 1:
                pygame.draw.rect(window, COLORS[len(COLORS) - 1], ((current_x + x) * BLOCK_SIZE, (current_y + y) * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE))

    pygame.display.update()
    clock.tick(60)

pygame.quit()

2.游戏运行

在这里插入图片描述

  • 5
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
下面是一个简单的Python俄罗斯方块游戏代码,使用了pygame库来绘制游戏界面和处理用户输入: ```python import pygame import random # 游戏区域大小 WIDTH, HEIGHT = 300, 600 # 俄罗斯方块大小 BLOCK_SIZE = 30 # 游戏区域大小(格子数) GRID_WIDTH, GRID_HEIGHT = WIDTH // BLOCK_SIZE, HEIGHT // BLOCK_SIZE # 定义方块类型和形状 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, 0], [5, 5, 5, 5]], [[0, 6, 0], [6, 6, 6], [0, 6, 0]], [[7, 7], [7, 7]] ] # 随机生成下一个方块的类型和形状 def new_block(): shape = random.choice(SHAPES) return shape, BLOCK_SIZE * (GRID_WIDTH // 2 - len(shape[0]) // 2), 0 # 将方块添加到游戏区域中 def add_block(grid, block, pos): for i in range(len(block)): for j in range(len(block[i])): if block[i][j] != 0: x, y = pos[0] + j, pos[1] + i grid[y][x] = block[i][j] # 检查方块是否与游戏区域的边界或已有方块重叠 def check_collision(grid, block, pos): for i in range(len(block)): for j in range(len(block[i])): if block[i][j] != 0: x, y = pos[0] + j, pos[1] + i if x < 0 or x >= GRID_WIDTH or y >= GRID_HEIGHT or grid[y][x] != 0: return True return False # 将游戏区域中已满一行的方块删除 def remove_full_rows(grid): rows_removed = 0 row = GRID_HEIGHT - 1 while row >= 0: if all(grid[row]): for r in range(row, 0, -1): grid[r] = grid[r-1][:] grid[0] = [0] * GRID_WIDTH rows_removed += 1 else: row -= 1 return rows_removed # 主函数 def main(): # 初始化pygame pygame.init() # 创建游戏窗口 screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Tetris") # 创建字体对象 font = pygame.font.Font(None, 36) # 初始化游戏区域 grid = [[0] * GRID_WIDTH for _ in range(GRID_HEIGHT)] # 随机生成下一个方块 next_block = new_block() # 初始化当前方块的类型、形状和位置 cur_block, cur_x, cur_y = new_block() # 游戏循环 clock = pygame.time.Clock() score = 0 while True: # 处理事件 for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() return elif event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: cur_x -= BLOCK_SIZE elif event.key == pygame.K_RIGHT: cur_x += BLOCK_SIZE elif event.key == pygame.K_DOWN: cur_y += BLOCK_SIZE elif event.key == pygame.K_UP: # 旋转方块 cur_block = [list(reversed(x)) for x in zip(*cur_block)] # 检查方块是否与游戏区域的边界或已有方块重叠 if check_collision(grid, cur_block, (cur_x, cur_y)): # 将方块添加到游戏区域中 add_block(grid, cur_block, (cur_x, cur_y)) # 将游戏区域中已满一行的方块删除 rows_removed = remove_full_rows(grid) # 更新得分 score += rows_removed ** 2 # 随机生成下一个方块 next_block = new_block() # 初始化当前方块的类型、形状和位置 cur_block, cur_x, cur_y = next_block if check_collision(grid, cur_block, (cur_x, cur_y)): # 游戏结束 text = font.render("Game Over", True, (255, 0, 0)) screen.blit(text, (WIDTH//2 - text.get_width()//2, HEIGHT//2 - text.get_height()//2)) pygame.display.flip() pygame.time.wait(2000) return # 更新方块位置 cur_y += BLOCK_SIZE # 绘制游戏界面 screen.fill((0, 0, 0)) for i in range(GRID_HEIGHT): for j in range(GRID_WIDTH): if grid[i][j] != 0: pygame.draw.rect(screen, (255, 255, 255), (j*BLOCK_SIZE, i*BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE)) for i in range(len(cur_block)): for j in range(len(cur_block[i])): if cur_block[i][j] != 0: pygame.draw.rect(screen, (255, 0, 0), (cur_x+j*BLOCK_SIZE, cur_y+i*BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE)) # 绘制下一个方块 text = font.render("Next Block", True, (255, 255, 255)) screen.blit(text, (WIDTH+20, 20)) for i in range(len(next_block[0])): for j in range(len(next_block[0][i])): if next_block[0][i][j] != 0: pygame.draw.rect(screen, (255, 0, 0), (WIDTH+j*BLOCK_SIZE+20, i*BLOCK_SIZE+60, BLOCK_SIZE, BLOCK_SIZE)) # 绘制得分 text = font.render("Score: {}".format(score), True, (255, 255, 255)) screen.blit(text, (WIDTH+20, 200)) # 更新屏幕 pygame.display.flip() # 控制游戏速度 clock.tick(10) if __name__ == "__main__": main() ``` 这个代码可以让你在Python中玩俄罗斯方块游戏,通过上下左右按键来控制方块的移动和旋转,尝试在游戏中获得更高的得分吧!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值