我喜欢直接上代码
# -*- coding:utf-8 -*-
import sys
import random, copy
import pygame as pg
from pygame.locals import *
'''
常量声明
'''
EMPTY_CELL = 0 # 空区标识,表示没有方块
FALLING_BLOCK = 1 # 下落中的方块标识,也就是活动方块。
STATIC_BLOCK = 2 # 固实方块标识
'''
全局变量声明
变量值以sysInit函数中初始化后的结果为准
'''
defaultFont = None # 默认字体
screen = None # 屏幕输出对象
backSurface = None # 图像输出缓冲画板
score = 0 # 玩家得分记录
clearLineScore = 0 # 玩家清除的方块行数
level = 1 # 关卡等级
clock = None # 游戏时钟
nowBlock = None # 当前下落中的方块
nextBlock = None # 下一个将出现的方块
fallSpeed = 10 # 当前方块下落速度
beginFallSpeed = fallSpeed # 游戏初始时方块下落速度
speedBuff = 0 # 下落速度缓冲变量
keyBuff = None # 上一次按键记录
maxBlockWidth = 10 # 舞台堆叠区X轴最大可容纳基础方块数
maxBlockHeight = 18 # 舞台堆叠区Y轴最大可容纳基础方块数
blockWidth = 30 # 以像素为单位的基础方块宽度
blockHeight = 30 # 以像素为单位的基础方块高度
blocks = [] # 方块形状矩阵四维列表。第一维为不同的方块形状,第二维为每个方块形状不同的方向(以0下标起始,一共四个方向),第三维为Y轴方块形状占用情况,第四维为X轴方块形状占用情况。矩阵中0表示没有方块,1表示有方块。
stage = [] # 舞台堆叠区矩阵二维列表,第一维为Y轴方块占用情况,第二维为X轴方块占用情况。矩阵中0表示没有方块,1表示有固实方块,2表示有活动方块。
gameOver = False # 游戏结束标志
pause = False # 游戏暂停标志
def printTxt(content, x, y, font, screen, color=(255, 255, 255)):
'''显示文本
args:
content:待显示文本内容
x,y:显示坐标
font:字体
screen:输出的screen
color:颜色
'''
imgTxt = font.render(content, True, color)
screen.blit(imgTxt, (x, y))
class point(object):
'''平面坐标点类
attributes:
x,y:坐标值
'''
def __init__(self, x, y):
self.__x = x
self.__y = y
def getx(self):
return self.__x
def setx(self, x):
self.__x = x
x = property(getx, setx)
def gety(self):
return self.__y
def sety(self, y):
self.__y = y
y = property(gety, sety)
def __str__(self):
return "{x:" + "{:.0f}".format(self.__x) + ",y:" + "{:.0f}".format(self.__y) + "}"
class blockSprite(object):
'''
方块形状精灵类
下落方块的定义全靠它了。
attributes:
shape:方块形状编号
direction:方块方向编号
xy,方块形状左上角方块坐标
block:方块形状矩阵
'''
def __init__(self, shape, direction, xy):
self.shape = shape
self.direction = direction
self.xy = xy
def chgDirection(self, direction):
'''
改变方块的方向
args:
direction:1为向右转,0为向左转。
'''
dirNumb = len(blocks[self.shape]) - 1
if direction == 1:
self.direction += 1
if self.direction > dirNumb:
self.direction = 0
else:
self.direction -= 1
if self.direction < 0:
self.direction = dirNumb
def clone(self):
'''
克隆本体
return:
返回自身的克隆
'''
return blockSprite(self.shape, self.direction, point(self.xy.x, self.xy.y))
def _getBlock(self):
return blocks[self.shape][self.direction]
block = property(_getBlock)
def getConf(fileName):
'''
从配置文件中读取方块形状数据
每个方块以4*4矩阵表示形状,配置文件每行代表一个方块,用