python实现俄罗斯方块


Posted in Python onJune 26, 2018

网上搜到一个Pygame写的俄罗斯方块(tetris),大部分看懂的前提下增加了注释,Fedora19下运行OK的

主程序:

#coding:utf8
#! /usr/bin/env python
# 注释说明:shape表示一个俄罗斯方块形状 cell表示一个小方块
import sys
from random import choice
import pygame
from pygame.locals import *
from block import O, I, S, Z, L, J, T

COLS = 16
ROWS = 20
CELLS = COLS * ROWS
CELLPX = 32 # 每个cell的像素宽度
POS_FIRST_APPEAR = COLS / 2
SCREEN_SIZE = (COLS * CELLPX, ROWS * CELLPX)
COLOR_BG = (0, 0, 0)


def draw(grid, pos=None):
 # grid是一个list,要么值为None,要么值为'Block'
 # 非空值在eval()的作用下,用于配置颜色
 if pos: # 6x5
  s = pos - 3 - 2 * COLS # upper left position
  for p in range(0, COLS):
   q = s + p * COLS
   for i in range(q, q + 6):
    if 0 <= i < CELLS:
     # 0 <=i < CELLS:表示i这个cell在board内部。
     c = eval(grid[i] + ".color") if grid[i] else COLOR_BG
     # 执行着色。shape的cell涂对应的class设定好的颜色,否则涂黑(背景色)
     a = i % COLS * CELLPX
     b = i / COLS * CELLPX
     screen.fill(c, (a, b, CELLPX, CELLPX))
 else: # all
  screen.fill(COLOR_BG)
  for i, occupied in enumerate(grid):
   if occupied:
    c = eval(grid[i] + ".color") # 获取方块对应的颜色
    a = i % COLS * CELLPX # 横向长度
    b = i / COLS * CELLPX # 纵向长度
    screen.fill(c, (a, b, CELLPX, CELLPX))
    # fill:为cell上色, 第二个参数表示rect
 pygame.display.flip()
 # 刷新屏幕


def phi(grid1, grid2, pos): # 4x4
# 两个grid之4*4区域内是否会相撞(冲突)
 s = pos - 2 - 1 * COLS # upper left position
 for p in range(0, 4):
  q = s + p * COLS
  for i in range(q, q + 4):
   try:
    if grid1[i] and grid2[i]:
     return False
   except:
    pass
 return True


def merge(grid1, grid2):
 # 合并两个grid
 grid = grid1[:]
 for i, c in enumerate(grid2):
  if c:
   grid[i] = c
 return grid


def complete(grid):
 # 减去满行
 n = 0
 for i in range(0, CELLS, COLS):
  # 步长为一行。
  if not None in grid[i:i + COLS]:
  #这一句很容易理解错误。
  #实际含义是:如果grid[i:i + COLS]都不是None,那么执行下面的语句
   grid = [None] * COLS + grid[:i] + grid[i + COLS:]
   n += 1
 return grid, n
#n表示减去的行数,用作统计分数

pygame.init()
pygame.event.set_blocked(None)
pygame.event.set_allowed((KEYDOWN, QUIT))
pygame.key.set_repeat(75, 0)
pygame.display.set_caption('Tetris')
screen = pygame.display.set_mode(SCREEN_SIZE)
pygame.display.update()

