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

如何修改粉丝猜测游戏Python代码,使正确选项固定为CompareA?

粉丝数量猜测游戏代码修改方案

需求:修改代码,让粉丝更多的账号(正确答案)始终处于CompareA位置,而非仅在猜对后替换账号位置。

修改思路

核心逻辑是每次生成两个不同的账号后,对比它们的粉丝数量,将粉丝数更多的账号固定赋值给accountA(即CompareA展示位),粉丝数更少的赋值给accountB(即AgainstB展示位),确保正确答案始终出现在CompareA位置。

修改后的完整代码

data = [
    {
        'name': 'Instagram',
        'follower_count': 346,
        'description': '社交媒体平台',
        'country': '美国'
    },
    {
        'name': '克里斯蒂亚诺·罗纳尔多',
        'follower_count': 215,
        'description': '足球运动员',
        'country': '葡萄牙'
    },
    {
        'name': '爱莉安娜·格兰德',
        'follower_count': 183,
        'description': '歌手兼演员',
        'country': '美国'
    },
    {
        'name': '道恩·强森',
        'follower_count': 181,
        'description': '演员兼职业摔跤手',
        'country': '美国'
    },
    {
        'name': '赛琳娜·戈麦斯',
        'follower_count': 174,
        'description': '歌手兼演员',
        'country': '美国'
    },
    {
        'name': '凯莉·詹娜',
        'follower_count': 172,
        'description': '真人秀明星、企业家,白手起家亿万富翁',
        'country': '美国'
    },
    {
        'name': '金·卡戴珊',
        'follower_count': 167,
        'description': '真人秀明星、企业家',
        'country': '美国'
    }
]

import random
score = 0

def account_format(account):
    """将账号信息格式化为可打印字符串:名称、描述、国家"""
    account_name = account["name"]
    account_description = account["description"]
    account_country = account["country"]
    return f"{account_name},来自{account_country}的{account_description}"

def check_followers(guess):
    """判断用户猜测是否正确,正确返回True,错误返回False"""
    # 因CompareA固定为粉丝更多的账号,仅需判断是否选'a'
    return guess == "a"

end_of_game = False
# 初始化第一个CompareA账号
accountA = random.choice(data)

while not end_of_game:
    # 随机生成AgainstB账号,确保与CompareA不重复
    accountB = random.choice(data)
    while accountA == accountB:
        accountB = random.choice(data)
    
    # 强制CompareA为粉丝更多的账号
    if accountB["follower_count"] > accountA["follower_count"]:
        accountA, accountB = accountB, accountA

    print(f"CompareA: {account_format(accountA)}。")
    print(f"AgainstB: {account_format(accountB)}。")

    guess = input("谁的粉丝更多?输入'a'或'b':").lower()

    is_correct = check_followers(guess)
    if is_correct:
        score += 1
        print(f"答对了!当前得分:{score}")
    else:
        end_of_game = True
        print(f"答错了,最终得分:{score}")

关键修改点

  1. 内容本地化:将所有账号的名称、描述、国家翻译成中文,适配中文使用场景。
  2. 固定正确答案位置:每次生成accountB后,对比两者粉丝数,若accountB粉丝更多则交换账号,确保accountA始终是粉丝多的一方。
  3. 简化判断逻辑:因为CompareA固定为正确答案,判断函数只需验证用户是否选择a即可,无需重复对比粉丝数。
  4. 修复初始化bug:原代码第一次循环时未初始化accountB就赋值给accountA,修改后先初始化accountA,再在循环内生成accountB,避免运行报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 03:25:23