Skip to main content
 首页 » 编程设计

python之如何在 Python 中创建自动化的俄罗斯方 block 机器人

2024年11月01日11cyq1162

所以我用 python 编写了一个俄罗斯方 block 机器人,它使用 pygame 事件来响应键盘输入。现在我正在尝试创建一个 AI 来玩这个游戏。所以我想基本上确定最好的一步是给定一个棋子和一个棋盘。我想遍历每一个可能的 Action ,并评估棋盘状态(我有一种方法可以评估给定棋盘的好坏),然后选择能够创造最佳棋盘状态的棋步。我目前的主要方法如下。

def main(): 
    pygame.init() 
    pygame.mixer.music.load("music.ogg") 
    #pygame.mixer.music.play(-1) 
    pygame.key.set_repeat(200,100) 
    game_state = state.GameState() 
 
    while True: 
        game_state.apply_gravity() 
        game_state.check_collision(place_if_collision=True) 
        game_state.time += 1 
        if game_state.hardDrop: 
            continue 
        game_state.check_for_full_rows() 
        game_state.print_state() 
        pygame.display.flip() 
        for event in pygame.event.get(): 
            if event.type == QUIT: 
                terminate() 
            elif event.type==KEYDOWN: 
                if event.key==K_ESCAPE: 
                    terminate() 
                if event.key==K_LEFT: 
                    game_state.save_state() 
                    game_state.piece_x -= 1 
                    game_state.check_collision() 
                if event.key==K_RIGHT: 
                    game_state.save_state() 
                    game_state.piece_x += 1 
                    game_state.check_collision()  
                if event.key==K_DOWN: 
                    game_state.save_state() 
                    game_state.piece_y += 1 
                    game_state.check_collision(place_if_collision=True) 
                if event.key==K_UP: 
                    game_state.save_state() 
                    game_state.curr_piece.rotate_cw() 
                    game_state.check_collision() 
                    game_state.print_state() 
                if event.key==K_SPACE: 
                    game_state.hardDrop = True 

如何在不实际修改状态/重写一堆代码的情况下弄清楚状态的样子?我可以根据需要提供更多代码。这样做的目的是为了让我可以使用遗传算法来训练神经网络,玩俄罗斯方 block 。

请您参考如下方法:

非常有趣和独特的问题,你不能只创建一个独立副本并在该副本上运行你的测试并在完成后将其删除。

从复制导入deepcopy

#some other code...

temp_state = deepcopy(original_state)

然后您在 temp_state 上运行您的测试,一旦您使用完它: del temp_state

至于你的第二个问题,你可以让机器人分析一个棋子的位置,一旦它到达 2 个街区或解决你的问题的任何东西。或者,您可能在顶部(屏幕之外)有一些看不见的额外线条,玩家看不到这些线条,但机器人可以使用它们来做出决定。

此外,我相信您已经这样做了,您可以使用 itertools 创建字符串列表,例如 lllllus,llllluus(引用您的评论)。具体来说,尝试 itertools.product 和 itertools.combinations。