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()
在我创建的 nims 游戏中,我创建了一个 CPU,它可以从一定数量的行中移除一定数量的木棍。我已经做到了这一点,所以它是一个随机选择,但我遇到了这个问题,CPU 将决定从棍棒已经消失的行中取出大量棍棒。我希望CPU只能获取适量的木棍,并且如果CPU从一行中移除大量的木棍,而木棍不在那里,我想要一个循环,直到CPU占用适量的木棍。
您可以添加 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"