pygame實(shí)現(xiàn)俄羅斯方塊游戲(AI篇1)
上次更新到pygame實(shí)現(xiàn)俄羅斯方塊游戲(基礎(chǔ)篇3)
現(xiàn)在繼續(xù)
一、定義玩家類
定義玩家類是為了便于進(jìn)行手動(dòng)和機(jī)器模式或各種不同機(jī)器人模式的混合使用,增加代碼擴(kuò)展性。
可以先定義一個(gè)玩家基類
class Player(object): auto_mode=False # 是否是自動(dòng)模式,自動(dòng)模式應(yīng)當(dāng)不響應(yīng)鍵盤操作 def __init__(self): pass def run(self): # 進(jìn)行操作 pass
手動(dòng)類和機(jī)器類繼承自Player類
class HumanPlayer(Player): def __init__(self): super(Player, self).__init__() class AIPlayer(Player): auto_mode=True def __init__(self): super(Player, self).__init__() def run(self): pass
下面然后游戲代碼中做下面三處修改

好了,現(xiàn)在玩家類添加完畢,由于HumanPlayer類的run執(zhí)行的是pass,原來的操作沒有受到影響,下面該去實(shí)現(xiàn)AIPlayer的run了
二、貪心計(jì)算
方塊有N種形態(tài),每種形態(tài)有若干種水平位置,假設(shè)AI只管方塊變形和移動(dòng)能落得最低位置,越低越好。
首先,我們要將當(dāng)前游戲界面的方塊情況告訴玩家,所以我們?cè)赑layer類的run函數(shù)增加一下panel參數(shù),將panel作為run的參數(shù)傳入。
AIPlayer的代碼大致改成下面這樣
class AIPlayer(Player): cal_block_id=-1 # 用于判斷是否方塊發(fā)生了變化 ctl_arr=[] # 存:1=變、2=左、3=右、4=下,這些數(shù) auto_mode=True def __init__(self): super(Player, self).__init__() def run(self, panel): if panel.block_id == self.cal_block_id: # block_id沒變,按原來計(jì)算好的操作規(guī)則進(jìn)行 if len(ctl_arr)>0: ctl = self.ctl_arr.pop(0) if ctl == 1: panel.change_block() if ctl == 2: panel.control_block(-1,0) if ctl == 3: panel.control_block(1,0) if ctl == 4: flag = panel.move_block() while flag==1: flag = panel.move_block() if flag == 9: game_state = 2 else: # block_id變了,計(jì)算新方塊的操作規(guī)則 self.cal_block_id = panel.block_id matrix = panel.get_rect_matrix() #matrix.print_matrix() # print for debug # # 添加計(jì)算操作的邏輯 # pass
這里為了方便計(jì)算將panel中rect_arr轉(zhuǎn)成matrix,一般建議matrix用numpy的,這邊的使用場景比較簡單,就不增加依賴包了,自己實(shí)現(xiàn)一個(gè)簡單的matrix
class Matrix(object): rows = 0 cols = 0 data = [] def __init__(self, rows, cols): self.rows = rows self.cols = cols self.data = [0 for i in range(rows*cols)] def set_val(self, x, y, val): self.data[y*self.cols+x] = val def get_val(self, x, y): return self.data[y*cols+x] def print_matrix(self): for i in range(self.rows): print self.data[self.cols*i:self.cols*(i+1)]
panel的get_rect_matrix是這么實(shí)現(xiàn)的
def get_rect_matrix(self): matrix = Matrix(ROW_COUNT, COL_COUNT) for rect_info in self.rect_arr: matrix.set_val(rect_info.x, rect_info.y, 1) return matrix
為獲取不同形態(tài)的值,Block類和子類的get_shape函數(shù)稍作修改,增加一個(gè)輸入
class TBlock(Block): # 四種形態(tài) shape_id=0 shape_num=4 def __init__(self, n=None): super(TBlock, self).__init__() if n is None: n=random.randint(0,3) self.shape_id=n self.rect_arr=self.get_shape() self.color=(255,0,0) def get_shape(self, sid=None): if sid is None: sid = self.shape_id if sid==0: return [(0,1),(1,1),(2,1),(1,2)] elif sid==1: return [(1,0),(1,1),(1,2),(0,1)] elif sid==2: return [(0,1),(1,1),(2,1),(1,0)] else: return [(1,0),(1,1),(1,2),(2,1)]
計(jì)算最優(yōu)操作的代碼如下,大致思路是落下的四個(gè)方塊的Y值加起來越大越好
def cal_best_arr(self, panel): matrix = panel.get_rect_matrix() #matrix.print_matrix() # print for debug cur_shape_id = panel.moving_block.shape_id shape_num = panel.moving_block.shape_num max_score = 0 best_arr = [] for i in range(shape_num): tmp_shape_id = cur_shape_id + i if tmp_shape_id >= shape_num: tmp_shape_id = tmp_shape_id % shape_num tmp_shape = panel.moving_block.get_shape(sid=tmp_shape_id) center_shape = [] for x,y in tmp_shape: center_shape.append((x+COL_COUNT/2-2,y-2)) minx = COL_COUNT maxx = 0 miny = ROW_COUNT maxy = -2 for x,y in center_shape: if x<minx: minx = x if x>maxx: maxx = x if y<miny: miny = y if y>maxy: maxy = y for xdiff in range(-minx,COL_COUNT-maxx): # 左右可以移動(dòng)的范圍 arr = [1 for _ in range(i)] if xdiff < 0: [arr.append(2) for _ in range(-xdiff)] if xdiff > 0: [arr.append(3) for _ in range(xdiff)] arr.append(4) for yindex in range(-miny, ROW_COUNT-maxy): # 往下檢測(cè)碰撞 if matrix.cross_block(center_shape, xdiff=xdiff, ydiff=yindex): break score = sum([y+yindex for x,y in center_shape]) #print i,xdiff,yindex,score if score > max_score: max_score = score best_arr = arr self.ctl_arr = best_arr

