如何让循环重复执行我的nims
# importing random module, for random choices
import random
# print_move function to display CPU and players current move
def print_move(current_player, row, stick_quantity):
current_player = current_player
if stick_quantity == 1:
print(f"{current_player} takes {stick_quantity} sticks from {row} row")
else:
print((f"{current_player} takes {stick_quantity} sticks from {row} row"))
# beginning of nims game, choosing who will choose
print("Welcome to Nim!")
name = input("Enter name: ")
current_player = random.choice([name, "CPU"])
print('game is starting',(current_player),'will be going first')
# create stick lists
sticks = [1, 3, 5, 7]
# looping the sticks
def nims():
for count, stick in enumerate(sticks):
print(count+1, stick * "|")
# loop that breaks when the number of sticks are less than 0
while sum(sticks) > 0:
nims()
if current_player == name:
# exception handling so that the user inputs the correct amount of sticks/rows
while True:
try:
row = int(input("Which row would you like to take sticks from? "))
stick_quantity = int(input("How many sticks would you like to take? "))
if 1 <= row <= len(sticks) and 1 <= stick_quantity <= sticks[row-1]:
break
else:
print("")
print("Invalid input, please enter a valid row, and or a valid amount of sticks")
except ValueError:
print("")
print("Invalid input, please enter a valid row, and or a valid amount of sticks")
sticks[row - 1] -= stick_quantity
print_move(current_player,row,stick_quantity)
if current_player == name:
current_player = "CPU"
else:
current_player = name
else:
# handling value error in the stick_quantity variable
try:
row = random.randint(1, len(sticks))
stick_quantity = random.randint(1, sticks[row-1])
sticks[row-1] -= stick_quantity
print_move(current_player,row,stick_quantity)
if current_player == "CPU":
current_player = name
else:
current_player = "CPU"
except ValueError:
print("")
winner = current_player
print("Winner is", winner)
我在Python中创建了一个Nims游戏,整体运行得很好,但我在循环重复这部分遇到了一些问题。我想在游戏结束后,宣布获胜者,然后问玩家是否想再玩一次。如果玩家输入'y',那么Nims游戏就会重新开始;如果玩家按'n'或者其他任何键,游戏就结束,并显示玩家的胜负记录。
我不太确定是不是应该在Nims游戏开始时就用一个类似于While play_again == 'y':的循环。我试过这样做,但似乎不太奏效。我还尝试了其他方法,但到目前为止,它们都没有很好地解决问题。任何帮助或指导都将非常感谢。提前谢谢你们。
1 个回答
0
你可以试试这样的做法:
print("Welcome to Nim!")
name = input("Enter name: ")
replay = 'y'
while replay == 'y':
然后在游戏结束的时候:
winner = current_player print("Winner is", winner)
replay = str(input("One more round (y/n)?"))