回顾我们的python制作小游戏之路
我们用python实现了坦克大战

python制作坦克大战

我们用python实现了飞船大战

python制作飞船大战

我们用python实现了两种不同的贪吃蛇游戏

200行python代码实现贪吃蛇游戏

150行代码实现贪吃蛇游戏

我们用python实现了扫雷游戏

python实现扫雷游戏

我们用python实现了五子棋游戏

python实现五子棋游戏

今天我们用python来实现小时候玩过的俄罗斯方块游戏吧
具体代码与文件可以访问我的GitHub地址获取
https://github.com/liuzuoping/python_Games

第一步——构建各种方块

import random
from collections import namedtuplePoint = 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]

第二部——构建主函数

import sys
import time
import pygame
from pygame.locals import *
import blocksSIZE = 30  # 每个小方格大小
BLOCK_HEIGHT = 25  # 游戏区高度
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)  # 背景色
BLOCK_COLOR = (20, 128, 200)  #
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)  # 黑体24font2 = 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  # 下一个方块cur_pos_x, cur_pos_y = 0, 0game_area = None    # 整个游戏区域game_over = Truestart = False       # 是否开始,当start = True,game_over = True 时,才显示 GAME OVERscore = 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, speedfor _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 = Trueelse:# 计算消除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 += 100elif remove_count == 2:score += 300elif remove_count == 3:score += 700elif remove_count == 4:score += 1500speed = orispeed - 0.03 * (score // 10000)# 消除_i = _j = remove_idxs[-1]while _i >= 0:while _j in remove_idxs:_j -= 1if _j < 0:game_area[_i] = ['.'] * BLOCK_WIDTHelse:game_area[_i] = game_area[_j]_i -= 1_j -= 1cur_block = next_blocknext_block = blocks.get_block()cur_pos_x, cur_pos_y = (BLOCK_WIDTH - cur_block.end_pos.X - 1) // 2, -1 - cur_block.end_pos.Ydef _judge(pos_x, pos_y, block):nonlocal game_areafor _i in range(block.start_pos.Y, block.end_pos.Y + 1):if pos_y + block.end_pos.Y >= BLOCK_HEIGHT:return Falsefor _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 Falsereturn Truewhile 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 = Truegame_over = Falsescore = 0last_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.Yelif event.key == K_SPACE:if not game_over:pause = not pauseelif 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_blockif 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 -= 1if 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 += 1if 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_draw_background(screen)_draw_game_area(screen, game_area)_draw_gridlines(screen)_draw_info(screen, font1, font_pos_x, font1_height, score)# 画显示信息中的下一个方块_draw_block(screen, next_block, font_pos_x, 30 + (font1_height + 6) * 5, 0, 0)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_timecur_pos_y += 1else:if start:print_text(screen, font2,(SCREEN_WIDTH - gameover_size[0]) // 2, (SCREEN_HEIGHT - gameover_size[1]) // 2,'GAME OVER', RED)# 画当前下落方块_draw_block(screen, cur_block, 0, 0, cur_pos_x, cur_pos_y)pygame.display.flip()# 画背景
def _draw_background(screen):# 填充背景色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)# 画网格线
def _draw_gridlines(screen):# 画网格线 竖线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)# 画已经落下的方块
def _draw_game_area(screen, game_area):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)# 画单个方块
def _draw_block(screen, block, offset_x, offset_y, pos_x, pos_y):if block:for i in range(block.start_pos.Y, block.end_pos.Y + 1):for j in range(block.start_pos.X, block.end_pos.X + 1):if block.template[i][j] != '.':pygame.draw.rect(screen, BLOCK_COLOR,(offset_x + (pos_x + j) * SIZE, offset_y + (pos_y + i) * SIZE, SIZE, SIZE), 0)# 画得分等信息
def _draw_info(screen, font, pos_x, font_height, score):print_text(screen, font, pos_x, 10, f'得分: ')print_text(screen, font, pos_x, 10 + font_height + 6, f'{score}')print_text(screen, font, pos_x, 20 + (font_height + 6) * 2, f'速度: ')print_text(screen, font, pos_x, 20 + (font_height + 6) * 3, f'{score // 10000}')print_text(screen, font, pos_x, 30 + (font_height + 6) * 4, f'下一个:')if __name__ == '__main__':main()

游戏截图

运行效果