大概的AI效果有了,但是發(fā)現(xiàn)它還不會(huì)考慮造成空洞的影響,下面還要繼續(xù)優(yōu)化
三、空洞的懲罰
Matrix類加一個(gè)獲取空洞數(shù)的函數(shù),這里先簡單定義為上方有方塊為空洞
def get_hole_number(self): hole_num=0 for x in range(0,self.cols): for y in range(1,self.rows): if self.get_val(x,y) == 0 and self.get_val(x,y-1) == 1: # 上方有方塊的當(dāng)成空洞 #print x,y hole_num+=1 return hole_num
計(jì)算最佳操作的函數(shù)加入空洞的懲罰值修改如下
def cal_best_arr(self, panel): matrix = panel.get_rect_matrix() cur_shape_id = panel.moving_block.shape_id shape_num = panel.moving_block.shape_num max_score = -10000 best_arr = [] for i in range(shape_num): tmp_shape_id = cur_shape_id + i if tmp_shape_id >= shape_num: tmp_shape_id = tmp_shape_id % shape_num tmp_shape = panel.moving_block.get_shape(sid=tmp_shape_id) center_shape = [] for x,y in tmp_shape: center_shape.append((x+COL_COUNT/2-2,y-2)) minx = COL_COUNT maxx = 0 miny = ROW_COUNT maxy = -2 for x,y in center_shape: if x<minx: minx = x if x>maxx: maxx = x if y<miny: miny = y if y>maxy: maxy = y for xdiff in range(-minx,COL_COUNT-maxx): # 左右可以移動(dòng)的范圍 arr = [1 for _ in range(i)] if xdiff < 0: [arr.append(2) for _ in range(-xdiff)] if xdiff > 0: [arr.append(3) for _ in range(xdiff)] max_yindex = -miny for yindex in range(-miny, ROW_COUNT-maxy): # 往下檢測(cè)碰撞 if matrix.cross_block(center_shape, xdiff=xdiff, ydiff=yindex): break max_yindex = yindex score = sum([y+max_yindex for x,y in center_shape]) # 克隆矩陣并且將方塊落下,便于計(jì)算落下后的空洞數(shù) clone_matrix = matrix.clone() clone_matrix.fill_block(center_shape, xdiff=xdiff, ydiff=max_yindex) score -= clone_matrix.get_hole_number() * COL_COUNT if score > max_score: max_score = score best_arr = arr self.ctl_arr = best_arr+[4]