grid = [None] * CELLS
speed = 500
screen.fill(COLOR_BG)
while True: # spawn a block
 block = choice([O, I, S, Z, L, J, T])()
 pos = POS_FIRST_APPEAR
 if not phi(grid, block.grid(pos), pos): break # you lose
 pygame.time.set_timer(KEYDOWN, speed)
 # repeatedly create an event on the event queue
 # speed是时间间隔。。。speed越小,方块下落的速度越快。。。speed应该换为其他名字

 while True: # move the block
  draw(merge(grid, block.grid(pos)), pos)
  event = pygame.event.wait()
  if event.type == QUIT: sys.exit()
  try:
   aim = {
    K_UNKNOWN: pos+COLS,
    K_UP: pos,
    K_DOWN: pos+COLS,
    K_LEFT: pos-1,
    K_RIGHT: pos+1,
   }[event.key]
  except KeyError:
   continue
  if event.key == K_UP:
   # 变形
   block.rotate()

  elif event.key in (K_LEFT, K_RIGHT) and pos / COLS != aim / COLS:
   # pos/COLS表示当前位置所在行
   # aim/COLS表示目标位置所在行
   # 此判断表示,当shape在左边界时,不允许再向左移动(越界。。),在最右边时向右也禁止
   continue

  grid_aim = block.grid(aim)
  if grid_aim and phi(grid, grid_aim, aim):
   pos = aim
  else:
   if event.key == K_UP:
    block.rotate(times=3)
   elif not event.key in (K_LEFT, K_RIGHT):
    break

 grid = merge(grid, block.grid(pos))
 grid, n = complete(grid)
 if n:
  draw(grid)
  speed -= 5 * n
  if speed < 75: speed = 75

调用的模块:

#coding:utf-8
#! /usr/bin/env python
COLS = 16
ROWS = 20

class Block():
 color = (255,255,255)
 def __init__(self):
  self._state = 0
 def __str__(self):
  return self.__class__.__name__
 def _orientations(self):
  raise NotImplementedError()
 def rotate(self, times=1):
  for i in range(times):
   if len(self._orientations())-1 == self._state:
    self._state = 0
    #只要_state比_orientations长度-1还要小,就让_state加1

   else:
    self._state += 1
 def blades(self):
  # 返回对应形状的一种旋转形状。(返回一个list,list中每个元素是一个(x,y))
  return self._orientations()[self._state]

 def grid(self, pos, cols=COLS, rows=ROWS):
  # grid()函数:对于一个形状,从它的cell中的pos位置,按照orientations的位置提示,把所有cell涂色
  # pos表示的是shape中的一个cell,也就是(0,0)
  if cols*rows <= pos:
   return None
  # 这种情况应该不可能出现吧。如果出现<=的情况
  # 那么,pos都跑到界外了。。

  grid = [None] * cols * rows
  grid[pos] = str(self)
  for b in self.blades():
   x, y = b
   # pos/cols表示pos处于board的第几行
   if pos/cols != (pos+x)/cols:
    return None
   i = pos + x + y * cols
   if i < 0:
    continue
   elif cols*rows <= i:
    return None
   grid[i] = str(self)
   # 给相应的其他位置都“涂色”,比如对于方块,是O型的,那么pos肯定是有值的,pos位于有上角。。
  return grid

# 以下每个形状class,_orientations()都返回形状的列表。(0,0)一定被包含在其中,为了省略空间所以都没有写出.
class O(Block):
 color = (207,247,0)
 def _orientations(self):
  return (
   [(-1,0), (-1,1), (0,1)],
   )
class I(Block):
 color = (135,240,60)
 def _orientations(self):
  return (
   [(-2,0), (-1,0), (1,0)],
   [(0,-1), (0,1), (0,2)],
   )
class S(Block):
 color = (171,252,113)
 def _orientations(self):
  return (
   [(1,0), (-1,1), (0,1)],
   [(0,-1), (1,0), (1,1)],
   )
class Z(Block):
 color = (243,61,110)
 def _orientations(self):
  return (
   [(-1,0), (0,1), (1,1)],
   [(1,-1), (1,0), (0,1)],
   )
class L(Block):
 color = (253,205,217)
 def _orientations(self):
  return (
   [(-1,1), (-1,0), (1,0)],
   [(0,-1), (0,1), (1,1)],
   [(-1,0), (1,0), (1,-1)],
   [(-1,-1), (0,-1), (0,1)],
   )
class J(Block):
 color = (140,180,225)
 def _orientations(self):
  return (
   [(-1,0), (1,0), (1,1)],
   [(0,1), (0,-1), (1,-1)],
   [(-1,-1), (-1,0), (1,0)],
   [(-1,1), (0,1), (0,-1)],
   )
class T(Block):
 color = (229,251,113)
 def _orientations(self):
  return (
   [(-1,0), (0,1), (1,0)],
   [(0,-1), (0,1), (1,0)],
   [(-1,0), (0,-1), (1,0)],
   [(-1,0), (0,-1), (0,1)],
   )