python实现俄罗斯方块小游戏相关推荐

  1. Python编写俄罗斯方块小游戏

    俄罗斯方块是俄罗斯人发明的一款休闲类的小游戏,这款小游戏可以说是很多人童年的主打电子游戏了,本文我们使用 Python 来实现这款小游戏. 很多人学习python,不知道从何学起. 很多人学习pyth ...

  2. python tkinter火柴人_用Python实现童年小游戏俄罗斯方块!别说还挺好玩!

    原标题:用Python实现童年小游戏俄罗斯方块!别说还挺好玩! 前言 大三上学期的程序设计实训大作业,挑了其中一个我认为最简单的的<图书管理系统>来写.用python写是因为py有自带的G ...

  3. python界面小游戏贪吃蛇_用Python实现童年小游戏贪吃蛇

    贪吃蛇作为一款经典小游戏,早在 1976 年就面世了,我最早接触它还是在家长的诺基亚手机中. 尽管贪吃蛇的历史相对比较久远,但它却有着十分顽强的生命力,保持经久不衰,其中很重要的原因便是游戏厂家不断的 ...

  4. python 贪吃蛇 turtle_关于python:用Python实现童年小游戏贪吃蛇

    贪吃蛇作为一款经典小游戏,早在 1976 年就面世了,我最早接触它还是在家长的诺基亚手机中. 只管贪吃蛇的历史绝对比拟长远,但它却有着非常倔强的生命力,放弃经久不衰,其中很重要的起因便是游戏厂家一直的 ...

  5. python经典小游戏五子棋,适合python编程的小游戏

    python入门可以做的小游戏 1.Python入门拼图小游戏简单介绍:将图像分为m×n个矩形块,并将图像右下角的矩形块替换为空白块后,将这些矩形块随机摆放成原图像的形状. 2.Python入门推箱子 ...

  6. pyqt5制作俄罗斯方块小游戏-----源码解析

    一.前言 最近学习pyqt5中文教程时,最后一个例子制作了一个俄罗斯方块小游戏,由于解释的不是很清楚,所以源码有点看不懂,查找网上资料后,大概弄懂了源码的原理. 二.绘制主窗口 将主窗口居中,且设置了 ...

  7. c++ 小游戏_C/C++编程新手入门基础系列:俄罗斯方块小游戏制作源代码

    这篇文章主要为大家详细介绍了C语言实现俄罗斯方块小游戏,具有一定的参考价值,感兴趣的小伙伴们可以参考一下. 1.要先下载一个 graphics.h 的头文件来绘图. 2.初始化窗口:initgraph ...

  8. python手机版做小游戏代码大全-python简单小游戏代码 怎么用Python制作简单小游戏...

    1.Python猜拳小游戏代码: 2.import random #导入随机模块 3. 4.num = 1 5.yin_num = 0 6.shu_num = 0 7.while num <= ...

  9. python写游戏脚本-使用Python写一个小游戏

    引言 最近python语言大火,除了在科学计算领域python有用武之地之外,在游戏.后台等方面,python也大放异彩,本篇博文将按照正规的项目开发流程,手把手教大家写个python小游戏,来感受下 ...

最新文章

  1. 微信遇到特殊服务器,解决微信网页授权,出现errcode:40163,errmsg:codebeenused,看似微信访问了2次这个回调接口的问题...
  2. Beef加载MSF插件
  3. c语言选择题答案在哪查,C语言选择题及答案
  4. Windows Server 2008 使用PowerShell开启 ssh 和 sftp
  5. 阶段3 3.SpringMVC·_01.SpringMVC概述及入门案例_03.入门程序之需求分析
  6. 超快捷的源代码编辑器「Textastic」
  7. 男生女生,呸,男生女生呸铃声 男生女生,呸,男生女生呸手机...
  8. excel中按出生日期排序公式
  9. 网页提示404什么意思
  10. 项目中采用J2EE体系架构分析
  11. Win10任务栏图标消失留下空格问题
  12. nnUNet 训练 AMOS22数据集 Task216(抽丝剥茧指令+原理篇)
  13. 程序员如何留住健康?
  14. html block属性,css display block属性的意思、作用和效果
  15. C++循环结构——津津的储蓄计划
  16. 【数论】快速幂(欧拉幂)
  17. Premiere Pro CC2019 软件安装包+安装教程
  18. bing搜索抓取错误警报列表
  19. 重装系统后XAMPP启动APACHE报错解决方法
  20. 手把手教你免费流畅访问GitHub

热门文章

  1. rabbitmq direct reply-to 在springAMQP和python之间的使用
  2. 数据结构-单链表基本操作带图完整详解
  3. html visibility属性,CSS属性参考 | visibility
  4. 关于在js中使用trim函数的一些小技巧
  5. neon 指令 c语言,NEON初步使用
  6. pandas.core.series.Series
  7. 移动开发(IOS) – iOS系统架构
  8. 多线程分批次查询数据
  9. STM32 USB HID Mouse And Keyboard (guide)
  10. 前瞻: 下一代网络 量子互联网