Pygame经典游戏:俄罗斯方块

------------★Pygame系列教程★------------

Pygame经典游戏:贪吃蛇

Pygame教程01:初识pygame游戏模块

Pygame教程02:图片的加载+缩放+旋转+显示操作

Pygame教程03:文本显示+字体加载+transform方法

Pygame教程04:draw方法绘制矩形、多边形、圆、椭圆、弧线、直线和线条等

Pygame教程05:帧动画原理+边界值检测,让小球来回上下运动

Pygame教程06:Event事件的类型+处理方法+监听鼠标事件

Pygame教程07:键盘常量+键盘事件的2种捕捉方式

Pygame教程08:使用键盘方向键,控制小球,上下左右移动。

Pygame教程09:font.render文本内容,如何自动换行显示

在这里插入图片描述
1.blocks模块

import random
from collections import namedtuple

Point = namedtuple('Point', 'X Y')
Shape = namedtuple('Shape', 'X Y Width Height')
Block = namedtuple('Block', 'template start_pos end_pos name next')

# 方块形状的设计,我最初我是做成 4 × 4,因为长宽最长都是4,这样旋转的时候就不考虑怎么转了,就是从一个图形替换成另一个
# 其实要实现这个功能,只需要固定左上角的坐标就可以了

# S形方块
S_BLOCK = [Block(['.OO',
                  'OO.',
                  '...'], Point(0, 0), Point(2, 1), 'S', 1),
           Block(['O..',
                  'OO.',
                  '.O.'], Point(0, 0), Point(1, 2), 'S', 0)]
# Z形方块
Z_BLOCK = [Block(['OO.',
                  '.OO',
                  '...'], Point(0, 0), Point(2, 1), 'Z', 1),
           Block(['.O.',
                  'OO.',
                  'O..'], Point(0, 0), Point(1, 2), 'Z', 0)]
# I型方块
I_BLOCK = [Block(['.O..',
                  '.O..',
                  '.O..',
                  '.O..'], Point(1, 0), Point(1, 3), 'I', 1),
           Block(['....',
                  '....',
                  'OOOO',
                  '....'], Point(0, 2), Point(3, 2), 'I', 0)]
# O型方块
O_BLOCK = [Block(['OO',
                  'OO'], Point(0, 0), Point(1, 1), 'O', 0)]
# J型方块
J_BLOCK = [Block(['O..',
                  'OOO',
                  '...'], Point(0, 0), Point(2, 1), 'J', 1),
           Block(['.OO',
                  '.O.',
                  '.O.'], Point(1, 0), Point(2, 2), 'J', 2),
           Block(['...',
                  'OOO',
                  '..O'], Point(0, 1), Point(2, 2), 'J', 3),
           Block(['.O.',
                  '.O.',
                  'OO.'], Point(0, 0), Point(1, 2), 'J', 0)]
# L型方块
L_BLOCK = [Block(['..O',
                  'OOO',
                  '...'], Point(0, 0), Point(2, 1), 'L', 1),
           Block(['.O.',
                  '.O.',
                  '.OO'], Point(1, 0), Point(2, 2), 'L', 2),
           Block(['...',
                  'OOO',
                  'O..'], Point(0, 1), Point(2, 2), 'L', 3),
           Block(['OO.',
                  '.O.',
                  '.O.'], Point(0, 0), Point(1, 2), 'L', 0)]
# T型方块
T_BLOCK = [Block(['.O.',
                  'OOO',
                  '...'], Point(0, 0), Point(2, 1), 'T', 1),
           Block(['.O.',
                  '.OO',
                  '.O.'], Point(1, 0), Point(2, 2), 'T', 2),
           Block(['...',
                  'OOO',
                  '.O.'], Point(0, 1), Point(2, 2), 'T', 3),
           Block(['.O.',
                  'OO.',
                  '.O.'], Point(0, 0), Point(1, 2), 'T', 0)]

BLOCKS = {'O': O_BLOCK,
          'I': I_BLOCK,
          'Z': Z_BLOCK,
          'T': T_BLOCK,
          'L': L_BLOCK,
          'S': S_BLOCK,
          'J': J_BLOCK}