更多俄罗斯方块精彩文章请点击专题:俄罗斯方块游戏集合 进行学习。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python中使用logging模块打印log日志详解
Apr 05 Python
Python fileinput模块使用实例
Jun 03 Python
一步步教你用Python实现2048小游戏
Jan 19 Python
Django项目中用JS实现加载子页面并传值的方法
May 28 Python
利用Python校准本地时间的方法教程
Oct 31 Python
django使用F方法更新一个对象多个对象字段的实现
Mar 28 Python
实例代码讲解Python 线程池
Aug 24 Python
Python classmethod装饰器原理及用法解析
Oct 17 Python
详解Selenium-webdriver绕开反爬虫机制的4种方法
Oct 28 Python
Django执行源生mysql语句实现过程解析
Nov 12 Python
Autopep8的使用(python自动编排工具)
Mar 02 Python
实例详解Python的进程,线程和协程
Mar 13 Python
解决python报错MemoryError的问题
Jun 26 #Python
pygame实现俄罗斯方块游戏
Jun 26 #Python
python和pygame实现简单俄罗斯方块游戏
Feb 19 #Python
解决python读取几千万行的大表内存问题
Jun 26 #Python
详解Python3的TFTP文件传输
Jun 26 #Python
python3爬取数据至mysql的方法
Jun 26 #Python
python清除函数占用的内存方法
Jun 25 #Python
You might like
?生?D片??C字串
2006/12/06 PHP
php一些错误处理的方法与技巧总结
2013/08/10 PHP
php以post形式发送xml的方法
2014/11/04 PHP
PHP+JS实现的实时搜索提示功能
2018/03/13 PHP
Javascript 构造函数 实例分析
2008/11/26 Javascript
在js中单选框和复选框获取值的方式
2009/11/06 Javascript
jquery与google map api结合使用 控件,监听器
2010/03/04 Javascript
utf-8编码引起js输出中文乱码的解决办法
2010/06/23 Javascript
JQuery中serialize()、serializeArray()和param()方法示例介绍
2014/07/31 Javascript
详解JS函数重载
2014/12/04 Javascript
JavaScript中对象介绍
2014/12/31 Javascript
JavaScript中的pow()方法使用详解
2015/06/15 Javascript
JS实现黑色大气的二级导航菜单效果
2015/09/18 Javascript
获取JavaScript异步函数的返回值
2016/12/21 Javascript
Vue请求JSON Server服务器数据的实现方法
2018/11/02 Javascript
详解微信小程序实现跑马灯效果(附完整代码)
2019/04/29 Javascript
JavaScript实现星级评价效果
2019/05/17 Javascript
layui 实现二级弹窗弹出之后 关闭一级弹窗的方法
2019/09/18 Javascript
Weex开发之地图篇的具体使用
2019/10/16 Javascript
使用BeautifulSoup爬虫程序获取百度搜索结果的标题和url示例
2014/01/19 Python
python插入数据到列表的方法
2015/04/30 Python
python类继承用法实例分析
2015/05/27 Python
Python使用三种方法实现PCA算法
2017/12/12 Python
Python爬虫之正则表达式的使用教程详解
2018/10/25 Python
Python常见数据结构之栈与队列用法示例
2019/01/14 Python
使用Python-OpenCV向图片添加噪声的实现(高斯噪声、椒盐噪声)
2019/05/28 Python
PyCharm中如何直接使用Anaconda已安装的库
2020/05/28 Python
Python基础教程(一)——Windows搭建开发Python开发环境
2020/07/20 Python
利用Python实现斐波那契数列的方法实例
2020/07/26 Python
python/golang实现循环链表的示例代码
2020/09/14 Python
html5读取本地文件示例代码
2014/04/22 HTML / CSS
关于Assembly命名空间的三个面试题
2015/07/23 面试题
了解AppleShare protocol(AppleShare协议)吗
2015/08/28 面试题
C#如何允许一个类被继承但是避免这个类的方法被重载?
2015/02/24 面试题
建筑安全员岗位职责
2014/03/13 职场文书
社区义诊活动总结
2014/04/30 职场文书