Program.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. #!/usr/bin/env python2
  2. import colorama, tempfile, os, time, re, sys, HumanReadableRoundNames, Combinations, Matches, TickBasedRandom
  3. from Team import Team
  4. fileName = ""
  5. teamsList = [ ]
  6. origTeams = []
  7. roundName = ""
  8. LastFixtures = ""
  9. def GetTempPath():
  10. with tempfile.NamedTemporaryFile() as tempFile:
  11. path = os.path.dirname(tempFile.name)
  12. return "/var/tmp" if (path.startswith("/tmp") or path == "/tmp/") and os.path.exists("/var/tmp") else path
  13. def GetNewFileName():
  14. tempPath = GetTempPath()
  15. return os.path.join(tempPath, "MISTBowl_Brackets_{0:.0f}.tmp".format(time.time()*1000))
  16. def GetExistingFileName():
  17. try:
  18. return sorted([a for a in os.listdir(GetTempPath()) if re.match(r'MISTBowl_Brackets_[0-9]+[.]tmp$', a)]).pop()
  19. except IndexError:
  20. raise IOError("no existing tournament file found")
  21. def Clear():
  22. sys.stdout.write("\x1Bc\x1B[97;44m\x1B[3J\x1B[H\x1B[2J")
  23. print("MIST Bowl Bracket Software")
  24. print("Copyright (c) 2018 Muhammad Mu'a" + unichr(240).encode('utf-8') + " Imtiaz")
  25. maxLength = 40
  26. if len(teamsList) > 0:
  27. pads = [ max([len(a.teamId) for a in teamsList]), max([len(a.region) for a in teamsList]), max([len(str(a.points)) for a in teamsList]) ]
  28. displayPoints = any([a.points != 0 for a in teamsList])
  29. teamsTable = [ [a.teamId.ljust(pads[0], " "), a.region.ljust(pads[1], " "), str(a.points).rjust(pads[2], " ") if displayPoints else "" ] for a in sorted(teamsList, key=lambda b: b.points,reverse=True) ]
  30. maxLength = max(len(HumanReadableRoundNames.GetHumanReadableName(roundName)) if roundName != "" else 0, max(40, max([len("".join(a)) for a in teamsTable])))
  31. for i in range(maxLength):
  32. sys.stdout.write("-")
  33. print(os.linesep + os.linesep.join(["\t".join(a) for a in teamsTable]))
  34. if roundName != "":
  35. print(HumanReadableRoundNames.GetHumanReadableName(roundName))
  36. for i in range(maxLength):
  37. sys.stdout.write("-")
  38. print("")
  39. def WriteToFile():
  40. with open(fileName, "w") as handle:
  41. for team in teamsList:
  42. handle.write("TEAM:" + team.teamId + "," + team.region + "\n")
  43. if roundName != "":
  44. handle.write(roundName + ":" + ",".join([a.teamId for a in teamsList]) + "\n")
  45. global LastFixtures
  46. if LastFixtures != "":
  47. handle.write(LastFixtures + "\n")
  48. LastFixtures = ""
  49. def ReadFromFile():
  50. raise NotImplementedError()
  51. sys.stdout.write("\x1B]0;MIST Bowl Bracket Software\x07")
  52. Clear()
  53. while True:
  54. print("Type 'c' to create a new tournament file, 'e' to use an existing one, or 'q' to quit, then press [Enter].")
  55. option = raw_input()
  56. if option == 'c':
  57. print("OK, creating new file. . .")
  58. fileName = GetNewFileName()
  59. while os.path.exists(fileName):
  60. fileName = GetNewFileName()
  61. break
  62. if option == 'e':
  63. print("OK, using existing file. . .")
  64. fileName = GetExistingFileName()
  65. break
  66. if option == 'q':
  67. exit(0)
  68. print("Invalid option '" + option + "'.");
  69. Clear()
  70. if not os.path.exists(fileName):
  71. print("For each team participating in the MIST Bowl tournament, please type the team ID, followed by a comma, followed by the team's region name, like as follows:")
  72. sys.stdout.write("\x1B[92m")
  73. print("1000,Detroit")
  74. print("1100/1600,Toronto")
  75. sys.stdout.write("\x1B[1;95m")
  76. print("MAKE SURE ALL REGION NAMES ARE SPELLED CORRECTLY!")
  77. sys.stdout.write("\x1B[22;97m")
  78. print("Press [Enter] twice when finished.")
  79. print("")
  80. while True:
  81. s = raw_input().upper()
  82. if s == "" :
  83. break
  84. if re.match(r'[0-9]+(/[0-9]+)* *, *[^ ,][^,]*$', s) == None or any([any([a in b.teamId.split("/") for b in teamsList]) for a in s.split(",")[0].split("/")]):
  85. raise ValueError("team ID cannot be repeated")
  86. teamsList.append(Team(re.sub(r' *, * ', r',', s).split(',')))
  87. if len(teamsList) == 0:
  88. raise ValueError("list of teams is empty")
  89. origTeamsList = list(teamsList)
  90. Clear()
  91. WriteToFile()
  92. sys.stdout.write("Please enter the number of preliminary rounds in this tournament: ")
  93. sys.stdout.flush()
  94. prelimRounds = int(raw_input())
  95. while True:
  96. sys.stdout.write("Please enter the number of matches taking place in each preliminary round: ")
  97. sys.stdout.flush()
  98. try:
  99. matchCount = int(raw_input())
  100. except:
  101. pass
  102. if len(teamsList) % matchCount == 0:
  103. break
  104. sys.stdout.write("\x1B[91m")
  105. print("That is not a valid number of matches given the number of teams. Please try again.")
  106. sys.stdout.write("\x1B[97m")
  107. print("")
  108. for i in range(prelimRounds):
  109. roundName = "PRELIM" + str(i + 1) + "/" + str(prelimRounds)
  110. Clear()
  111. print("The following matches will take place in this round:")
  112. for match in Combinations.GenerateBestMatches(teamsList, len(teamsList) / matchCount, matchCount, origTeamsList):
  113. Matches.AddMatch(match)
  114. print(" v. ".join([a.teamId for a in match]))
  115. sys.stdout.write("\x1B[1;95m")
  116. print("MAKE SURE TO WRITE DOWN THIS MATCH LIST BEFORE CONTINUING.")
  117. sys.stdout.write("\x1B[22;97m")
  118. time.sleep(3)
  119. print("")
  120. print("Press [Enter] to continue. . .")
  121. raw_input()
  122. Clear()
  123. print("Please enter the number of points earned by each team.")
  124. for team in teamsList:
  125. sys.stdout.write(team.teamId + "," + team.region + ": ")
  126. sys.stdout.flush()
  127. team.points += int(raw_input())
  128. while roundName != "F":
  129. roundName = ""
  130. Clear()
  131. sys.stdout.write("Please enter the number of teams progressing to the next round: ")
  132. sys.stdout.flush()
  133. teamsList = [sorted(sorted(teamsList, key=lambda a: TickBasedRandom.GetInteger(0, sys.maxsize)), key=lambda a: a.points, reverse=True)[b] for b in range(int(raw_input()))]
  134. for team in teamsList:
  135. team.points = 0
  136. while True:
  137. sys.stdout.write("Please enter the number of matches taking place in this round: ")
  138. sys.stdout.flush()
  139. try:
  140. matchCount = int(raw_input())
  141. except:
  142. pass
  143. if len(teamsList) % matchCount == 0:
  144. break
  145. sys.stdout.write("\x1B[91m")
  146. print("That is not a valid number of matches given the number of teams. Please try again.")
  147. sys.stdout.write("\x1B[97m")
  148. print("")
  149. roundName = "F" if matchCount == 1 else "ROUNDOF" + str(matchCount)
  150. Clear()
  151. print("The following matches will take place in this round:")
  152. for match in Combinations.GenerateBestMatches(teamsList, len(teamsList) / matchCount, matchCount, origTeamsList):
  153. Matches.AddMatch(match)
  154. print(" v. ".join([a.teamId for a in match]))
  155. sys.stdout.write("\x1B[1;95m")
  156. print("MAKE SURE TO WRITE DOWN THIS MATCH LIST BEFORE CONTINUING.")
  157. sys.stdout.write("\x1B[22;97m")
  158. print("")
  159. time.sleep(3)
  160. print("Press [Enter] to continue. . .")
  161. raw_input()
  162. Clear()
  163. print("Please enter the number of points earned by each team.")
  164. for team in teamsList:
  165. sys.stdout.write(team.teamId + "," + team.region + ": ")
  166. sys.stdout.flush()
  167. team.points += int(raw_input())
  168. teamsList = sorted(sorted(teamsList, key=lambda a: TickBasedRandom.GetInteger(0, sys.maxsize)), key=lambda a: a.points, reverse=True)
  169. print("1ST PLACE CHAMPIONS: " + teamsList[0].teamId + "," + teamsList[0].region)
  170. print("2ND PLACE CHAMPIONS: " + teamsList[1].teamId + "," + teamsList[1].region)
  171. print("3RD PLACE CHAMPIONS: " + teamsList[2].teamId + "," + teamsList[2].region)
  172. print("Press [Enter] to quit. . .")
  173. raw_input()
  174. sys.stdout.write("\x1B0m")
  175. sys.stdout.flush()