我试着在周末学习Python,在获得了一些知识之后,我决定制作一个小石头剪刀游戏。我很感谢你对我如何改进我的代码的意见。所有反馈都是非常感谢的。
import random
def round_winner(choice):
ai_chosen = str(random.randint(1, 3))
print(f'AI chose {ai_chosen}')
if choice == '1' and ai_chosen == '2':
return 'ai'
elif choice == '2' and ai_chosen == '3':
return 'ai'
elif choice == '3' and ai_chosen == '1':
return 'ai'
elif choice == ai_chosen:
return 'tie'
else:
return 'player'
def display_round_winner(winner):
if winner == 'tie':
print('This round is tied!')
else:
print(f'The winner this round is the {winner.upper()}')
print(f'''
Current points as follows:
Player: {counter['player']}
AI: {counter['ai']}
Rounds Tied: {counter['tie']}
''')
def score_checker():
global game_ongoing
for key, value in counter.items():
if value == 2:
print(f'{key.upper()} wins the game!')
game_ongoing = False
def initializer():
global counter
message = '''
Please choose one of the following:
1: Rock
2: Paper
3: Scissors
'''
print(message)
choice_of_obj = input('What will it be: ')
if choice_of_obj in ['1', '2', '3']:
winner = round_winner(choice_of_obj)
counter[winner] += 1
display_round_winner(winner)
score_checker()
else:
print('Out of bounds')
counter = {
'player': 0,
'ai': 0,
'tie': 0
}
game_ongoing = True
while game_ongoing:
initializer()发布于 2019-03-19 03:54:58
你要求玩家输入1,2或3的岩石,纸或剪刀。当你告诉玩家AI的选择时,你会说它是1,2或3。如果你说出他们的选择,那就更友好了。您可以使用字典将缩写的选项转换为实际项来完成此操作。
choices = { '1': 'Rock', '2': 'Paper', '3': 'Scissors' }
def round_winner(choice):
ai_chosen = ...
print(f'AI chose {choice[ai_chosen]}')
...此外,您也可以使用该字典打印出播放器的菜单,而不是硬编码它:
print('Please choose one of the following:')
for choice, item in choices:
print(f'{choice}: {item}')您正在使用“ai”、“player”和“tie”作为您的计数器字典的键,并在打印出赢家时始终打印出winner.upper()。您可以使用“AI”、“PLAYER”和“TIE”作为字典键,从而避免了对.upper()调用的需要。
score_checker是个奇怪的名字。也许编程最难的事情之一就是想出好名字。check_for_game_winner可能会更好。
使用global几乎总是不好的。您只需要将一个true/false值传递给调用方,以指示游戏是否结束。使用返回语句。在if value == 2:内部,添加一个return True语句。
initializer是另一个可怕的名字。play_round会更好。
在play_round中检查总赢家是令人费解的责任。如果有的话,play_round函数不知道它是在循环中调用的。它应该从这里移除。
global counter又是个坏主意。您可以简单地将counter作为参数传递进来。
与其直接运行游戏代码,不如添加一个play_games函数,并在其中移动计数器初始化代码和循环。通过以上的其他更改,它可能如下所示:
def play_games():
counter = { 'PLAYER': 0, 'AI':0, 'TIE': 0}
while True:
play_round(counter)
if check_for_game_winner(counter):
break只有当文件是主程序时,文件才应该执行代码。如果将该文件导入到另一个文件中,则不希望代码自动运行。以下护卫通常用于此:
if __name__ == '__main__':
play_game()你把玩家的动作和AI的动作存储为字符串的模型可能不是最好的。如果你使用整数,你可以用模块化的算术来执行岩石拍剪刀拍纸拍岩石的测试:
if ai_choice % 3 == (choice + 1) % 3:
# the AI wonhttps://codereview.stackexchange.com/questions/215714
复制相似问题