📜  一系列剪刀石头布游戏中每位玩家的获胜次数(1)

📅  最后修改于: 2023-12-03 15:06:10.195000             🧑  作者: Mango

一系列剪刀石头布游戏中每位玩家的获胜次数

这个程序用于记录一系列剪刀石头布游戏中每位玩家的获胜次数。

功能
  • 输入玩家数量和游戏轮数
  • 输出每位玩家的获胜次数和胜率
使用方法
  1. 安装Python
  2. 下载并解压本程序
  3. 打开命令行工具,如Terminal或Command Prompt
  4. 进入程序文件所在目录
  5. 运行程序:python rock_paper_scissors.py
输入说明

输入格式为两个整数,以空格分隔,分别表示玩家数量和游戏轮数。

示例输入:3 5

输出说明

输出格式为一个表格,包括每位玩家的获胜次数和胜率。

示例输出:

| 玩家 | 获胜次数 | 胜率 |
|------|----------|------|
| 1    | 2        | 40%  |
| 2    | 1        | 20%  |
| 3    | 2        | 40%  |
代码片段
import random
from collections import defaultdict

def play_round(players):
    choices = ['rock', 'paper', 'scissors']
    for player in players:
        player.choice = random.choice(choices)

    winners = []
    for choice in choices:
        winners.extend([player for player in players if player.choice == choice and player not in winners])

    for winner in winners:
        winner.score += 1

def play_game(num_players, num_rounds):
    players = [Player(i) for i in range(1, num_players+1)]
    for i in range(num_rounds):
        play_round(players)

    return players

class Player:
    def __init__(self, number):
        self.number = number
        self.score = 0
        self.choice = None

    def __repr__(self):
        return f'Player {self.number}'

def print_results(players):
    print('| 玩家 | 获胜次数 | 胜率 |')
    print('|------|----------|------|')
    total_score = sum([player.score for player in players])
    for player in players:
        print(f'| {player.number} | {player.score} | {int(player.score/total_score*100)}% |')

if __name__ == '__main__':
    num_players, num_rounds = [int(x) for x in input().split()]
    players = play_game(num_players, num_rounds)
    print_results(players)

以上是本程序的主要代码。程序采用了面向对象的思路,定义了一个Player类来记录每个玩家的相关信息,然后编写了play_roundplay_game函数来实现游戏的逻辑。print_results函数用于格式化输出游戏结果。在main函数部分,读取用户输入并调用相关函数,最终输出结果。