这是我代码的一部分。
if deplacement_result == "ok":
if self.current_player_color == "white":
self.current_player_color = "black"
else:
self.current_player_color = "white"
elif deplacement_result == "taking":
if self.damier.can_take_the_piece(target_position):
self.forced_source_position = target_position
else:
self.forced_source_position = None
self.have_to_take = False
if self.current_player_color == "white":
self.current_player_color = "black"
else:
self.current_player_color = "white"
我注意到我输入了两次验证码
if self.current_player_color == "white":
self.current_player_color = "black"
else:
self.current_player_color = "white"
如何避免重复自己
答案 0 :(得分:1)
您可以将其缩小为一行。
self.couleur_joueur_courant = "noir" if self.couleur_joueur_courant == "blanc" else "blanc"
答案 1 :(得分:1)
只是为了避免每个问题重复代码,
您可以使用标志变量。
switch_color = False
if deplacement_result == "ok":
switch_color = True
elif deplacement_result == "taking":
if self.damier.can_take_the_piece(target_position):
self.forced_source_position = target_position
else:
self.forced_source_position = None
self.have_to_take = False
switch_color = True
if switch_color:
if self.current_player_color == "white":
self.current_player_color = "black"
else:
self.current_player_color = "white"
switch_color = False
答案 2 :(得分:0)
如果要摆脱冗余,可以尝试使用此功能:
if resultat_deplacement == "ok" or resultat_deplacement == "prise":
# This code is executed in either case
if self.couleur_joueur_courant == "blanc":
self.couleur_joueur_courant = "noir"
else:
self.couleur_joueur_courant = "blanc"
if resultat_deplacement == "prise": # Only executes for the if this is True
if self.damier.piece_peut_faire_une_prise(position_cible):
self.position_source_forcee = position_cible
else:
self.position_source_forcee = None
self.doit_prendre = False
但是正如@chessguy指出的那样,它会重复两次if语句。
您可以尝试定义这样的函数(并根据需要转换为法语):
def setColour():
if self.couleur_joueur_courant == "blanc":
self.couleur_joueur_courant = "noir"
else:
self.couleur_joueur_courant = "blanc"
if resultat_deplacement == "ok":
setColour()
if resultat_deplacement == "prise": # Only executes for the if this is True
setColour()
if self.damier.piece_peut_faire_une_prise(position_cible):
self.position_source_forcee = position_cible
else:
self.position_source_forcee = None
self.doit_prendre = False
答案 3 :(得分:0)
在您的代码中,不需要scores
部分,因为它会重新初始化为相同的字符串。仅以下代码就足够了:
"(?=Wild pitch)*(?=scores).*"
代替此:
else
或者,您可以使用一个衬纸:
if self.current_player_color == "white":
self.current_player_color = "black"