現(xiàn)在AI的表現(xiàn)正常一些了,先優(yōu)化到這,下章繼續(xù),下面繼續(xù)貼下目前的完整代碼
# -*- coding=utf-8 -*-
import random
import pygame
from pygame.locals import KEYDOWN,K_LEFT,K_RIGHT,K_UP,K_DOWN,K_SPACE
import pickle,os
ROW_COUNT=20
COL_COUNT=10
SCORE_MAP=(100,300,800,1600)
class Matrix(object):
rows = 0
cols = 0
data = []
def __init__(self, rows, cols, data=None):
self.rows = rows
self.cols = cols
if data is None: data = [0 for i in range(rows*cols)]
self.data = data
def set_val(self, x, y, val):
self.data[y*self.cols+x] = val
def get_val(self, x, y):
return self.data[y*self.cols+x]
def cross_block(self, rect_arr, xdiff=0, ydiff=0):
for x,y in rect_arr:
#if x+xdiff>=0 and x+xdiff<self.cols and y+ydiff>=0 and y+ydiff<self.rows:
if self.get_val(x+xdiff,y+ydiff) == 1: return True
return False
def get_hole_number(self):
hole_num=0
for x in range(0,self.cols):
for y in range(1,self.rows):
if self.get_val(x,y) == 0 and self.get_val(x,y-1) == 1: # 上方有方塊的當(dāng)成空洞
#print x,y
hole_num+=1
return hole_num
def clone(self):
clone_matrix=Matrix(self.rows, self.cols, list(self.data))
return clone_matrix
def fill_block(self, rect_arr, xdiff=0, ydiff=0):
for x,y in rect_arr:
self.set_val(x+xdiff,y+ydiff, 1)
def print_matrix(self):
for i in range(self.rows):
print self.data[self.cols*i:self.cols*(i+1)]
class Player(object):
auto_mode=False # 是否是自動(dòng)模式,自動(dòng)模式應(yīng)當(dāng)不響應(yīng)鍵盤操作
def __init__(self):
pass
def run(self, panel): # 進(jìn)行操作
pass
class HumanPlayer(Player):
def __init__(self):
super(Player, self).__init__()
class AIPlayer(Player):
cal_block_id=-1 # 用于判斷是否方塊發(fā)生了變化
ctl_arr=[] # 存:1=變、2=左、3=右、4=下,這些數(shù)
auto_mode=True
ai_diff_ticks = 1 # 移動(dòng)一次的時(shí)間,單位毫秒
def __init__(self):
super(Player, self).__init__()
self.ctl_ticks = pygame.time.get_ticks() + self.ai_diff_ticks
def cal_best_arr(self, panel):
matrix = panel.get_rect_matrix()
cur_shape_id = panel.moving_block.shape_id
shape_num = panel.moving_block.shape_num
max_score = -10000
best_arr = []
for i in range(shape_num):
tmp_shape_id = cur_shape_id + i
if tmp_shape_id >= shape_num: tmp_shape_id = tmp_shape_id % shape_num
tmp_shape = panel.moving_block.get_shape(sid=tmp_shape_id)
center_shape = []
for x,y in tmp_shape: center_shape.append((x+COL_COUNT/2-2,y-2))
minx = COL_COUNT
maxx = 0
miny = ROW_COUNT
maxy = -2
for x,y in center_shape:
if x<minx: minx = x
if x>maxx: maxx = x
if y<miny: miny = y
if y>maxy: maxy = y
for xdiff in range(-minx,COL_COUNT-maxx): # 左右可以移動(dòng)的范圍
arr = [1 for _ in range(i)]
if xdiff < 0: [arr.append(2) for _ in range(-xdiff)]
if xdiff > 0: [arr.append(3) for _ in range(xdiff)]
max_yindex = -miny
for yindex in range(-miny, ROW_COUNT-maxy): # 往下檢測(cè)碰撞
if matrix.cross_block(center_shape, xdiff=xdiff, ydiff=yindex):
break
max_yindex = yindex
score = sum([y+max_yindex for x,y in center_shape])
# 克隆矩陣并且將方塊落下,便于計(jì)算落下后的空洞數(shù)
clone_matrix = matrix.clone()
clone_matrix.fill_block(center_shape, xdiff=xdiff, ydiff=max_yindex)
score -= clone_matrix.get_hole_number() * COL_COUNT
if score > max_score:
max_score = score
best_arr = arr
self.ctl_arr = best_arr+[4]
def run(self, panel):
if pygame.time.get_ticks() < self.ctl_ticks: return
self.ctl_ticks += self.ai_diff_ticks
if panel.block_id == self.cal_block_id: # block_id沒變,按原來計(jì)算好的操作規(guī)則進(jìn)行
if len(self.ctl_arr)>0:
ctl = self.ctl_arr.pop(0)
if ctl == 1: panel.change_block()
if ctl == 2: panel.control_block(-1,0)
if ctl == 3: panel.control_block(1,0)
if ctl == 4:
flag = panel.move_block()
while flag==1:
flag = panel.move_block()
else: # block_id變了,計(jì)算新方塊的操作規(guī)則
self.cal_block_id = panel.block_id
self.cal_best_arr(panel)
class RectInfo(object):
def __init__(self, x, y, color):
self.x = x
self.y = y
self.color = color
class HintBox(object):
next_block=None
def __init__(self, bg, block_size, position):
self._bg=bg;
self._x,self._y,self._width,self._height=position
self._block_size=block_size
self._bgcolor=[0,0,0]
def take_block(self):
block = self.next_block
if block is None: # 如果還沒有方塊,先產(chǎn)生一個(gè)
block = create_block()
self.next_block = create_block() # 產(chǎn)生下一個(gè)方塊
return block
def paint(self):
mid_x=self._x+self._width/2
pygame.draw.line(self._bg,self._bgcolor,[mid_x,self._y],[mid_x,self._y+self._height],self._width)
bz=self._block_size
# 繪制正在落下的方塊
if self.next_block:
arr = self.next_block.get_rect_arr()
minx,miny=arr[0]
maxx,maxy=arr[0]
for x,y in arr:
if x<minx: minx=x
if x>maxx: maxx=x
if y<miny: miny=y
if y>maxy: maxy=y
w=(maxx-minx)*bz
h=(maxy-miny)*bz
# 計(jì)算使方塊繪制在提示窗中心位置所需要的偏移像素
cx=self._width/2-w/2-minx*bz-bz/2
cy=self._height/2-h/2-miny*bz-bz/2
for rect in arr:
x,y=rect
pygame.draw.line(self._bg,self.next_block.color,[self._x+x*bz+cx+bz/2,self._y+cy+y*bz],[self._x+x*bz+cx+bz/2,self._y+cy+(y+1)*bz],bz)
pygame.draw.rect(self._bg,[255,255,255],[self._x+x*bz+cx,self._y+y*bz+cy,bz+1,bz+1],1)
class ScoreBox(object):
total_score = 0
high_score = 0
db_file = 'tetris.db'
def __init__(self, bg, block_size, position):
self._bg=bg;
self._x,self._y,self._width,self._height=position
self._block_size=block_size
self._bgcolor=[0,0,0]
if os.path.exists(self.db_file): self.high_score = pickle.load(open(self.db_file,'rb'))
def paint(self):
myfont = pygame.font.Font(None,36)
white = 255,255,255
textImage = myfont.render('High: %06d'%(self.high_score), True, white)
self._bg.blit(textImage, (self._x,self._y))
textImage = myfont.render('Score:%06d'%(self.total_score), True, white)
self._bg.blit(textImage, (self._x,self._y+40))
def add_score(self, score):
self.total_score += score
if self.total_score > self.high_score:
self.high_score=self.total_score
pickle.dump(self.high_score, open(self.db_file,'wb+'))
class Panel(object): # 用于繪制整個(gè)游戲窗口的版面
block_id=0
#rect_arr=[RectInfo(4,19,[0,0,255]),RectInfo(6,19,[0,0,255])] # 已經(jīng)落底下的方塊
rect_arr=[] # 已經(jīng)落底下的方塊
moving_block=None # 正在落下的方塊
hint_box=None
score_box=None
def __init__(self,bg, block_size, position):
self._bg=bg;
self._x,self._y,self._width,self._height=position
self._block_size=block_size
self._bgcolor=[0,0,0]
def get_rect_matrix(self):
matrix = Matrix(ROW_COUNT, COL_COUNT)
for rect_info in self.rect_arr:
matrix.set_val(rect_info.x, rect_info.y, 1)
return matrix
def add_block(self,block):
for x,y in block.get_rect_arr():
self.rect_arr.append(RectInfo(x,y, block.color))
def create_move_block(self):
self.block_id+=1
block = self.hint_box.take_block()
#block = create_block()
block.move(COL_COUNT/2-2,-2) # 方塊挪到中間
self.moving_block=block
def check_overlap(self, diffx, diffy, check_arr=None):
if check_arr is None: check_arr = self.moving_block.get_rect_arr()
for x,y in check_arr:
for rect_info in self.rect_arr:
if x+diffx==rect_info.x and y+diffy==rect_info.y:
return True
return False
def control_block(self, diffx, diffy):
if self.moving_block.can_move(diffx,diffy) and not self.check_overlap(diffx, diffy):
self.moving_block.move(diffx,diffy)
def change_block(self):
if self.moving_block:
new_arr = self.moving_block.change()
if new_arr and not self.check_overlap(0, 0, check_arr=new_arr): # 變形不能造成方塊重疊
self.moving_block.rect_arr=new_arr
def move_block(self):
if self.moving_block is None: create_move_block()
if self.moving_block.can_move(0,1) and not self.check_overlap(0,1):
self.moving_block.move(0,1)
return 1
else:
self.add_block(self.moving_block)
self.check_clear()
for rect_info in self.rect_arr:
if rect_info.y<0: return 9 # 游戲失敗
self.create_move_block()
return 2
def check_clear(self):
tmp_arr = [[] for i in range(20)]
# 先將方塊按行存入數(shù)組
for rect_info in self.rect_arr:
if rect_info.y<0: return
tmp_arr[rect_info.y].append(rect_info)
clear_num=0
clear_lines=set([])
y_clear_diff_arr=[[] for i in range(20)]
# 從下往上計(jì)算可以消除的行,并記錄消除行后其他行的向下偏移數(shù)量
for y in range(19,-1,-1):
if len(tmp_arr[y])==10:
clear_lines.add(y)
clear_num += 1
y_clear_diff_arr[y] = clear_num
if clear_num>0:
new_arr=[]
# 跳過移除行,并將其他行做偏移
for y in range(19,-1,-1):
if y in clear_lines: continue
tmp_row = tmp_arr[y]
y_clear_diff=y_clear_diff_arr[y]
for rect_info in tmp_row:
#new_arr.append([x,y+y_clear_diff])
new_arr.append(RectInfo(rect_info.x, rect_info.y+y_clear_diff, rect_info.color))
self.rect_arr = new_arr
score = SCORE_MAP[clear_num-1]
self.score_box.add_score(score)
def paint(self):
mid_x=self._x+self._width/2
pygame.draw.line(self._bg,self._bgcolor,[mid_x,self._y],[mid_x,self._y+self._height],self._width) # 用一個(gè)粗線段來填充背景
# 繪制已經(jīng)落底下的方塊
bz=self._block_size
for rect_info in self.rect_arr:
x=rect_info.x
y=rect_info.y
pygame.draw.line(self._bg,rect_info.color,[self._x+x*bz+bz/2,self._y+y*bz],[self._x+x*bz+bz/2,self._y+(y+1)*bz],bz)
pygame.draw.rect(self._bg,[255,255,255],[self._x+x*bz,self._y+y*bz,bz+1,bz+1],1)
# 繪制正在落下的方塊
if self.move_block:
for rect in self.moving_block.get_rect_arr():
x,y=rect
pygame.draw.line(self._bg,self.moving_block.color,[self._x+x*bz+bz/2,self._y+y*bz],[self._x+x*bz+bz/2,self._y+(y+1)*bz],bz)
pygame.draw.rect(self._bg,[255,255,255],[self._x+x*bz,self._y+y*bz,bz+1,bz+1],1)
class Block(object):
sx=0
sy=0
def __init__(self):
self.rect_arr=[]
def get_rect_arr(self): # 用于獲取方塊種的四個(gè)矩形列表
return self.rect_arr
def move(self,xdiff,ydiff): # 用于移動(dòng)方塊的方法
self.sx+=xdiff
self.sy+=ydiff
self.new_rect_arr=[]
for x,y in self.rect_arr:
self.new_rect_arr.append((x+xdiff,y+ydiff))
self.rect_arr=self.new_rect_arr
def can_move(self,xdiff,ydiff):
for x,y in self.rect_arr:
if y+ydiff>=20: return False
if x+xdiff<0 or x+xdiff>=10: return False
return True
def change(self):
self.shape_id+=1 # 下一形態(tài)
if self.shape_id >= self.shape_num:
self.shape_id=0
arr = self.get_shape()
new_arr = []
for x,y in arr:
if x+self.sx<0 or x+self.sx>=10: # 變形不能超出左右邊界
self.shape_id -= 1
if self.shape_id < 0: self.shape_id = self.shape_num - 1
return None
new_arr.append([x+self.sx,y+self.sy])
return new_arr
class LongBlock(Block):
shape_id=0
shape_num=2
def __init__(self, n=None): # 兩種形態(tài)
super(LongBlock, self).__init__()
if n is None: n=random.randint(0,1)
self.shape_id=n
self.rect_arr=self.get_shape()
self.color=(50,180,50)
def get_shape(self, sid=None):
if sid is None: sid = self.shape_id
return [(1,0),(1,1),(1,2),(1,3)] if sid==0 else [(0,2),(1,2),(2,2),(3,2)]
class SquareBlock(Block): # 一種形態(tài)
shape_id=0
shape_num=1
def __init__(self, n=None):
super(SquareBlock, self).__init__()
self.rect_arr=self.get_shape()
self.color=(0,0,255)
def get_shape(self, sid=None):
if sid is None: sid = self.shape_id
return [(1,1),(1,2),(2,1),(2,2)]
class ZBlock(Block): # 兩種形態(tài)
shape_id=0
shape_num=2
def __init__(self, n=None):
super(ZBlock, self).__init__()
if n is None: n=random.randint(0,1)
self.shape_id=n
self.rect_arr=self.get_shape()
self.color=(30,200,200)
def get_shape(self, sid=None):
if sid is None: sid = self.shape_id
return [(2,0),(2,1),(1,1),(1,2)] if sid==0 else [(0,1),(1,1),(1,2),(2,2)]
class SBlock(Block): # 兩種形態(tài)
shape_id=0
shape_num=2
def __init__(self, n=None):
super(SBlock, self).__init__()
if n is None: n=random.randint(0,1)
self.shape_id=n
self.rect_arr=self.get_shape()
self.color=(255,30,255)
def get_shape(self, sid=None):
if sid is None: sid = self.shape_id
return [(1,0),(1,1),(2,1),(2,2)] if sid==0 else [(0,2),(1,2),(1,1),(2,1)]
class LBlock(Block): # 四種形態(tài)
shape_id=0
shape_num=4
def __init__(self, n=None):
super(LBlock, self).__init__()
if n is None: n=random.randint(0,3)
self.shape_id=n
self.rect_arr=self.get_shape()
self.color=(200,200,30)
def get_shape(self, sid=None):
if sid is None: sid = self.shape_id
if sid==0: return [(1,0),(1,1),(1,2),(2,2)]
elif sid==1: return [(0,1),(1,1),(2,1),(0,2)]
elif sid==2: return [(0,0),(1,0),(1,1),(1,2)]
else: return [(0,1),(1,1),(2,1),(2,0)]
class JBlock(Block): # 四種形態(tài)
shape_id=0
shape_num=4
def __init__(self, n=None):
super(JBlock, self).__init__()
if n is None: n=random.randint(0,3)
self.shape_id=n
self.rect_arr=self.get_shape()
self.color=(200,100,0)
def get_shape(self, sid=None):
if sid is None: sid = self.shape_id
if sid==0: return [(1,0),(1,1),(1,2),(0,2)]
elif sid==1: return [(0,1),(1,1),(2,1),(0,0)]
elif sid==2: return [(2,0),(1,0),(1,1),(1,2)]
else: return [(0,1),(1,1),(2,1),(2,2)]
class TBlock(Block): # 四種形態(tài)
shape_id=0
shape_num=4
def __init__(self, n=None):
super(TBlock, self).__init__()
if n is None: n=random.randint(0,3)
self.shape_id=n
self.rect_arr=self.get_shape()
self.color=(255,0,0)
def get_shape(self, sid=None):
if sid is None: sid = self.shape_id
if sid==0: return [(0,1),(1,1),(2,1),(1,2)]
elif sid==1: return [(1,0),(1,1),(1,2),(0,1)]
elif sid==2: return [(0,1),(1,1),(2,1),(1,0)]
else: return [(1,0),(1,1),(1,2),(2,1)]
def create_block():
n = random.randint(0,18)
if n==0: return SquareBlock(n=0)
elif n==1 or n==2: return LongBlock(n=n-1)
elif n==3 or n==4: return ZBlock(n=n-3)
elif n==5 or n==6: return SBlock(n=n-5)
elif n>=7 and n<=10: return LBlock(n=n-7)
elif n>=11 and n<=14: return JBlock(n=n-11)
else: return TBlock(n=n-15)
def run():
pygame.init()
space=30
main_block_size=30
main_panel_width=main_block_size*COL_COUNT
main_panel_height=main_block_size*ROW_COUNT
screencaption = pygame.display.set_caption('Tetris')
screen = pygame.display.set_mode((main_panel_width+160+space*3,main_panel_height+space*2)) #設(shè)置窗口長寬
main_panel=Panel(screen,main_block_size,[space,space,main_panel_width,main_panel_height])
hint_box=HintBox(screen,main_block_size,[main_panel_width+space+space,space,160,160])
score_box=ScoreBox(screen,main_block_size,[main_panel_width+space+space,160+space*2,160,160])
main_panel.hint_box=hint_box
main_panel.score_box=score_box
pygame.key.set_repeat(200, 30)
main_panel.create_move_block()
diff_ticks = 300 # 移動(dòng)一次蛇頭的事件,單位毫秒
ticks = pygame.time.get_ticks() + diff_ticks
player = AIPlayer()
pause=0
game_state = 1 # 游戲狀態(tài)1.表示正常 2.表示失敗
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == KEYDOWN:
if event.key==97: pause=1-pause # 按鍵盤a支持暫停
if event.key==112: # for debug # 按鍵盤p打印矩陣信息
main_panel.get_rect_matrix().print_matrix()
if player.auto_mode:continue
if event.type == KEYDOWN:
if event.key == K_LEFT: main_panel.control_block(-1,0)
if event.key == K_RIGHT: main_panel.control_block(1,0)
if event.key == K_UP: main_panel.change_block()
if event.key == K_DOWN: main_panel.control_block(0,1)
if event.key == K_SPACE:
flag = main_panel.move_block()
while flag==1:
flag = main_panel.move_block()
if flag == 9: game_state = 2
screen.fill((100,100,100)) # 將界面設(shè)置為灰色
main_panel.paint() # 主面盤繪制
hint_box.paint() # 繪制下一個(gè)方塊的提示窗
score_box.paint() # 繪制總分
if game_state == 2:
myfont = pygame.font.Font(None,30)
white = 255,255,255
textImage = myfont.render("Game over", True, white)
screen.blit(textImage, (160,190))
pygame.display.update() # 必須調(diào)用update才能看到繪圖顯示
if pause==1: continue
if game_state == 1: player.run(main_panel)
if game_state == 1 and pygame.time.get_ticks() >= ticks:
ticks+=diff_ticks
if main_panel.move_block()==9: game_state = 2 # 游戲結(jié)束
run()
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- pygame實(shí)現(xiàn)俄羅斯方塊游戲(對(duì)戰(zhàn)篇1)
- pygame實(shí)現(xiàn)俄羅斯方塊游戲(AI篇2)
- pygame實(shí)現(xiàn)俄羅斯方塊游戲(基礎(chǔ)篇3)
- pygame實(shí)現(xiàn)俄羅斯方塊游戲(基礎(chǔ)篇2)
- pygame實(shí)現(xiàn)俄羅斯方塊游戲(基礎(chǔ)篇1)
- pygame實(shí)現(xiàn)俄羅斯方塊游戲
- python和pygame實(shí)現(xiàn)簡單俄羅斯方塊游戲
- Python使用pygame模塊編寫俄羅斯方塊游戲的代碼實(shí)例
- pygame庫實(shí)現(xiàn)俄羅斯方塊小游戲
相關(guān)文章
python選取特定列 pandas iloc,loc,icol的使用詳解(列切片及行切片)
今天小編就為大家分享一篇python選取特定列 pandas iloc,loc,icol的使用詳解(列切片及行切片),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-08-08
python破解bilibili滑動(dòng)驗(yàn)證碼登錄功能
這篇文章主要介紹了python破解bilibili滑動(dòng)驗(yàn)證碼登錄功能,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-09-09
pandas取dataframe特定行列的實(shí)現(xiàn)方法
大家在使用Python進(jìn)行數(shù)據(jù)分析時(shí),經(jīng)常要使用到的一個(gè)數(shù)據(jù)結(jié)構(gòu)就是pandas的DataFrame,本文介紹了pandas取dataframe特定行列的實(shí)現(xiàn)方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-05-05
詳解使用 pyenv 管理多個(gè)版本 python 環(huán)境
本篇文章主要介紹了詳解使用 pyenv 管理多個(gè)版本 python 環(huán)境,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-10-10
python2與python3的print及字符串格式化小結(jié)
最近一直在用python寫程序,對(duì)于python的print一直很惱火,老是不按照預(yù)期輸出。今天特來總結(jié)一樣print和format,也希望能幫助大家徹底理解它們2018-11-11
Pandas中Series的創(chuàng)建及數(shù)據(jù)類型轉(zhuǎn)換
這篇文章主要介紹了Pandas中Series的創(chuàng)建及數(shù)據(jù)類型轉(zhuǎn)換,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-08-08

