有没有办法进入for循环,然后从当前位置反转该循环?

2024-04-24 09:29:48 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,我已经开始编写一个UNO!游戏我要做倒牌。整个'主游戏代码'在那里你放置卡和重新排序的一堆等。。。“主游戏代码”在这个循环中: while self.gamestr==True: for l in range(1,players+1): 我需要循环范围(1,玩家+1,-1),而在循环内,并改变它回来,而仍然在循环! 提前谢谢


Tags: 代码inselftrue游戏for排序玩家
2条回答

这只是一个demo如何做到这一点,当一张通配符被抽出来时,你可以通过使用切片和反向步骤[::-1]来重建你正在循环的列表

players = [1, 2, 3]
while True:
    for i, v in enumerate(players):
        if v == 1:
            print('wild card')
            players = players[i - 1::-1] + players[:i - 1:-1]
    print(players)
    for i, v in enumerate(players):
        if v == 3:
            print('wild card')
            players = players[i - 1::-1] + players[:i - 1:-1]
    print(players)
    break
wild card
[3, 2, 1]
wild card
[1, 2, 3]

这里我们看到,如果wildplayer 1上,那么它就变成了player 3的反向播放,当wildplayer 3上时,它再次反向播放,并且它在player 1上。这是应用于游戏的总体思路,这种格式只是为了演示。你知道吗

做你想做的事不容易。你可以或者在适当的位置反转列表,但是你还需要移动列表的一部分,以确保正确的玩家是“下一个”。你知道吗

更好的选择是简单地使用不同类型的循环。最简单的方法可能是使用while循环,跟踪您所在的索引以及您可以更改的某些变量的递增方向:

players_list = range(1, players+1) # not actually a list in Python 3, but that doesn't matter
player_index = 0
player_direction = 1 # going forwards in the list, to start

while True:
    current_player = players_list[player_index]

    # do game stuff here with current_player

    if game_over:
        break

    if reverse:
        player_direction = -player_direction

    players_index = (players_index + player_direction) % players # update for next index

您还可以将一些逻辑放到生成器函数中。这样就可以封装稍微混乱的循环和反转逻辑,并且主循环代码就是for player in player_gen()。唯一棘手的事情是弄清楚如何让游戏逻辑告诉生成器何时反转(以及何时退出)。如果生成器是某个类的方法(可能是Game类),那么使用属性或方法调用为您处理事情就很容易了(变量game_over可以是self.game_overplayer_direction的翻转可以是在reverse方法中)。你知道吗

相关问题 更多 >