You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现石头剪刀布游戏:如何优化冗长的if-else语句?

优化石头剪刀布游戏的几种优雅实现

嘿,作为Python新手能写出石头剪刀布游戏已经很赞啦!你提到的超长if-else确实可以用更简洁、易维护的方式替代,下面分享几种实用的优化思路:

方法1:用字典映射胜负规则

我们可以把所有胜负关系提前存在字典里,直接通过键值对快速判断结果,代码会清爽很多:

import random

options = ["rock", "paper", "scissors"]
# 定义胜负映射:key是玩家出的选项,value是它能击败的电脑选项
win_conditions = {
    "rock": "scissors",
    "paper": "rock",
    "scissors": "paper"
}

played_hand = input("Play rock, paper or scissors please: ").lower()
computer_hand = random.choice(options)  # 用random.choice替代手动计算索引,更简洁

if played_hand not in options:
    print("Invalid input! Please choose rock, paper or scissors.")
else:
    print(f"The computer played {computer_hand}.")
    if played_hand == computer_hand:
        print("It's a tie!")
    elif win_conditions[played_hand] == computer_hand:
        print("You win!")
    else:
        print("You lose!")

这种方式的好处是规则清晰易维护,以后要改规则或者扩展选项(比如加lizard、spock),只需要修改字典就行,不用堆一堆if-else。

方法2:利用索引计算胜负

石头剪刀布的胜负是循环克制的,我们可以通过选项的索引来计算:

  • 玩家索引 - 电脑索引 的结果如果是1或者-2,玩家赢
  • 如果是0,平局
  • 其他情况玩家输

代码示例:

import random

options = ["rock", "paper", "scissors"]
played_hand = input("Play rock, paper or scissors please: ").lower()

if played_hand not in options:
    print("Invalid input! Please choose rock, paper or scissors.")
else:
    player_idx = options.index(played_hand)
    computer_idx = random.randint(0, 2)
    computer_hand = options[computer_idx]
    
    print(f"The computer played {computer_hand}.")
    if player_idx == computer_idx:
        print("It's a tie!")
    elif (player_idx - computer_idx) % 3 == 1:
        print("You win!")
    else:
        print("You lose!")

这种方式利用了数学规律,代码更简洁,不需要额外维护规则字典,特别适合这种有循环克制关系的游戏。

方法3:使用枚举类(进阶版)

如果想让代码更具可读性和规范性,可以用Python的enum模块定义枚举类,把每个选项和对应的克制关系绑定:

import random
from enum import Enum

class Hand(Enum):
    ROCK = ("rock", "scissors")
    PAPER = ("paper", "rock")
    SCISSORS = ("scissors", "paper")
    
    def __init__(self, name, beats):
        self.name = name
        self.beats = beats

# 把枚举转换为方便查找的字典
hand_map = {hand.name: hand for hand in Hand}

played_hand_name = input("Play rock, paper or scissors please: ").lower()

if played_hand_name not in hand_map:
    print("Invalid input! Please choose rock, paper or scissors.")
else:
    player_hand = hand_map[played_hand_name]
    computer_hand = random.choice(list(Hand))
    
    print(f"The computer played {computer_hand.name}.")
    if player_hand == computer_hand:
        print("It's a tie!")
    elif computer_hand.name == player_hand.beats:
        print("You win!")
    else:
        print("You lose!")

这种方式适合想要代码更严谨、可扩展的场景,枚举类让每个选项的职责更清晰。

不管哪种方法,都比一堆嵌套的if-else要好维护得多,你可以根据自己的需求选择合适的方式~

内容的提问来源于stack exchange,提问作者mark olieman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:15:22