python代码怎么用类编写剪刀石头布

发布时间:2021-06-12 16:47:21 作者:小新
来源:亿速云 阅读:326
# Python代码怎么用类编写剪刀石头布

在Python中,使用面向对象编程(OOP)的类可以优雅地实现剪刀石头布游戏。下面通过一个完整示例演示如何用类封装游戏逻辑:

```python
import random

class RockPaperScissors:
    def __init__(self):
        self.choices = ['石头', '剪刀', '布']
        self.rules = {
            ('石头', '剪刀'): '石头',
            ('剪刀', '布'): '剪刀',
            ('布', '石头'): '布'
        }
    
    def get_computer_choice(self):
        return random.choice(self.choices)
    
    def determine_winner(self, user_choice, computer_choice):
        if user_choice == computer_choice:
            return "平局!"
        winner = self.rules.get((user_choice, computer_choice)) or \
                 self.rules.get((computer_choice, user_choice))
        return "你赢了!" if winner == user_choice else "电脑赢了!"
    
    def play(self):
        print("游戏开始!输入石头/剪刀/布或q退出")
        while True:
            user_input = input("你的选择:").strip()
            if user_input == 'q':
                break
            if user_input not in self.choices:
                print("无效输入,请重试")
                continue
            
            computer_choice = self.get_computer_choice()
            print(f"电脑选择:{computer_choice}")
            print(self.determine_winner(user_input, computer_choice))

# 运行游戏
if __name__ == "__main__":
    game = RockPaperScissors()
    game.play()

代码解析

  1. 类结构

    • __init__初始化游戏选项和胜负规则字典
    • get_computer_choice生成随机电脑选择
    • determine_winner根据规则字典判断胜负
    • play方法处理游戏主循环
  2. 优势

    • 将游戏状态和逻辑封装在类中
    • 规则字典使胜负判断更清晰
    • 易于扩展(如增加”蜥蜴”“史波克”等选项)
  3. 使用方法: 直接实例化类并调用play()方法即可开始游戏,输入q可随时退出。

这种面向对象的实现方式比过程式代码更易维护和扩展,适合作为学习Python类的基础练习项目。 “`

推荐阅读:
  1. Python之石头剪刀布
  2. 如何用python写剪刀石头布

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python

上一篇:怎么用python编辑 一个偶数总能表示为两个素数之和

下一篇:使用 Python 怎么实现自动交易加密货币

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》