这是我在2个玩家之间进行游戏的代码,其中2个骰子已经滚动,第一个玩家获得50或者超过50。但不是这样,输出是分数的无限打印而不实际更新。我知道错误可能是我将Apos和Bpos设置为1的地方,但我不知道其他任何解决方法。
from itertools import cycle
import random
def turn_control():
for current_player in cycle(["A", "B"]):
play_game(current_player)
def play_game(current_player):
Apos = 1
Bpos = 1
if current_player == "A":
number1 = random.randint(1,6)
number2 = random.randint(1,6)
add = number1 + number2
Apos = Apos + add
print("Player A position: ", Apos)
if Apos >= 50:
print(current_player, " wins")
elif current_player == "B":
number1 = random.randint(1,6)
number2 = random.randint(1,6)
add = number1 + number2
Bpos = Bpos + add
print("Player B position: ", Bpos)
if Bpos >= 50:
print(current_player, " wins")
turn_control()
答案 0 :(得分:0)
Apos
和Bpos
是函数play_game
的局部变量,因此在每次调用play_game
后都会被丢弃并重置。
你需要使它们成为全局变量(用global
关键字作为声明前缀并在函数外单独初始化它们),或者在turn_control
中创建某种状态对象然后传递给每个变量调用play_game
以便更新。
global
路线可能更容易,但状态对象对于专业编程更具可持续性/可测试性/可重用性。
global
示例foo = 1
def increment_and_print():
global foo
foo += 1
print(foo)
increment_and_print() # prints '2'
increment_and_print() # prints '3'
def repeatedly_increment_and_print():
foo_state = {'foo': 1}
increment_and_print(foo_state)
increment_and_print(foo_state)
def increment_and_print(foo_state):
foo_state['foo'] += 1
print(foo_state['foo'])
repeatedly_increment_and_print() # prints '2', then '3'
答案 1 :(得分:0)
您需要进行此更改
from itertools import cycle
import random
Apos = 1
Bpos = 1
def turn_control():
for current_player in cycle(["A", "B"]):
play_game(current_player)
def play_game(current_player):
global Apos
global Bpos
if current_player == "A":
number1 = random.randint(1,6)
number2 = random.randint(1,6)
add = number1 + number2
Apos = Apos + add
print("Player A position: ", Apos)
if Apos >= 50:
print(current_player, " wins")
quit()
elif current_player == "B":
number1 = random.randint(1,6)
number2 = random.randint(1,6)
add = number1 + number2
Bpos = Bpos + add
print("Player B position: ", Bpos)
if Bpos >= 50:
print(current_player, " wins")
quit()
turn_control()