我正在尝试编写一个竞争代码,该代码将获得竞争对手的列表,然后将随机决定他们必须在每轮中面对谁,循环风格而不会被淘汰。 wiki article about this type of competition
在每轮结束时,每场比赛的获胜者将获得一分。
当所有可能的战斗结束时,得分最多的人获胜。
但我遇到了一些麻烦,到目前为止我的代码是:
import itertools
# list of competitors (does not need to be even, in this case, 7)
# maybe this should be a dict with their wins and loses like:
# {'Andy': [2,['Bob','Charlie'],0,[]], ... }
# which means andy won 2 times, against bob and charlie, and lost 0 times
competitors = ['Andy', 'Bob', 'Charlie', 'Daniel', 'Eric', 'Ferdinand', 'Gabriel']
# the starting round number
round_number = 1
# holds the winner
winner = None
# start the competition
print "The competitors are: \n" + " ".join(competitors)
# round handler
def do_round():
#round notifier
print "Round " + str(round_number)
#here is the problem
matches = itertools.permutations(competitors,2)
for match in matches:
print match
# increase round number
round_number += 1
#return this rounds matches
return matches
# gets the winners of each round for each match
def get_winners(matches):
winners = []
for match in matches:
winners.append(raw_input("who won?: " + " or ".join(match)))
# decides if the games are over yet
def is_there_a_winner(winners):
# this function should know how to get every rounds winners and add their points
# and then decide if the game is over and there is a total winner
winner = ??
# main loop
while not winner:
matches = do_round()
get_winners(matches)
is_there_a_winner(winners)
编辑:很抱歉,在我出于某种原因编写此部分之前,问了这个问题。
我的问题是排列提供了所有可能的排列,我只是希望获得竞争对手的一轮排列,然后下次我运行它,以便能够引用他们已经与之抗争的人而不是那场比赛再次出现。
编辑2:我决定在帖子中添加“所需结果”。
我希望输出是这样的:
The competitors are:
Andy Bob Charlie Daniel Eric Ferdinand Gabriel
Round 1
Andy vs Bob
Charlie vs Daniel
Eric vs Ferdinand
Gabriel sits out
Round 1 Results:
Andy beat Bob
Charlie beat Daniel
Eric beat Ferdinand
Round 2
Andy vs Daniel
Bob vs Gabriel
Eric vs Charlie
Ferdinand sits out
... etc etc ... until at the end the winner (highest score) is revealed.
答案 0 :(得分:1)
我在这里找到了答案:
https://stackoverflow.com/a/11246261/1561176
这就是我需要的,只需要输入我自己的值。并修改它输出的方式。
可能应该尝试更深入,感谢大家的帮助。
答案 1 :(得分:0)
不是使用排列,而是如下:
import copy
import random
# Setup:
opponents = dict()
for competitor in competitors:
opponents[competitor] = copy.deepcopy(competitors)
def do_round():
players = copy.deepcopy(competitors)
while players:
p1 = players.pop(0)
p2 = random.choice(opponents[p1])
opponents[p2].remove(p1)
opponents[p1].remove(p2)
players.remove(p2)
play_match(p1, p2)
for _ in range(len(competitors)):
do_round()
如果不能并行播放,则为much easier to create a schedule
答案 2 :(得分:0)
你说“随机决定他们必须在每一轮面对谁”,但你可以按照维基百科文章中描述的循环算法,这不是随机的,但确保n个玩家之后,(n-1)轮次,每个球员都遇到了所有其他球员。