如何在玩家之间进行循环功能切换?

2024-04-20 12:16:47 发布

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

我正在尝试用python编写一个蛇和梯子的游戏,而我让玩家沿着棋盘移动的功能似乎不起作用。 我需要让我的函数循环一次又一次,直到游戏赢了,但我不知道如何让它用new_pos值代替current_pos值重新启动函数。另外,当我尝试运行它时,它说current_pos没有定义

理想情况下,我需要在整个游戏中在player_oneplayer_two之间切换的函数。有人建议使用我编写的函数player_turns,但我不知道如何将其实际合并到代码中

import time
import random
def roll_dice():
    dice_value = random.randint(1,6)
    print("Its a..." + str(dice_value))
    return dice_value


player_one = input("What is your name Player One?" + "\n")
player_two = input("What is your name Player Two?" + "\n")
print("\n" + str(player_one) + " Vs " + str(player_two) + "\n" + "Let's Play!")


def player_turns(total_turns):
    if total_turns % 2 == 0:
        total_turns += 1
        return player_one

    else:
        return player_two

def move_player(player):
    snake_squares = {26: 17, 40: 9, 43: 24, 67: 25, 75: 57, 82: 71, 98: 80}
    ladder_squares = {10: 40, 16: 38, 37: 46, 41: 52, 50: 68, 53: 73, 87: 97}
    print("Your turn, " + str(player))
    input(str(player) + " , type 'roll' to roll the dice" + "\n")
    obtained_dice = roll_dice()
    new_pos = current_pos + obtained_dice
    print(str(player) + ", move to space " + str(new_pos))

    if new_pos < 100:
        if new_pos in snake_squares:
            print("Oh no! you have landed on a snake!" + "\n" + "You fall down the snake and land back on square {0}". format(snake_squares[new_pos]))
            new_pos = snake_squares[new_pos]
            return new_pos

        elif new_pos in ladder_squares:
            print("Hurray, you have landed on a ladder!" + "\n" + "Climb the ladder and move to square number {0}". format(ladder_squares[new_pos]))
            new_pos = ladder_squares[new_pos]
            return new_pos

    elif new_pos >= 100:
            print("Congratulations, " + str(player) + "!" + "\n" + "You win!")
             print("Hope you enjoyed the game!")


Tags: 函数posnewreturndiceoneplayerprint
1条回答
网友
1楼 · 发布于 2024-04-20 12:16:47

您可以稍微重新构造代码:

  • 您需要在每次移动一名玩家时增加回合数,而不仅仅是当玩家1移动时(或者当回合%2==0时)
  • 如果使用整数模2,则得到正确的播放机,它给出0或1
  • 你需要一个无休止的循环,如果你的游戏结束了,循环就会中断
  • 您可以使用模2数字索引到属于玩家的2个值的列表中,例如玩家的姓名和在棋盘上的位置

总而言之,它可能是这样的:

import random 


one = input("What is your name Player One?\n")
two = input("What is your name Player Two?\n")

round = 0

# store the position and names in a list, access it by round%2 to get correct name/pos
player_pos = [0, 0]
player_names = [one, two]

snake_squares = {26: 17, 40: 9, 43: 24, 67: 25, 75: 57, 82: 71, 98: 80}
ladder_squares = {10: 40, 16: 38, 37: 46, 41: 52, 50: 68, 53: 73, 87: 97}

print(f"\n{one} Vs. {two}\nLet us Play!\n")

# some convenience methods that give you the current name and pos based on round
def who_pos():
    return player_pos[round % 2]

def who_name():
    return player_names[round % 2]

def roll_dice():
    dice_value = random.randint(1,6)
    print(f"{who_name()}: You rolled a {dice_value}")
    return dice_value 

# set the new position, names do not change so no setter for that
def set_pos(new_pos):
    player_pos[round % 2] = new_pos

def move_player(automatic = False):
    """Moves the player around which turn it is. Use automatic = True to autoplay. 
    Returns True if game continues.
    Returns False if game ended."""

    what = ""

    # on automatic, don't ask, simply roll
    while what != "roll" and not automatic:
        what = input(f"{who_name()}, type 'roll' to roll the dice\n").lower().strip()

    new_pos = who_pos() + roll_dice()
    print(f"{who_name()} moves to space {new_pos}")

    if new_pos < 100:
        if new_pos in snake_squares:
            new_pos = snake_squares[new_pos]
            print("Oh no! you have landed on a snake!\n" + 
                  f"You fall down the snake and land back on square {new_pos}")

        elif new_pos in ladder_squares: 
            new_pos = ladder_squares[new_pos]
            print("Hurray, you have landed on a ladder!\n" + 
                  f"Climb the ladder and move to square number {new_pos}")

    elif new_pos >= 100:
        print(f"Congratulations, {who_name()}!\nYou win!")
        print("Hope you enjoyed the game!")
        return False

    set_pos(new_pos)
    return True

# endless loop until move_player returns False, then it breaks and game is over
while True:
    if move_player(automatic=True):
        # switching between players happens because of the increase here
        # and the usage of %2 so it flipps between 0 and 1 all the time
        # and references player_pos and player_names lists above
        round += 1
    else:
        break

输出:

What is your name Player One?
P1
What is your name Player Two?
P2

P1 Vs. P2
Let us Play!

P1: You rolled a 5
P1 moves to space 5
P2: You rolled a 5
P2 moves to space 5
P1: You rolled a 1
P1 moves to space 6
P2: You rolled a 5
P2 moves to space 10
Hurray, you have landed on a ladder!
Climb the ladder and move to square number 40
P1: You rolled a 1
P1 moves to space 7
P2: You rolled a 1
P2 moves to space 41
Hurray, you have landed on a ladder!
Climb the ladder and move to square number 52
P1: You rolled a 3
P1 moves to space 10
Hurray, you have landed on a ladder!
Climb the ladder and move to square number 40
P2: You rolled a 3
P2 moves to space 55
P1: You rolled a 4
P1 moves to space 44
P2: You rolled a 3
P2 moves to space 58
P1: You rolled a 6
P1 moves to space 50
Hurray, you have landed on a ladder!
Climb the ladder and move to square number 68
P2: You rolled a 5
P2 moves to space 63
P1: You rolled a 6
P1 moves to space 74
P2: You rolled a 6
P2 moves to space 69
P1: You rolled a 2
P1 moves to space 76
P2: You rolled a 5
P2 moves to space 74
P1: You rolled a 1
P1 moves to space 77
P2: You rolled a 5
P2 moves to space 79
P1: You rolled a 6
P1 moves to space 83
P2: You rolled a 1
P2 moves to space 80
P1: You rolled a 6
P1 moves to space 89
P2: You rolled a 6
P2 moves to space 86
P1: You rolled a 3
P1 moves to space 92
P2: You rolled a 6
P2 moves to space 92
P1: You rolled a 4
P1 moves to space 96
P2: You rolled a 6
P2 moves to space 98
Oh no! you have landed on a snake!
You fall down the snake and land back on square 80
P1: You rolled a 1
P1 moves to space 97 
P2: You rolled a 6
P2 moves to space 86
P1: You rolled a 6
P1 moves to space 103
Congratulations, P1!

You win!
Hope you enjoyed the game!

相关问题 更多 >