def get_block():
    block_name = random.choice('OIZTLSJ')
    b = BLOCKS[block_name]
    idx = random.randint(0, len(b) - 1)
    return b[idx]


def get_next_block(block):
    b = BLOCKS[block.name]
    return b[block.next]

2.主函数源码

# -*- coding: utf-8 -*-
# @Author : 小红牛
# 微信公众号:WdPython
import sys
import time
import pygame
from pygame.locals import *
import blocks

SIZE = 30  # 每个小方格大小
BLOCK_HEIGHT = 20  # 游戏区高度
BLOCK_WIDTH = 10   # 游戏区宽度
BORDER_WIDTH = 4   # 游戏区边框宽度
BORDER_COLOR = (40, 40, 200)  # 游戏区边框颜色
SCREEN_WIDTH = SIZE * (BLOCK_WIDTH + 5)  # 游戏屏幕的宽
SCREEN_HEIGHT = SIZE * BLOCK_HEIGHT      # 游戏屏幕的高
BG_COLOR = (40, 40, 60)  # 背景色
BLACK = (0, 0, 0)
RED = (200, 30, 30)      # GAME OVER 的字体颜色


def print_text(screen, font, x, y, text, fcolor=(255, 255, 255)):
    imgText = font.render(text, True, fcolor)
    screen.blit(imgText, (x, y))


