当前位置: 首页 > news >正文

Python小游戏15——俄罗斯方块

如果你还没有安装pygame,可以通过运行pip install pygame来安装它。

fc88822fd24f4c27b86f8ec7642b51fd.png

 

  • 代码如下:

python

import pygame

import random

 

# 初始化pygame

pygame.init()

 

# 屏幕尺寸

WIDTH, HEIGHT = 10, 20

TILE_SIZE = 40

WINDOW_SIZE = WIDTH * TILE_SIZE, HEIGHT * TILE_SIZE

WINDOW = pygame.display.set_mode(WINDOW_SIZE)

pygame.display.set_caption("Tetris")

 

# 颜色定义

WHITE = (255, 255, 255)

BLACK = (0, 0, 0)

CYAN = (0, 255, 255)

MAGENTA = (255, 0, 255)

YELLOW = (255, 255, 0)

BLUE = (0, 0, 255)

GREEN = (0, 255, 0)

RED = (255, 0, 0)

ORANGE = (255, 165, 0)

 

# 形状定义

SHAPES = [

    [[1, 1, 1, 1]], # I

    [[1, 1], [1, 1]], # O

    [[1, 1, 1], [0, 1, 0]], # T

    [[1, 1, 0], [1, 1, 0]], # S

    [[0, 1, 1], [1, 1, 0]], # Z

    [[1, 1, 1], [1, 0, 0]], # J

    [[1, 1, 1], [0, 0, 1]], # L

]

 

# 游戏变量

clock = pygame.time.Clock()

FPS = 15

board = [[0] * WIDTH for _ in range(HEIGHT)]

next_piece = random.choice(SHAPES)

current_piece = [[0] * WIDTH for _ in range(HEIGHT)]

piece_x, piece_y = WIDTH // 2 - len(next_piece[0]) // 2, 0

piece_color = random.choice([CYAN, MAGENTA, YELLOW, BLUE, GREEN, RED, ORANGE])

dropping = False

game_over = False

score = 0

 

# 检查是否消除行

def check_lines():

    nonlocal score

    lines_cleared = 0

    for y in range(HEIGHT):

        if all(board[y][x] != 0 for x in range(WIDTH)):

            for y2 in range(y, 0, -1):

                board[y2] = board[y2 - 1][:]

            board[0] = [0] * WIDTH

            lines_cleared += 1

            score += 10 * (lines_cleared + 1)

    return lines_cleared > 0

 

# 绘制游戏板

def draw_board():

    WINDOW.fill(BLACK)

    for y in range(HEIGHT):

        for x in range(WIDTH):

            if board[y][x] != 0:

                color = (

                    YELLOW if board[y][x] == 1 else

                    MAGENTA if board[y][x] == 2 else

                    CYAN if board[y][x] == 3 else

                    BLUE if board[y][x] == 4 else

                    GREEN if board[y][x] == 5 else

                    RED if board[y][x] == 6 else

                    ORANGE

                )

                pygame.draw.rect(WINDOW, color, (x * TILE_SIZE, y * TILE_SIZE, TILE_SIZE, TILE_SIZE))

 

# 绘制当前下落中的形状

def draw_piece():

    for y, row in enumerate(current_piece):

        for x, cell in enumerate(row):

            if cell != 0:

                pygame.draw.rect(WINDOW, piece_color, ((piece_x + x) * TILE_SIZE, (piece_y + y) * TILE_SIZE, TILE_SIZE, TILE_SIZE))

 

# 主游戏循环

running = True

