石头数量不一致,nim game
Number of stones is inconsistent, nim game
问题是计算机拿走的石头数量与屏幕上显示的数量不同。
我知道这是因为该功能被重复了两次。但是我找不到一种方法来存储生成的随机数并将该数字用于打印和减去
[我也知道这可以在不使用函数的情况下完成,但这是必需的]
代码如下:
import random
stones = random.randint(15, 30)
turn = 0
while stones > 0:
if turn == 0:
def player_announce():
print('There are', stones, 'stones. How many would you like?', end=' ')
def invalid_entry():
print('Enter a number from 1-3.')
player_announce()
player_stones = int(input(''))
if player_stones > 3 or player_stones < 1:
invalid_entry()
else:
stones = stones - player_stones
turn = 1
else:
def draw_stones():
computer_stones = random.randint(1, 3)
return computer_stones
print('There are', stones, 'stones. The computer takes', draw_stones())
stones -= draw_stones()
turn = 0
if turn == 0:
print('The computer beats the player!')
else:
print('The player beats the computer!')
简单的答案是调用 draw_stones 一次并存储结果:
computers_stones = draw_stones()
print('There are', stones, 'stones. The computer takes', computers_stones)
stones -= computers_stones
一旦你开始工作,我建议你找人为你通读一遍,有很多地方你可以做得更好!
问题是计算机拿走的石头数量与屏幕上显示的数量不同。 我知道这是因为该功能被重复了两次。但是我找不到一种方法来存储生成的随机数并将该数字用于打印和减去 [我也知道这可以在不使用函数的情况下完成,但这是必需的]
代码如下:
import random
stones = random.randint(15, 30)
turn = 0
while stones > 0:
if turn == 0:
def player_announce():
print('There are', stones, 'stones. How many would you like?', end=' ')
def invalid_entry():
print('Enter a number from 1-3.')
player_announce()
player_stones = int(input(''))
if player_stones > 3 or player_stones < 1:
invalid_entry()
else:
stones = stones - player_stones
turn = 1
else:
def draw_stones():
computer_stones = random.randint(1, 3)
return computer_stones
print('There are', stones, 'stones. The computer takes', draw_stones())
stones -= draw_stones()
turn = 0
if turn == 0:
print('The computer beats the player!')
else:
print('The player beats the computer!')
简单的答案是调用 draw_stones 一次并存储结果:
computers_stones = draw_stones()
print('There are', stones, 'stones. The computer takes', computers_stones)
stones -= computers_stones
一旦你开始工作,我建议你找人为你通读一遍,有很多地方你可以做得更好!