def main():
    pygame.init()
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    pygame.display.set_caption('俄罗斯方块')

    font1 = pygame.font.SysFont('SimHei', 24)  # 黑体24
    font2 = pygame.font.Font(None, 72)  # GAME OVER 的字体
    font_pos_x = BLOCK_WIDTH * SIZE + BORDER_WIDTH + 10  # 右侧信息显示区域字体位置的X坐标
    gameover_size = font2.size('GAME OVER')
    font1_height = int(font1.size('得分')[1])

    cur_block = None   # 当前下落方块
    next_block = None  # 下一个方块
    block_color = (20, 128, 200)  #
    cur_pos_x, cur_pos_y = 0, 0

    game_area = None    # 整个游戏区域
    game_over = True
    start = False       # 是否开始,当start = True,game_over = True 时,才显示 GAME OVER
    score = 0           # 得分
    orispeed = 0.5      # 原始速度
    speed = orispeed    # 当前速度
    pause = False       # 暂停
    last_drop_time = None   # 上次下落时间
    last_press_time = None  # 上次按键时间

    def _dock():
        nonlocal cur_block, next_block, game_area, cur_pos_x, cur_pos_y, game_over, score, speed
        for _i in range(cur_block.start_pos.Y, cur_block.end_pos.Y + 1):
            for _j in range(cur_block.start_pos.X, cur_block.end_pos.X + 1):
                if cur_block.template[_i][_j] != '.':
                    game_area[cur_pos_y + _i][cur_pos_x + _j] = '0'
        if cur_pos_y + cur_block.start_pos.Y <= 0:
            game_over = True
        else:
            # 计算消除
            remove_idxs = []
            for _i in range(cur_block.start_pos.Y, cur_block.end_pos.Y + 1):
                if all(_x == '0' for _x in game_area[cur_pos_y + _i]):
                    remove_idxs.append(cur_pos_y + _i)
            if remove_idxs:
                # 计算得分
                remove_count = len(remove_idxs)
                if remove_count == 1:
                    score += 100
                elif remove_count == 2:
                    score += 300
                elif remove_count == 3:
                    score += 700
                elif remove_count == 4:
                    score += 1500
                speed = orispeed - 0.03 * (score // 10000)
                # 消除
                _i = _j = remove_idxs[-1]
                while _i >= 0:
                    while _j in remove_idxs:
                        _j -= 1
                    if _j < 0:
                        game_area[_i] = ['.'] * BLOCK_WIDTH
                    else:
                        game_area[_i] = game_area[_j]
                    _i -= 1
                    _j -= 1
            cur_block = next_block
            next_block = blocks.get_block()
            cur_pos_x, cur_pos_y = (BLOCK_WIDTH - cur_block.end_pos.X - 1) // 2, -1 - cur_block.end_pos.Y

    def _judge(pos_x, pos_y, block):
        nonlocal game_area
        for _i in range(block.start_pos.Y, block.end_pos.Y + 1):
            if pos_y + block.end_pos.Y >= BLOCK_HEIGHT:
                return False
            for _j in range(block.start_pos.X, block.end_pos.X + 1):
                if pos_y + _i >= 0 and block.template[_i][_j] != '.' and game_area[pos_y + _i][pos_x + _j] != '.':
                    return False
        return True

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                sys.exit()
            elif event.type == KEYDOWN:
                if event.key == K_RETURN:
                    if game_over:
                        start = True
                        game_over = False
                        score = 0
                        last_drop_time = time.time()
                        last_press_time = time.time()
                        game_area = [['.'] * BLOCK_WIDTH for _ in range(BLOCK_HEIGHT)]
                        cur_block = blocks.get_block()
                        next_block = blocks.get_block()
                        cur_pos_x, cur_pos_y = (BLOCK_WIDTH - cur_block.end_pos.X - 1) // 2, -1 - cur_block.end_pos.Y
                elif event.key == K_SPACE:
                    if not game_over:
                        pause = not pause
                elif event.key in (K_w, K_UP):
                    # 旋转
                    # 其实记得不是很清楚了,比如
                    # .0.
                    # .00
                    # ..0
                    # 这个在最右边靠边的情况下是否可以旋转,我试完了网上的俄罗斯方块,是不能旋转的,这里我们就按不能旋转来做
                    # 我们在形状设计的时候做了很多的空白,这样只需要规定整个形状包括空白部分全部在游戏区域内时才可以旋转
                    if 0 <= cur_pos_x <= BLOCK_WIDTH - len(cur_block.template[0]):
                        _next_block = blocks.get_next_block(cur_block)
                        if _judge(cur_pos_x, cur_pos_y, _next_block):
                            cur_block = _next_block

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                if not game_over and not pause:
                    if time.time() - last_press_time > 0.1:
                        last_press_time = time.time()
                        if cur_pos_x > - cur_block.start_pos.X:
                            if _judge(cur_pos_x - 1, cur_pos_y, cur_block):
                                cur_pos_x -= 1
            if event.key == pygame.K_RIGHT:
                if not game_over and not pause:
                    if time.time() - last_press_time > 0.1:
                        last_press_time = time.time()
                        # 不能移除右边框
                        if cur_pos_x + cur_block.end_pos.X + 1 < BLOCK_WIDTH:
                            if _judge(cur_pos_x + 1, cur_pos_y, cur_block):
                                cur_pos_x += 1
            if event.key == pygame.K_DOWN:
                if not game_over and not pause:
                    if time.time() - last_press_time > 0.1:
                        last_press_time = time.time()
                        if not _judge(cur_pos_x, cur_pos_y + 1, cur_block):
                            _dock()
                        else:
                            last_drop_time = time.time()
                            cur_pos_y += 1

        # 填充背景色
        screen.fill(BG_COLOR)
        # 画游戏区域分隔线
        pygame.draw.line(screen, BORDER_COLOR,
                         (SIZE * BLOCK_WIDTH + BORDER_WIDTH // 2, 0),
                         (SIZE * BLOCK_WIDTH + BORDER_WIDTH // 2, SCREEN_HEIGHT), BORDER_WIDTH)

        # 画现有方块
        if game_area:
            for i, row in enumerate(game_area):
                for j, cell in enumerate(row):
                    if cell != '.':
                        pygame.draw.rect(screen, block_color, (j * SIZE, i * SIZE, SIZE, SIZE), 0)

        # 画网格线 竖线
        for x in range(BLOCK_WIDTH):
            pygame.draw.line(screen, BLACK, (x * SIZE, 0), (x * SIZE, SCREEN_HEIGHT), 1)
        # 画网格线 横线
        for y in range(BLOCK_HEIGHT):
            pygame.draw.line(screen, BLACK, (0, y * SIZE), (BLOCK_WIDTH * SIZE, y * SIZE), 1)

        if not game_over:
            cur_drop_time = time.time()
            if cur_drop_time - last_drop_time > speed:
                if not pause:
                    # 不应该在下落的时候来判断到底没,我们玩俄罗斯方块的时候,方块落到底的瞬间是可以进行左右移动
                    if not _judge(cur_pos_x, cur_pos_y + 1, cur_block):
                        _dock()
                    else:
                        last_drop_time = cur_drop_time
                        cur_pos_y += 1
        else:
            if start:
                print_text(screen, font2,
                           (SCREEN_WIDTH - gameover_size[0]) // 2, (SCREEN_HEIGHT - gameover_size[1]) // 2,
                           'GAME OVER', RED)

        # 画当前下落方块
        if cur_block:
            for i in range(cur_block.start_pos.Y, cur_block.end_pos.Y + 1):
                for j in range(cur_block.start_pos.X, cur_block.end_pos.X + 1):
                    if cur_block.template[i][j] != '.':
                        pygame.draw.rect(screen, block_color,
                                         ((cur_pos_x + j) * SIZE, (cur_pos_y + i) * SIZE, SIZE, SIZE), 0)

        print_text(screen, font1, font_pos_x, 10, f'得分: ')
        print_text(screen, font1, font_pos_x, 10 + font1_height + 6, f'{score}')
        print_text(screen, font1, font_pos_x, 20 + (font1_height + 6) * 2, f'速度: ')
        print_text(screen, font1, font_pos_x, 20 + (font1_height + 6) * 3, f'{score // 10000}')
        print_text(screen, font1, font_pos_x, 30 + (font1_height + 6) * 4, f'下一个:')

        if next_block:
            _h = 30 + (font1_height + 6) * 5
            for i in range(next_block.start_pos.Y, next_block.end_pos.Y + 1):
                for j in range(next_block.start_pos.X, next_block.end_pos.X + 1):
                    if next_block.template[i][j] != '.':
                        pygame.draw.rect(screen, block_color, (font_pos_x + j * SIZE, _h + i * SIZE, SIZE, SIZE), 0)

        pygame.display.flip()


if __name__ == '__main__':
    main()

完毕!!感谢您的收看

----------★★历史博文集合★★----------

我的零基础Python教程,Python入门篇 进阶篇 视频教程 Py安装py项目 Python模块 Python爬虫 Json Xpath 正则表达式 Selenium Etree CssGui程序开发 Tkinter Pyqt5 列表元组字典数据可视化 matplotlib 词云图 Pyecharts 海龟画图 Pandas Bug处理 电脑小知识office自动化办公 编程工具 NumPy Pygame

相关推荐

  1. 基于Python的pygame库的俄罗斯方块游戏

    2024-04-13 19:22:01       21 阅读
  2. 俄罗斯方块【python,小游戏

    2024-04-13 19:22:01       10 阅读
  3. python实现俄罗斯方块游戏

    2024-04-13 19:22:01       40 阅读
  4. 俄罗斯方块游戏开发思路随想

    2024-04-13 19:22:01       21 阅读
  5. 使用VHDL实现俄罗斯方块游戏设计

    2024-04-13 19:22:01       19 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-13 19:22:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-13 19:22:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-13 19:22:01       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-13 19:22:01       20 阅读

热门阅读

  1. Lambda表达式

    2024-04-13 19:22:01       17 阅读
  2. MySQL优化常见面试题

    2024-04-13 19:22:01       12 阅读
  3. 深入理解负载均衡:原理及常用算法

    2024-04-13 19:22:01       17 阅读
  4. 富格林:摸清受害亏损陷阱安全预防

    2024-04-13 19:22:01       18 阅读
  5. DRBD双主模式自动化安装部署脚本

    2024-04-13 19:22:01       14 阅读
  6. Unity面经(自整)——C#基础

    2024-04-13 19:22:01       18 阅读
  7. C#多线程

    2024-04-13 19:22:01       12 阅读
  8. C# WinForm —— 06 常用控件

    2024-04-13 19:22:01       13 阅读
  9. symfony框架

    2024-04-13 19:22:01       13 阅读
  10. Docker之数据卷和Dockerfile

    2024-04-13 19:22:01       17 阅读
  11. C#实现HTTP上传文件的方法

    2024-04-13 19:22:01       19 阅读
  12. jieba分词的应用

    2024-04-13 19:22:01       18 阅读
  13. 04-springmvc-RequestContextHolder

    2024-04-13 19:22:01       19 阅读