python俄罗斯方块思路_python实现俄罗斯方块小游戏
回顾我们的python制作小游戏之路,几篇非常精彩的文章
我们用python实现了坦克大战
我们用python实现了飞船大战
我们用python实现了两种不同的贪吃蛇游戏
150行代码实现贪吃蛇游戏
我们用python实现了扫雷游戏
我们用python实现了五子棋游戏
今天我们用python来实现小时候玩过的俄罗斯方块游戏吧
具体代码与文件可以访问我的GitHub地址获取
第一步——构建各种方块
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]
第二部——构建主函数
import sys
import time
import pygame
from pygame.locals import *
import blocks
SIZE = 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) # 黑体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 # 下一个方块
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
_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_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)
# 画当前下落方块
_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俄罗斯方块思路_python实现俄罗斯方块小游戏相关推荐
- python玩扫雷_python实现扫雷小游戏
前面我们用python实现了贪吃蛇.坦克大战.飞船大战.五子棋等游戏 今天我们用python来实现一下扫雷游戏 本游戏代码量和源文件较多 可以从我的GitHub地址中获取 构建地雷区import ra ...
- python双手打字_Python打字练习小游戏源代码
Python打字练习小游戏源代码 Python代码狂人 Python代码大全 Python打字练习小游戏源程序,随机产生一串字符,可对打字练习的正确率和时间进行统计,运行截图如下: from tkin ...
- python五子棋代码_python实现五子棋小游戏
本文实例为大家分享了python实现五子棋小游戏的具体代码,供大家参考,具体内容如下 暑假学了十几天python,然后用pygame模块写了一个五子棋的小游戏,代码跟有缘人分享一下. import n ...
- python象棋编程_Python开发象棋小游戏(绘制棋盘)
上一篇中,我们缕清了思路,知道了如何写,怎么做,从哪入手,这一篇,我们就正式开始敲代码了,编程使我快乐,对吧,emm~~~ 还记得这张图吧: 编程完成 好了,向着目标,进发了... 程序中牵扯到的函数 ...
- 利用python制作拼图_python制作拼图小游戏
开发工具 Python版本:3.6.4 相关模块: pygame模块: 以及一些Python自带的模块 环境搭建 安装Python并添加到环境变量,pip安装需要的相关模块即可. 原理介绍 游戏简介: ...
- python文字游戏源代码_python 像素小鸟小游戏源码(flappybird)
[实例简介] 像素小鸟这个简单的游戏于2014年在网络上爆红,游戏上线一段时间内appleStore上的下载量一度达到5000万次,风靡一时 [实例截图] [核心代码] from Class impo ...
- python逻辑运算的一些流程图_Python猜数小游戏
使用random变量随机生成一个1到100之间的数 采集用户所输入的数字,如果输入的不符合要求会让用户重新输入. 输入符合要求,游戏开始.如果数字大于随机数,输出数字太大:如果小于随机数,输出数字太小 ...
- Py之tkinter:python最简单的猜字小游戏带你进入python的GUI世界
Py之tkinter:python最简单的猜字小游戏带你进入python的GUI世界 目录 输出结果 设计思路 输出结果 设计思路 from tkinter import * import tkint ...
- Python快速实现简易飞机大战小游戏
参考:用python实现简单的飞机大战小游戏_化华桦的博客-CSDN博客_python飞机大战 敌机图片: 我方飞机: 子弹: 背景图: 主函数代码main.py: from PySide2 impo ...
- python井字棋_用Python做一个井字棋小游戏
井字棋是一个经典的小游戏,在九宫格上玩家轮流画OXO,当每列或每行或是两个对角成一线时便是获胜. 今天就用Python编写一个井字棋小游戏,与电脑对战. 程序执行画面如下图所示: 程序提供了两种人工智 ...
最新文章
- 初步了解超图桌面版导入CityGML数据
- 2019 年 Vue 学习路线图
- 【C语言】switch…case无break情况(2)
- Java 7功能概述
- 如何给影像添加投影_如何在EasyEarth Desktop(CS客户端)进行影像处理
- J.U.C并发框架源码阅读(十七)ReentrantReadWriteLock
- 内核编程的主要调用源
- MATLAB 2016a 安装包以及安装破解教程
- 【软件分析/静态程序分析学习笔记】5.数据流分析基础(Data Flow Analysis-Foundations)
- 小飞鱼通达二开 致远OA启动时报错“无法初始化数据库连接池,系统无法启动”的问题处理(图文)
- Windows 11 22H2 (KB5017321) 更新失败并显示下载错误 0x800F0806
- 02-SA8155P ADB数据传输
- 安装virtualbox快完成时立即回滚,并提示安装出现严重错误
- 自定义viewGroup防淘宝商品详情页
- 学校BBS上C版总结的月经贴,感觉很不错
- RS485中继器电路(转)
- 从宴请潜规则看中国官场的酒桌文化
- 基于51单片机的数字温度计ds18b20温度测量报警仿真(仿真+源码+全套资料)
- html5 video播放调研,全屏,伪全屏
- 无人驾驶汽车系统入门(十二)——卷积神经网络入门,基于深度学习的车辆实时检测
热门文章
- mapgis考试11
- 一条sql执行很慢,可能是因为什么? 怎么优化?
- 怎么设置html禁止直接打开,如何禁止网页自动跳转
- 基于STM32单片机的FM调频TEA5767功放收音机方案原理图设计
- ArcGIS导入excel文件
- java冻结行列,Java 冻结或解除冻结Excel中的行和列的方法
- 拉钩网招聘信息爬虫项目
- Cyclone FPGA踏足笔记(一):开发环境建立与使用
- icloud连接服务器时出现问题_苹果iCloud连接超时/验证失败解决方法
- 【游戏开发实战】(完结)使用Unity制作水果消消乐游戏教程(九):使用UGUI显示游戏UI