您好,登錄后才能下訂單哦!
這篇文章給大家介紹pygame實現俄羅斯方塊游戲,內容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
在Panel類里增加函數
def check_overlap(self, diffx, diffy): for x,y in self.moving_block.get_rect_arr(): for rx,ry in self.rect_arr: if x+diffx==rx and y+diffy==ry: return True return False
修改move_block函數的判斷,增加check_overlap函數檢測
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) else: self.add_block(self.moving_block) self.create_move_block()
現在的效果是方塊可以堆疊了
六、鍵盤控制左右移動
導入變量
from pygame.locals import KEYDOWN,K_LEFT,K_RIGHT,K_UP,K_DOWN
Panel類里增加一個控制移動方塊的函數
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)
鼠標事件監聽處做下鍵盤的響應
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: pass # 變形過會實現 if event.key == K_DOWN: main_panel.control_block(0,1)
由于Block類的can_move函數沒有實現左右移動的判斷,所以需要再對can_move
增加左右邊界的處理
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
現在,左右的移動也正常了,效果圖如下
貼下目前的代碼
# -*- coding=utf-8 -*- import random import pygame from pygame.locals import KEYDOWN,K_LEFT,K_RIGHT,K_UP,K_DOWN class Panel(object): # 用于繪制整個游戲窗口的版面 rect_arr=[] # 已經落底下的方塊 moving_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 add_block(self,block): for rect in block.get_rect_arr(): self.rect_arr.append(rect) def create_move_block(self): block = create_block() block.move(5-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 rx,ry in self.rect_arr: if x+diffx==rx and y+diffy==ry: 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 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) else: self.add_block(self.moving_block) self.create_move_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 for rect in self.rect_arr: x,y=rect pygame.draw.line(self._bg,[0,0,255],[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,[0,0,255],[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): def __init__(self): self.rect_arr=[] def get_rect_arr(self): # 用于獲取方塊種的四個矩形列表 return self.rect_arr def move(self,xdiff,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 class LongBlock(Block): def __init__(self, n=None): # 兩種形態 super(LongBlock, self).__init__() if n is None: n=random.randint(0,1) self.rect_arr=[(1,0),(1,1),(1,2),(1,3)] if n==0 else [(0,2),(1,2),(2,2),(3,2)] class SquareBlock(Block): # 一種形態 def __init__(self, n=None): super(SquareBlock, self).__init__() self.rect_arr=[(1,1),(1,2),(2,1),(2,2)] class ZBlock(Block): # 兩種形態 def __init__(self, n=None): super(ZBlock, self).__init__() if n is None: n=random.randint(0,1) self.rect_arr=[(2,0),(2,1),(1,1),(1,2)] if n==0 else [(0,1),(1,1),(1,2),(2,2)] class SBlock(Block): # 兩種形態 def __init__(self, n=None): super(SBlock, self).__init__() if n is None: n=random.randint(0,1) self.rect_arr=[(1,0),(1,1),(2,1),(2,2)] if n==0 else [(0,2),(1,2),(1,1),(2,1)] class LBlock(Block): # 四種形態 def __init__(self, n=None): super(LBlock, self).__init__() if n is None: n=random.randint(0,3) if n==0: self.rect_arr=[(1,0),(1,1),(1,2),(2,2)] elif n==1: self.rect_arr=[(0,1),(1,1),(2,1),(0,2)] elif n==2: self.rect_arr=[(0,0),(1,0),(1,1),(1,2)] else: self.rect_arr=[(0,1),(1,1),(2,1),(2,0)] class JBlock(Block): # 四種形態 def __init__(self, n=None): super(JBlock, self).__init__() if n is None: n=random.randint(0,3) if n==0: self.rect_arr=[(1,0),(1,1),(1,2),(0,2)] elif n==1: self.rect_arr=[(0,1),(1,1),(2,1),(0,0)] elif n==2: self.rect_arr=[(2,0),(1,0),(1,1),(1,2)] else: self.rect_arr=[(0,1),(1,1),(2,1),(2,2)] class TBlock(Block): # 四種形態 def __init__(self, n=None): super(TBlock, self).__init__() if n is None: n=random.randint(0,3) if n==0: self.rect_arr=[(0,1),(1,1),(2,1),(1,2)] elif n==1: self.rect_arr=[(1,0),(1,1),(1,2),(0,1)] elif n==2: self.rect_arr=[(0,1),(1,1),(2,1),(1,0)] else: self.rect_arr=[(1,0),(1,1),(1,2),(2,1)] def create_block(): n = random.randint(0,19) 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*10 main_panel_height=main_block_size*20 screencaption = pygame.display.set_caption('Tetris') screen = pygame.display.set_mode((main_panel_width+160+space*3,main_panel_height+space*2)) #設置窗口長寬 main_panel=Panel(screen,main_block_size,[space,space,main_panel_width,main_panel_height]) pygame.key.set_repeat(200, 30) main_panel.create_move_block() diff_ticks = 300 # 移動一次蛇頭的事件,單位毫秒 ticks = pygame.time.get_ticks() + diff_ticks while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit() 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: pass # 變形過會實現 if event.key == K_DOWN: main_panel.control_block(0,1) screen.fill((100,100,100)) # 將界面設置為灰色 main_panel.paint() # 主面盤繪制 pygame.display.update() # 必須調用update才能看到繪圖顯示 if pygame.time.get_ticks() >= ticks: ticks+=diff_ticks main_panel.move_block() run()
七、控制變形
變形的實現,我們對每個方塊子類的初始化函數稍作修改,將獲取形狀做一個獨立的get_shape函數,并且給每個子類增加一個變量用于記錄當前形態id,用一個變量用于標識每種方塊的形態數量,以T型為例,修改后代碼如下
class TBlock(Block): # 四種形態 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() def get_shape(self): if self.shape_id==0: return [(0,1),(1,1),(2,1),(1,2)] elif self.shape_id==1: return [(1,0),(1,1),(1,2),(0,1)] elif self.shape_id==2: return [(0,1),(1,1),(2,1),(1,0)] else: return [(1,0),(1,1),(1,2),(2,1)]
這樣我們在Block父類里可以加一個change函數,用于變換至下一形態,由于變化時要保持原來的移動位置,我們增加sx,sy兩個變量將方塊移動過的位置存著,便于在變化時使用
class Block(object): sx=0 sy=0 def __init__(self): self.rect_arr=[] def get_rect_arr(self): # 用于獲取方塊種的四個矩形列表 return self.rect_arr def move(self,xdiff,ydiff): # 用于移動方塊的方法 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 # 下一形態 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
在Panel類里的再增加一個change函數,直接調用moving_block的change
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
最后將key_up事件的響應加入change_block的調用就好了
if event.key == K_UP: main_panel.change_block()
現在已經實現了,變形和移動了,方塊基本可以正常下落了
八、方塊的消除
這個計算主要是處理Panel類的rect_arr,如果數組中出現某一行有10個就符合消除條件,為簡化計算,我們將這些矩形按y值存到一個數組中,便于計算
def check_clear(self): tmp_arr = [[] for i in range(20)] # 先將方塊按行存入數組 for x,y in self.rect_arr: if y<0: return tmp_arr[y].append([x,y]) clear_num=0 clear_lines=set([]) y_clear_diff_arr=[[] for i in range(20)] # 從下往上計算可以消除的行,并記錄消除行后其他行的向下偏移數量 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 x,y in tmp_row: new_arr.append([x,y+y_clear_diff]) self.rect_arr = new_arr
在Panel的move_block處增加check_clear的調用
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) else: self.add_block(self.moving_block) self.check_clear() self.create_move_block()
現在游戲可以消除方塊了
九、增加空格鍵使快速落下
快速落下可以快速調用Panel的move_block函數,我們在move_block函數增加一個返回值,用于標記使正常下移還是移到底部后新的方塊
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() self.create_move_block() return 2
在鍵盤響應處增加鍵盤處理
if event.key == K_SPACE: while main_panel.move_block()==1: pass
十、增加游戲結束判斷
游戲結束同樣可以在Panel類的move_block中處理,如果一個方塊到底,并且消除進行后,發現有方塊的y值小于0,那么一定是失敗了
修改Panel類的move_block函數
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 x,y in self.rect_arr: if y<0: return 9 # 游戲失敗 self.create_move_block() return 2
增加一個變量記錄游戲狀態
game_state = 1 # 游戲狀態1.表示正常 2.表示失敗
計時器處修改程序
if game_state == 1 and pygame.time.get_ticks() >= ticks: ticks+=diff_ticks if main_panel.move_block()==9: game_state = 2
鼠標鍵盤響應空格鍵中也增加一下判斷
if event.key == K_SPACE: flag = main_panel.move_block() while flag==1: flag = main_panel.move_block() if flag == 9: game_state = 2
最后增加游戲結束文字的繪制
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))
好了,現在會提示游戲結束了
最后附下目前的完整代碼
# -*- coding=utf-8 -*- import random import pygame from pygame.locals import KEYDOWN,K_LEFT,K_RIGHT,K_UP,K_DOWN,K_SPACE class Panel(object): # 用于繪制整個游戲窗口的版面 rect_arr=[] # 已經落底下的方塊 moving_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 add_block(self,block): for rect in block.get_rect_arr(): self.rect_arr.append(rect) def create_move_block(self): block = create_block() block.move(5-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 rx,ry in self.rect_arr: if x+diffx==rx and y+diffy==ry: 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 x,y in self.rect_arr: if y<0: return 9 # 游戲失敗 self.create_move_block() return 2 def check_clear(self): tmp_arr = [[] for i in range(20)] # 先將方塊按行存入數組 for x,y in self.rect_arr: if y<0: return tmp_arr[y].append([x,y]) clear_num=0 clear_lines=set([]) y_clear_diff_arr=[[] for i in range(20)] # 從下往上計算可以消除的行,并記錄消除行后其他行的向下偏移數量 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 x,y in tmp_row: new_arr.append([x,y+y_clear_diff]) self.rect_arr = new_arr 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 for rect in self.rect_arr: x,y=rect pygame.draw.line(self._bg,[0,0,255],[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,[0,0,255],[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): # 用于獲取方塊種的四個矩形列表 return self.rect_arr def move(self,xdiff,ydiff): # 用于移動方塊的方法 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 # 下一形態 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): # 兩種形態 super(LongBlock, self).__init__() if n is None: n=random.randint(0,1) self.shape_id=n self.rect_arr=self.get_shape() def get_shape(self): return [(1,0),(1,1),(1,2),(1,3)] if self.shape_id==0 else [(0,2),(1,2),(2,2),(3,2)] class SquareBlock(Block): # 一種形態 shape_id=0 shape_num=1 def __init__(self, n=None): super(SquareBlock, self).__init__() self.rect_arr=self.get_shape() def get_shape(self): return [(1,1),(1,2),(2,1),(2,2)] class ZBlock(Block): # 兩種形態 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() def get_shape(self): return [(2,0),(2,1),(1,1),(1,2)] if self.shape_id==0 else [(0,1),(1,1),(1,2),(2,2)] class SBlock(Block): # 兩種形態 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() def get_shape(self): return [(1,0),(1,1),(2,1),(2,2)] if self.shape_id==0 else [(0,2),(1,2),(1,1),(2,1)] class LBlock(Block): # 四種形態 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() def get_shape(self): if self.shape_id==0: return [(1,0),(1,1),(1,2),(2,2)] elif self.shape_id==1: return [(0,1),(1,1),(2,1),(0,2)] elif self.shape_id==2: return [(0,0),(1,0),(1,1),(1,2)] else: return [(0,1),(1,1),(2,1),(2,0)] class JBlock(Block): # 四種形態 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() def get_shape(self): if self.shape_id==0: return [(1,0),(1,1),(1,2),(0,2)] elif self.shape_id==1: return [(0,1),(1,1),(2,1),(0,0)] elif self.shape_id==2: return [(2,0),(1,0),(1,1),(1,2)] else: return [(0,1),(1,1),(2,1),(2,2)] class TBlock(Block): # 四種形態 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() def get_shape(self): if self.shape_id==0: return [(0,1),(1,1),(2,1),(1,2)] elif self.shape_id==1: return [(1,0),(1,1),(1,2),(0,1)] elif self.shape_id==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,19) 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*10 main_panel_height=main_block_size*20 screencaption = pygame.display.set_caption('Tetris') screen = pygame.display.set_mode((main_panel_width+160+space*3,main_panel_height+space*2)) #設置窗口長寬 main_panel=Panel(screen,main_block_size,[space,space,main_panel_width,main_panel_height]) pygame.key.set_repeat(200, 30) main_panel.create_move_block() diff_ticks = 300 # 移動一次蛇頭的事件,單位毫秒 ticks = pygame.time.get_ticks() + diff_ticks game_state = 1 # 游戲狀態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 == 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)) # 將界面設置為灰色 main_panel.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() # 必須調用update才能看到繪圖顯示 if game_state == 1 and pygame.time.get_ticks() >= ticks: ticks+=diff_ticks if main_panel.move_block()==9: game_state = 2 # 游戲結束 run()
關于pygame實現俄羅斯方塊游戲就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。