1
0

cgame.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. #!/usr/bin/env python
  2. """
  3. Class defenition for Carcassonne score keeping system.
  4. Copyright 2018 George C. Privon
  5. This program is free software: you can redistribute it and/or modify
  6. it under the terms of the GNU General Public License as published by
  7. the Free Software Foundation, either version 3 of the License, or
  8. (at your option) any later version.
  9. This program is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. """
  16. import re as _re
  17. import sys as _sys
  18. from datetime import datetime as _datetime
  19. import sqlite3 as _sqlite3
  20. import numpy as _np
  21. class cgame:
  22. """
  23. Carcassonne game object
  24. """
  25. def __init__(self):
  26. """
  27. Initialize some variables and set up a game
  28. """
  29. self.commands = [('n', 'next round'),
  30. ('r', 'record score and advance turn'),
  31. ('t', 'advance turn, no score'),
  32. ('b', 'additional turn for a player due to a builder'),
  33. ('e', 'end game (or play if already in postgame scoring'),
  34. ('s', '(current) score and game status'),
  35. ('?', 'print help')]
  36. self.conn = _sqlite3.connect('CarcassonneScore.db')
  37. self.cur = self.conn.cursor()
  38. self.setupGame()
  39. def showCommands(self):
  40. """
  41. Print out a list of valid commands for in-game play.
  42. """
  43. _sys.stderr.write('Possible commands:\n')
  44. for entry in self.commands:
  45. _sys.stderr.write('\t' + entry[0] + ': ' + entry[1] + '\n')
  46. def setupGame(self):
  47. """
  48. Initialize a game
  49. """
  50. # check to see if there's a game which has not yet been finished (i.e., has a starttime but no endtime). If there is, resume it. Otherwise:
  51. # generate a new game ID and enter a start time
  52. # get a list of players (from database list)
  53. # have user input which expansions are being used
  54. time = _datetime.utcnow().strftime("%Y-%m-%dT%H:%M")
  55. # insert this into the database
  56. # get players for this game
  57. _sys.stdout.write("Collecting player information...\n")
  58. while self.getPlayers():
  59. continue
  60. # general information
  61. self.gameID = 0
  62. # get expansions used for this game
  63. _sys.stdout.write("Collecting expansion information...\n")
  64. while self.getExpansions():
  65. continue
  66. # game state information
  67. self.state = 0 # 0 for main game, 1 for postgame, 2 for ended game
  68. self.ntile = 1 # number of tiles played
  69. self.nbuilder = 0 # number of tiles placed due to builders
  70. def getPlayers(self):
  71. """
  72. Get a list of possible players from the database
  73. """
  74. self.players = []
  75. dbplayers = self.cur.execute('''SELECT * FROM players''').fetchall()
  76. if len(dbplayers):
  77. for dbplayer in dbplayers:
  78. print("{0:d}) ".format(dbplayer[0]) + dbplayer[1])
  79. playerinput = input("Please list the IDs for the players in this game (in order of play): ")
  80. playerIDs = [int(x) for x in playerinput.split()]
  81. for playerID in playerIDs:
  82. matched = False
  83. for dbplayer in dbplayers:
  84. if playerID == dbplayer[0]:
  85. self.players.append((playerID, dbplayer[1]))
  86. matched = True
  87. continue
  88. if not matched:
  89. _sys.stderr.write("Error: player ID {0:d} does not match an option from the list.\n".format(playerID))
  90. return 1
  91. else:
  92. _sys.stderr.write("Error: players table empty. Exiting.\n")
  93. _sys.exit(-1)
  94. return 0
  95. def getExpansions(self):
  96. """
  97. Get a list of playable expansions
  98. """
  99. self.expansionIDs = []
  100. for minisel in range(0, 2):
  101. if minisel:
  102. exptype = "mini"
  103. else:
  104. exptype = "large"
  105. dbexpans = self.cur.execute('''SELECT expansionID,name FROM expansions WHERE active==1 and mini=={0:d}'''.format(minisel)).fetchall()
  106. if len(dbexpans):
  107. for dbexpan in dbexpans:
  108. print("{0:d}) ".format(dbexpan[0]) + dbexpan[1])
  109. expaninput = input("Please list the numbers for the " + exptype + " used in this game: ")
  110. expanIDs = [int(x) for x in expaninput.split()]
  111. for expanID in expanIDs:
  112. matched = False
  113. for dbexpan in dbexpans:
  114. if expanID == dbexpan[0]:
  115. self.expansionIDs.append(expanID)
  116. matched = True
  117. continue
  118. if not matched:
  119. _sys.stderr.write("Error: expansion ID {0:d} does not match an option from the list.\n".format(expanID))
  120. return 1
  121. else:
  122. sys.stdout.write("No active " + exptype + " expansions found. Continuing.\n")
  123. return 0
  124. def recordScore(gameID, playerIDs, expansionIDs, cround, state):
  125. """
  126. Record a score event in the game
  127. """
  128. if state:
  129. ingame = 0
  130. pname = getPlayerNames(playerIDs)
  131. # for i, pname in enumerate(pname):
  132. pID = input("")
  133. # if the builder was used
  134. BUILDERUSED = True
  135. advanceTurn(builder=BUILDERUSED)
  136. return 0
  137. def advanceTurn(self, builder=False):
  138. """
  139. Make a new entry in the turns table
  140. """
  141. command = '''INSERT INTO turns VALUES ({0:d}, {1:d}, '''.format(self.gameID, self.ntile)
  142. command = command + cmdtime
  143. if builder:
  144. bID = 1
  145. else:
  146. bID = 0
  147. # compute playerID based on the turn number minus nbuilders / number of players
  148. playerID = playerIDs[(self.ntile- self.nbuilder) / len(playerIDs)]
  149. command = command + ', {0:d}, {1:d})'.format(bID, playerID)
  150. c.execute(command)
  151. self.ntile += 1
  152. if builder:
  153. self.nbuilder += 1
  154. def runGame(self):
  155. """
  156. Main routine for entering games
  157. """
  158. # here wait for input for scores, advancing to next round, or completion of game
  159. # for each step of entry, present a series of options, based on the list
  160. # of playerIDs and expansions
  161. while self.state < 2:
  162. # set up prompt based on current round
  163. if self.state:
  164. prompt = "postgame > "
  165. else:
  166. prompt = "round: {0:d}, turn: {1:d} > ".format(int(_np.floor((self.ntile-self.nbuilder) / len(self.players))),
  167. self.ntile-self.nbuilder)
  168. try:
  169. cmd = input(prompt)
  170. except (EOFError, KeyboardInterrupt):
  171. _sys.stderr.write('Improper input. Please retry\n')
  172. self.showCommands()
  173. if _re.match('e', cmd, _re.IGNORECASE):
  174. self.advanceState()
  175. elif _re.match('s', cmd, _re.IGNORECASE):
  176. printStatus(tilestats=True)
  177. elif _re.match('n', cmd, _re.IGNORECASE):
  178. self.advanceTurn()
  179. elif _re.match('r', cmd, _re.IGNORECASE):
  180. self.recordScore()
  181. elif _re.match('t', cmd, _re.IGNORECASE):
  182. self.advanceTurn(builder=False)
  183. elif _re.match('b', cmd, _re.IGNORECASE):
  184. self.advanceTurn(builder=True)
  185. elif _re.match('\?', cmd, _re.IGNORECASE):
  186. self.showCommands()
  187. else:
  188. _sys.stderr.write('Command not understood. Please try again.\n')
  189. self.showCommands()
  190. if state == 2:
  191. #game is over. write end time to the games table
  192. time = _datetime.utcnow().strftime("%Y-%m-%dT%H:%M")
  193. c.execute('''UPDATE games SET endtime = "''' + time + '''" WHERE gameID = ''' + str(gameID))
  194. conn.commit()
  195. printStatus(tilestats=False)
  196. #### Is there a way to capture "ineffective" uses? For example,
  197. #### meeples that don't score points because they end up in a meadow that's
  198. #### controled by someone else?
  199. return 0
  200. def printStatus(self, tilestats=False):
  201. """
  202. Print the total score (current or final) for the specified gameID
  203. """
  204. for playerID in self.playerIDs:
  205. pname = c.execute('SELECT name FROM players WHERE playerID={0:d}'.format(playerID[0])).fetchall()[0]
  206. a = c.execute('SELECT points FROM scores WHER gameID={0:d} and playerID={1:d}'.format(self.gameID, playerID[0]))
  207. res = a.fetchall()
  208. score = _np.sum(res)
  209. print(pname + ': {0:d}'.format(score))
  210. print("{0:d} tiles played out of {1:d} total ({2:d} remaining).".format(self.ntiles,
  211. self.totaltiles,
  212. self.totaltiles - self.ntiles))