一起创业网-为互联网创业者服务

猜拳程序怎么无限运行

猜拳程序无限运行的方法主要依赖于循环结构,以下是一个简单的猜拳程序示例,使用Python编写,实现无限循环运行直到用户选择退出:

```python

import random

def get_user_choice():

while True:

user_input = input("请输入你要出的拳头(石头、剪刀、布)或输入'退出':")

if user_input.lower() == '退出':

return None

elif user_input in ['石头', '剪刀', '布']:

return user_input

else:

print("输入错误,请重新输入。")

def get_computer_choice():

return random.choice(['石头', '剪刀', '布'])

def determine_winner(user_choice, computer_choice):

if user_choice == computer_choice:

return '平局'

elif (user_choice == '石头' and computer_choice == '剪刀') or \

(user_choice == '剪刀' and computer_choice == '布') or \

(user_choice == '布' and computer_choice == '石头'):

return '你赢了'

else:

return '你输了'

def main():

player_score = 0

computer_score = 0

tie_count = 0

while True:

user_choice = get_user_choice()

if user_choice is None:

break

computer_choice = get_computer_choice()

print(f'你的选择:{user_choice},电脑的选择:{computer_choice}')

result = determine_winner(user_choice, computer_choice)

if result == '你赢了':

player_score += 1

elif result == '你输了':

computer_score += 1

else:

tie_count += 1

print(f'当前比分:你 {player_score} - 电脑 {computer_score} - 平局 {tie_count}')

play_again = input("再玩一次吗?(是/否):")

if play_again.lower() != '是':

break

if __name__ == "__main__":

main()

```

代码说明:

get_user_choice():

该函数用于获取用户的输入,如果用户输入“退出”,则返回`None`,否则返回用户输入的拳头类型。

get_computer_choice():

该函数用于生成电脑的随机选择。

determine_winner(user_choice, computer_choice):

该函数用于比较用户和电脑的选择,并返回比赛结果(平局、用户赢、电脑赢)。

main():

该函数是程序的主循环,不断循环直到用户选择退出。在每次循环中,程序会获取用户的输入,生成电脑的选择,比较结果,并更新比分。然后询问用户是否继续游戏。

通过这种方式,程序可以无限循环运行,直到用户选择退出。