如何让CPU在这个python nims游戏中选择合适数量的棋子

0 投票
2 回答
40 浏览
提问于 2025-04-12 18:33
import random

def print_move(current_player,row,stick_quantity):
  current_player = current_player
  print(f"{current_player} takes {stick_quantity} sticks from {row} row")

 
sticks = [1, 3, 5, 7]

def nims():
  for count, stick in enumerate(sticks):
    print(count+1,stick * "|")


print("Welcome to Nim!")
name = input("Enter name: ")
current_player = random.choice([name, "CPU"])
print('game is starting',(current_player),'will be going first')
 
while True:
  if current_player == name:
    row = int(input("Which row would you like to take sticks from? "))
    stick_quantity = int(input("How many sticks would you like to take? "))
    sticks[row - 1] -= stick_quantity    
    print_move(current_player,row,stick_quantity)
    if current_player == name:
      current_player = "CPU"
    else:
      current_player = name
  
  elif current_player == "CPU":
    row = random.choice([1,2,3,4])
    stick_quantity = random.choice([1,2,3,4,5,6,7])
    sticks[row - 1] -= stick_quantity
    print_move(current_player,row,stick_quantity)
    if current_player == "CPU":
      current_player = name
    else:
      current_player = "CPU"


  nims()

在我创建的尼姆游戏中,我设计了一个CPU,它可以从某一行中移除一定数量的木棍。我让这个选择是随机的,但我遇到了一个问题:CPU有时会选择从已经没有木棍的行中拿走很多木棍。我希望CPU只能拿走合适数量的木棍,如果它试图从没有木棍的行中拿走过多的木棍,我想要一个循环,让它一直尝试,直到它拿走合适数量的木棍。

2 个回答

0

你可以为CPU添加一个控制功能,这样它就能检查在选定的行中是否有足够的木棍。如果没有足够的木棍,CPU就应该选择另一行,或者选择更少的木棍。

简单来说,CPU的行为可以设计成这样:

def cpu_turn():
    while True:
        row = random.randint(1, len(sticks))
        if sticks[row - 1] > 0:
            max_sticks = min(sticks[row - 1], 7)  # Maximum sticks CPU can take
            stick_quantity = random.randint(1, max_sticks)
            sticks[row - 1] -= stick_quantity
            print_move(current_player, row, stick_quantity)
            break

然后:

elif current_player == "CPU":
   cpu_turn()
   if current_player == "CPU":
      current_player = name
   else:
      current_player = "CPU"

1

我想要一个循环,直到CPU处理适量的任务为止。

虽然你的计划可能不太合理,但我们就这样做吧。

...
  elif current_player == "CPU":
    # We may try infinitely until we have a good luck.
    while True:
      # Just roll the dice.
      row = random.choice([1,2,3,4])
      stick_quantity = random.choice([1,2,3,4,5,6,7])

      # When we finally have a valid `stick_quantity`,
      # exit the loop to continue.
      if stick_quantity <= sticks[row - 1]:
        break

    sticks[row - 1] -= stick_quantity
...

请注意,还有更好的方法来确保生成的数字是有效的。例如——

...
    # Choose a row which is not empty.
    row = random.choice(
      [
        i + 1
        for i, quantity in enumerate(sticks) 
        if quantity > 0
      ]
    )
    # Choose a quantity that does not exceed maximum.
    stick_quantity = random.randint(0, sticks[row - 1]) + 1
...

撰写回答