Python小游戏4——石头剪刀布

  • 代码

import random

def get_computer_choice():
    choices = ['石头', '剪刀', '布']
    return random.choice(choices)

def get_user_choice():
    user_input = input("\n请输入你的选择(石头、剪刀、布):")
    while user_input not in ['石头', '剪刀', '布']:
        print("无效输入,请重新输入。")
        user_input = input("\n请输入你的选择(石头、剪刀、布):")
    return user_input

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 play_rock_paper_scissors():
    print("欢迎来到石头剪刀布游戏!")
    
    while True:
        user_choice = get_user_choice()
        computer_choice = get_computer_choice()
        
        print("\n你选择了:{}".format(user_choice))
        print("计算机选择了:{}".format(computer_choice))
        
        result = determine_winner(user_choice, computer_choice)
        print(result)
        
        play_again = input("\n你想再玩一次吗?(y/n):").strip().lower()
        if play_again != 'y':
            break

    print("游戏结束,感谢你的参与!")

# 开始游戏
play_rock_paper_scissors()

知识点总结

一、基础语法
变量与数据类型:
游戏中使用了字符串(如`'石头'`、`'剪刀'`、`'布'`)来存储用户和计算机的选择。
使用了布尔值(如`True`、`False`)来控制游戏循环。
输入与输出:
使用`input()`函数获取用户输入。
使用`print()`函数输出游戏信息、用户选择、计算机选择以及游戏结果。
条件语句:
使用`if`、`elif`和`else`语句来判断用户输入是否有效,以及确定游戏结果。
循环语句:
使用`while`循环来重复游戏,直到用户选择不再玩为止。
在用户输入验证中,也使用了`while`循环来确保输入有效。
二、函数与模块
函数定义与调用:
定义了多个函数(如`get_computer_choice()`、`get_user_choice()`、`determine_winner()`和`play_rock_paper_scissors()`)来组织代码,提高可读性和可维护性。
在主程序中调用这些函数来执行游戏逻辑。
随机模块:
使用`random`模块中的`choice()`函数来生成计算机的随机选择。
三、逻辑与算法
用户输入验证:
通过循环和条件语句来验证用户输入是否有效,确保游戏能够正确进行。
游戏结果判定:
使用条件语句来比较用户和计算机的选择,确定游戏结果(赢、输或平局)。
游戏循环控制:
使用`while`循环来控制游戏的重复进行,直到用户选择退出。
四、用户体验与交互
友好的用户提示:
在游戏过程中,通过输出提示信息来引导用户进行输入和操作。
游戏结束提示:
在用户选择退出游戏后,输出感谢信息,提升用户体验。
五、扩展与改进
增加游戏难度:
可以考虑增加计算机的选择策略,使其更加智能和难以预测。
记录游戏成绩:
可以添加功能来记录用户的赢、输和平局次数,并在游戏结束时显示。
图形化界面:
可以使用图形化编程库(如Tkinter)来创建更加直观和友好的用户界面。
网络对战:
可以考虑将游戏扩展到网络上,允许用户与远程玩家进行对战。

猜你喜欢

转载自blog.csdn.net/cxh666888_/article/details/142945920