老虎杠子鸡虫”游戏

作者 by 超米 / 2024-11-25 / 暂无评论 / 23 个足迹

import random # 包含random.randrange(start, stop)函数的模块
# 辅助函数
def name_to_number(name):
 if name == '虫子':
    return 0
 elif name == '鸡':
    return 1
 elif name == '老虎':
    return 2
 elif name == '杠子':
    return 3
 else:
    return -1

def number_to_name(number):
 if number == 0:
     return '虫子'
 elif number == 1:
    return '鸡'
 elif number == 2:
    return '老虎'
 elif number == 3:
    return '杠子'
 else:
    return '所喊无效!'

def shout_out(name):
 if name == '随机':
    return random.randrange(0, 4)
 else:
    return name_to_number(name)

def play_one_round(player1_name, player1_code, player2_name, player2_code, print_msg = True):
    if player1_code == player2_code:
        if print_msg:
             print("双方平局,再来一次!")
        return 0
    elif (player1_code - player2_code) % 4 == 1:
        if print_msg:
         print(player1_name + "获胜!")
         return 1
    else:
        if print_msg:
            print(player2_name + "获胜!")
        return 2

def result_probability():
    play_times = 0
    player1_win_times = 0
    player1_loss_times = 0
    tie_times = 0

    for i in range(4):
        player1_code = shout_out("随机")
        player2_code = shout_out("随机")
        result = play_one_round("甲", player1_code, "乙", player2_code, False)
        play_times += 1
        if result == 0:
            tie_times += 1
        elif result == 1:
         player1_win_times += 1
        else:
         player1_loss_times += 1

    player1_win_prob = player1_win_times / play_times
    tie_prob = tie_times / play_times
    player1_loss_prob = player1_loss_times / play_times
    print("")
    print("甲乙随机比赛"+str(play_times)+"次,验证对决结果的概率为:")
    print("甲方获胜的概率为:" + str(player1_win_prob))
    print("双方平局的概率为:" + str(tie_prob))
    print("甲方失败的概率为:" + str(player1_loss_prob))

# 以下为测试代码,请在你提交的程序中保留以下代码

# 测试name_to_number()函数
print(name_to_number('虫子'))
print(name_to_number('鸡'))
print(name_to_number('老虎'))
print(name_to_number('杠子'))
print(name_to_number('豹子'))

# 测试number_to_name()函数
print(number_to_name(0))
print(number_to_name(1))
print(number_to_name(2))
print(number_to_name(3))
print(number_to_name(10))

# 测试shout_out()函数
print(shout_out("随机"))
print(shout_out("虫子"))
print(shout_out("鸡"))
print(shout_out("老虎"))
print(shout_out("杠子"))
print(shout_out("棍子"))

# 测试play_one_round()函数
result1 = play_one_round("计算机", 1, "玩家", 1)
print(result1)
result2 = play_one_round("张太红", 2, "白涛", 3)
print(result2)
result3 = play_one_round("甲", 3, "乙", 1)
print(result3)
result4 = play_one_round("A", 2, "B", 1)
print(result4)
print(play_one_round("A", 4, "B", 1))
print(play_one_round("张太红", shout_out("随机"), "白涛", shout_out("随机")))
print(play_one_round("张太红", shout_out("老虎"), "白涛", shout_out("虫子")))
print(play_one_round("计算机", shout_out("随机"), "糊涂玩家", shout_out("豹子"), False))
print(play_one_round("计算机", shout_out("随机"), "糊涂玩家", shout_out("豹子")))

# 测试result_probability()函数
result_probability()

独特见解