当前位置 主页 > 网站技术 > 代码类 >

    pygame实现俄罗斯方块游戏(对战篇1)

    栏目:代码类 时间:2019-10-29 21:08

    上篇更新到pygame实现俄罗斯方块游戏(AI篇2) ,原本应该继续做优化,不过考虑到完成游戏完整性,这张就先把对战做好。

    一、对战的方块管理

    定义一个BlockManage管理对战的方块

    class BlockManage(object):
     pnum=1
     blocks = []
     def __init__(self,pnum):
     self.pnum=pnum
     self.blocks=[[] for i in range(self.pnum)]
    
     def get_block(self, pid=0):
     if len(self.blocks[pid]) == 0:
     block = create_block()
     for arr in self.blocks:
     arr.append(pickle.loads(pickle.dumps(block)))
     return self.blocks[pid].pop(0)

    根据BlockManage根据传入的玩家id返回方块,保证每个玩家拿到的方块序列十一致的,所以在每次创建方块时存放了玩家数量相同的拷贝,拷贝是避免对象的引用造成对同一个方块对象操作混乱。

    然后HintBox里加入block_manage的引用并且在take_block函数里将创建Block改为使用block_manage去取方块

    class HintBox(object):
     block_manage=None
     next_block=None
     def __init__(self, bg, block_size, position, block_manage):
     self._bg=bg;
     self._x,self._y,self._width,self._height=position
     self._block_size=block_size
     self._bgcolor=[0,0,0]
     self.block_manage=block_manage
    
     def take_block(self):
     block = self.next_block
     if block is None: # make first block
     block = self.block_manage.get_block()
     
     self.next_block = self.block_manage.get_block()
     return block

    分别定义一个VirtualHintBox和一个VirtualScoreBox,用于给右下角面板上的

    class VirtualHintBox(object):
     pid = 0
     block_manage=None
     next_block=None
     def __init__(self, pid, block_manage):
     print pid
     self.pid=pid
     self.block_manage=block_manage
    
     def take_block(self):
     block = self.next_block
     if block is None: # make first block
     block = block_manage.get_block(self.pid)
     
     self.next_block = block_manage.get_block(self.pid)
     return block
    class VirtualScoreBox(object):
     total_score = 0
     def __init__(self):
     pass
    
     def add_score(self, score):
     self.total_score += score

    使用block_manage并分别传递给主面板的hint_box和右下角面板的VirtualHintBox,右下角面板的定义和初使设置完了以后,将下面的player改为player1和player2两个玩家。

    在游戏主循环增加完相应的设置和操作,现在就可以玩人机对战了。

    当然如果你把

    player1 = HumanPlayer()
    player2 = AIPlayer(ai_diff_ticks=350)

    改成

    player1 = AIPlayer(ai_diff_ticks=150)
    player2 = AIPlayer(ai_diff_ticks=350)

    当然就是一场机器人对机器人的战斗

    二、记分和增加对抗性

    增加记分显示比较容易,给VirtualScoreBox实现下paint就行。

    class VirtualScoreBox(object):
     total_score = 0
     def __init__(self, bg, position):
     self._bg=bg;
     self._x,self._y,self._width,self._height=position
     self._bgcolor=[0,0,0]
    
     def paint(self):
     myfont = pygame.font.Font(None,22)
     white = 255,255,255
     textImage = myfont.render('Player2 Score:%06d'%(self.total_score), True, white)
     self._bg.blit(textImage, (self._x,self._y))
    
     def add_score(self, score):
     self.total_score += score