while running:

    for event in pygame.event.get():

        if event.type == pygame.QUIT:

            running = False

        elif event.type == pygame.KEYDOWN:

            if event.key == pygame.K_LEFT and piece_x > 0:

                piece_x -= 1

            elif event.key == pygame.K_RIGHT and piece_x < WIDTH - len(next_piece[0]):

                piece_x += 1

            elif event.key == pygame.K_DOWN or dropping:

                dropping = True

                piece_y += 1

                if not all(all(board[piece_y + y][piece_x + x] == 0 or board[piece_y + y][piece_x + x] == piece_color for x, cell in enumerate(row)) for y, row in enumerate(next_piece)):

                    for y, row in enumerate(next_piece):

                        for x, cell in enumerate(row):

                            if cell != 0:

                                current_piece[y][x] = board[piece_y + y][piece_x + x]

                                board[piece_y + y][piece_x + x] = piece_color

                    piece_y = -1

                    dropping = False

                    next_piece = random.choice(SHAPES)

                    piece_color = random.choice([CYAN, MAGENTA, YELLOW, BLUE, GREEN, RED, ORANGE])

                    if not all(all(cell == 0 or (x >= piece_x and x < piece_x + len(next_piece[0]) and y >= 0 and y < len(next_piece)) and (next_piece[y - piece_y][x - piece_x] == 0 or next_piece[y - piece_y][x - piece_x] == piece_color) for x, cell in enumerate(row)) for y, row in enumerate(board[0:HEIGHT-piece_y])):

                        game_over = True

                    if check_lines():

                        dropping = True

 

    if game_over:

        running = False

 

    # 更新当前形状位置

    current_piece = [[0] * WIDTH for _ in range(HEIGHT)]

    for y, row in enumerate(next_piece):

        for x, cell in enumerate(row):

            if cell != 0:

                current_piece[y + piece_y][x + piece_x] = cell

 

    # 绘制

    draw_board()

    draw_piece()

    pygame.display.flip()

 

    # 控制下落速度

    clock.tick(FPS)

 

# 结束游戏

pygame.quit()

print(f"Game Over! Your score: {score}")

  • 知识点总结:

一、关键类与功能

Brick类:表示游戏中的砖块,包括其位置、颜色以及图像。

Block(或Shape)类:表示游戏中的方块,包括其布局、方向、位置、砖块列表等。方块有7种基本形状:S、Z、T、L、反向L、直线、方块,每个形状都由4个砖块组成。

游戏区域与地图:使用二维数组表示游戏区域,其中0表示无砖块,1表示有砖块。定义游戏区域的宽度、高度以及方块的初始位置。

二、技术实现

使用pygame库:pygame是一个用于创建视频游戏的Python库,它提供了图形和声音库,使开发者能够轻松地创建游戏。

初始化pygame:在使用pygame库时,需要先进行初始化,保证pygame的代码块可以正常运行。

设置屏幕与刷新频率:使用pygame.display.set_mode()设置游戏窗口的大小和标题,使用pygame.time.Clock()创建时钟对象以控制游戏循环的频率。

绘制图形与文本:使用pygame的绘图函数绘制游戏区域、砖块、边框以及文本信息。

游戏循环:主游戏循环不断生成新方块,并更新和绘制游戏界面,直到游戏结束。


http://www.mrgr.cn/news/60826.html

相关文章:

  • Linux---硬盘管理
  • PH47代码框架功能速查
  • Python3+Requests+Excel完整接口自动化测试框架的实现
  • 云服务器数据删除了能恢复吗?
  • 什么是大数据?一文讲清大数据的概念、演进、趋势、产业链及关键技术!
  • GPT打数模——电商品类货量预测及品类分仓规划
  • 什么是JVM
  • Vue3中props的使用方法以及例子
  • OpenCV图像处理方法:腐蚀操作
  • flutter实战短视频课程
  • docker 相关操作命令
  • 前端项目代码风格及校验统一格式化配置
  • 代码随想录算法训练营第十三天|二叉树的递归遍历、 二叉树的迭代遍历、二叉树的层次遍历
  • 常见学习陷阱及解决方案
  • 认识线程 — JavaEE
  • 论文精读:Approximating Maximin Share Allocations(上)
  • java中的二叉树
  • MinIO服务部署指南
  • < 背包问题 >
  • 多源BFS问题(1)_01矩阵
  • Tangible Software Solutions 出品最准确可靠的源代码转换器
  • 大数据新视界 -- 大数据大厂之大数据重塑影视娱乐产业的未来(4 - 2)
  • DispatchingController
  • Java Lock ConditionObject 总结
  • 优先算法——复写零(双指针)
  • BFS解决最短路问题(4)_为高尔夫比赛砍树