-1
當我運行我的遊戲功能我得到這個錯誤之前定義的:UnboundLocalError:說變量沒有被使用
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "hog.py", line 162, in play
if is_swap(score0,score1)== True and who == 0:
File "hog.py", line 121, in is_swap
elif swap1 == score0:
UnboundLocalError: local variable 'swap1' referenced before assignment
下面是錯誤引用的兩個功能(第一父,然後子功能) :
def play(strategy0, strategy1, score0=0, score1=0, goal=GOAL_SCORE):
"""Simulate a game and return the final scores of both players, with
Player 0's score first, and Player 1's score second.
A strategy is a function that takes two total scores as arguments
(the current player's score, and the opponent's score), and returns a
number of dice that the current player will roll this turn.
strategy0: The strategy function for Player 0, who plays first
strategy1: The strategy function for Player 1, who plays second
score0 : The starting score for Player 0
score1 : The starting score for Player 1
"""
who = 0 # Which player is about to take a turn, 0 (first) or 1 (second)
# BEGIN Question 5
while score0 <= goal and score1 <= goal:
#Palyerx Turn
if who == 0:
score0 += take_turn(strategy0(score0,score1), score1, select_dice(score0,score1))
elif who == 1:
score1 += take_turn(strategy1(score1,score0), score0, select_dice(score1,score0))
print(score0,score1)
#Swine Swap
if is_swap(score0,score1)== True and who == 0:
temp = score0
score0 = score1
score1 = temp
elif is_swap(score1,score0) == True and who == 1:
temp = score1
score1 = score0
score0 = temp
who = other(who)
# END Question 5
return score0, score1
def is_swap(score0, score1):
"""Return True if ending a turn with SCORE0 and SCORE1 will result in a
swap.
Swaps occur when the last two digits of the first score are the reverse
of the last two digits of the second score.
"""
# BEGIN Question 4
#If scores are equal there is no need to flip
if score0 == score1:
return True
#Flipping Score0
if score0 >= 10 and score0 < 100:
s0String = str(score0)
x = s0String[0]
y = s0String[1]
swap0 = int(y+x)
elif score0 < 10:
x = '0'
y = str(score0)
swap0 = int(y+x)
elif score0 > 100:
s0String = str(score0)
x = s0String[0]
y = s0String[1]
z = s0String[2]
swap0 = int(z+y)
#Flipping Score1
if score1 >= 10 and score1 < 100:
s1String = str(score1)
i = s1String[0]
j = s1String[1]
swap1 = int(j+i)
elif score1 < 10:
i = '0'
j = str(score1)
swap1 = int(j+i)
elif score1 > 100:
s1String = str(score1)
i = s1String[0]
j = s1String[1]
f = s1String[2]
swap1 = int(f+j)
#Swapping Scores Bases on Flipped equivelence
if swap0 == score1:
return True
elif swap1 == score0:
return True
else:
return False
我不確定它想要什麼。因爲swap0在swap函數中被使用之前是defiend,並且它在播放中被正確調用。
因爲不管條件已設置的初始分配'swap1'沒有發生。因此,當它到達引發錯誤的行時:'swap1 == score0','swap1'從未被聲明並分配一個值。您需要修改您的條件語句以確保它們按預期行事。 – idjaw