1
0

cgame.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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 = [('r', 'record score and advance turn'),
  30. ('t', 'advance turn, no score'),
  31. ('b', 'additional turn for a player due to a builder'),
  32. ('e', 'end game (or play if already in postgame scoring'),
  33. ('s', '(current) score and game status'),
  34. ('?', 'print help')]
  35. self.conn = _sqlite3.connect('CarcassonneScore.db')
  36. self.cur = self.conn.cursor()
  37. self.setupGame()
  38. def showCommands(self):
  39. """
  40. Print out a list of valid commands for in-game play.
  41. """
  42. _sys.stderr.write('Possible commands:\n')
  43. for entry in self.commands:
  44. _sys.stderr.write('\t' + entry[0] + ': ' + entry[1] + '\n')
  45. def setupGame(self):
  46. """
  47. Initialize a game
  48. """
  49. # get players for this game
  50. _sys.stdout.write("Collecting player information...\n")
  51. while self.getPlayers():
  52. continue
  53. # get expansions used for this game
  54. _sys.stdout.write("Collecting expansion information...\n")
  55. while self.getExpansions():
  56. continue
  57. # get general game info (do this after expansions because
  58. # expansion info is entered into the game table)
  59. while self.gameInfo()
  60. continue
  61. # game state information
  62. self.state = 0 # 0 for main game, 1 for postgame, 2 for ended game
  63. self.ntile = 1 # number of tiles played
  64. self.nbuilder = 0 # number of tiles placed due to builders
  65. def gameInfo(self):
  66. """
  67. Load basic game info
  68. """
  69. location = input("Where is the game being played? ")
  70. starttime = _datetime.utcnow().strftime("%Y-%m-%dT%H:%M")
  71. c.execute('INSERT INTO TABLE games (location, starttime, expansions) VALUES ' + location + ',' + starttime + ',"' + ["{0:d}".format(x) for x in self.expansionIDs].join(',') + '")')
  72. gID = c.execute('select last_insert_rowid();').fetchall()[0]
  73. self.gameID = gID
  74. def getPlayers(self):
  75. """
  76. Get a list of possible players from the database
  77. """
  78. self.players = []
  79. dbplayers = self.cur.execute('''SELECT * FROM players''').fetchall()
  80. if len(dbplayers):
  81. for dbplayer in dbplayers:
  82. print("{0:d}) ".format(dbplayer[0]) + dbplayer[1])
  83. playerinput = input("Please list the IDs for the players in this game (in order of play): ")
  84. playerIDs = [int(x) for x in playerinput.split()]
  85. for playerID in playerIDs:
  86. matched = False
  87. for dbplayer in dbplayers:
  88. if playerID == dbplayer[0]:
  89. self.players.append((playerID, dbplayer[1]))
  90. matched = True
  91. continue
  92. if not matched:
  93. _sys.stderr.write("Error: player ID {0:d} does not match an option from the list.\n".format(playerID))
  94. return 1
  95. else:
  96. _sys.stderr.write("Error: players table empty. Exiting.\n")
  97. _sys.exit(-1)
  98. return 0
  99. def getExpansions(self):
  100. """
  101. Get a list of playable expansions
  102. """
  103. self.expansionIDs = []
  104. for minisel in range(0, 2):
  105. if minisel:
  106. exptype = "mini"
  107. else:
  108. exptype = "large"
  109. dbexpans = self.cur.execute('''SELECT expansionID,name FROM expansions WHERE active==1 and mini=={0:d}'''.format(minisel)).fetchall()
  110. if len(dbexpans):
  111. for dbexpan in dbexpans:
  112. print("{0:d}) ".format(dbexpan[0]) + dbexpan[1])
  113. expaninput = input("Please list the numbers for the " + exptype + " used in this game: ")
  114. expanIDs = [int(x) for x in expaninput.split()]
  115. for expanID in expanIDs:
  116. matched = False
  117. for dbexpan in dbexpans:
  118. if expanID == dbexpan[0]:
  119. self.expansionIDs.append(expanID)
  120. matched = True
  121. continue
  122. if not matched:
  123. _sys.stderr.write("Error: expansion ID {0:d} does not match an option from the list.\n".format(expanID))
  124. return 1
  125. else:
  126. sys.stdout.write("No active " + exptype + " expansions found. Continuing.\n")
  127. return 0
  128. def recordScore(gameID, playerIDs, expansionIDs, cround, state):
  129. """
  130. Record a score event in the game
  131. """
  132. if state:
  133. ingame = 0
  134. pname = getPlayerNames(playerIDs)
  135. # for i, pname in enumerate(pname):
  136. pID = input("")
  137. # if the builder was used
  138. BUILDERUSED = True
  139. advanceTurn(builder=BUILDERUSED)
  140. return 0
  141. def advanceTurn(self, builder=False):
  142. """
  143. Make a new entry in the turns table
  144. """
  145. cmdtime = _datetime.utcnow().strftime("%Y-%m-%dT%H:%M")
  146. command = '''INSERT INTO turns VALUES ({0:d}, {1:d}, '''.format(self.gameID, self.ntile)
  147. command = command + cmdtime
  148. if builder:
  149. bID = 1
  150. else:
  151. bID = 0
  152. # compute playerID based on the turn number minus nbuilders / number of players
  153. playerID = playerIDs[(self.ntile- self.nbuilder) / len(playerIDs)]
  154. command = command + ', {0:d}, {1:d})'.format(bID, playerID)
  155. c.execute(command)
  156. self.ntile += 1
  157. if builder:
  158. self.nbuilder += 1
  159. def runGame(self):
  160. """
  161. Main routine for entering games
  162. """
  163. # here wait for input for scores, advancing to next round, or completion of game
  164. # for each step of entry, present a series of options, based on the list
  165. # of playerIDs and expansions
  166. while self.state < 2:
  167. # set up prompt based on current round
  168. if self.state:
  169. prompt = "postgame > "
  170. else:
  171. prompt = "round: {0:d}, turn: {1:d} > ".format(int(_np.floor((self.ntile-self.nbuilder) / len(self.players))),
  172. self.ntile-self.nbuilder)
  173. try:
  174. cmd = input(prompt)
  175. except (EOFError, KeyboardInterrupt):
  176. _sys.stderr.write('Improper input. Please retry\n')
  177. self.showCommands()
  178. if _re.match('e', cmd, _re.IGNORECASE):
  179. self.advanceState()
  180. elif _re.match('s', cmd, _re.IGNORECASE):
  181. printStatus(tilestats=True)
  182. elif _re.match('n', cmd, _re.IGNORECASE):
  183. self.advanceTurn()
  184. elif _re.match('r', cmd, _re.IGNORECASE):
  185. self.recordScore()
  186. elif _re.match('t', cmd, _re.IGNORECASE):
  187. self.advanceTurn(builder=False)
  188. elif _re.match('b', cmd, _re.IGNORECASE):
  189. self.advanceTurn(builder=True)
  190. elif _re.match('\?', cmd, _re.IGNORECASE):
  191. self.showCommands()
  192. else:
  193. _sys.stderr.write('Command not understood. Please try again.\n')
  194. self.showCommands()
  195. if state == 2:
  196. #game is over. write end time to the games table
  197. time = _datetime.utcnow().strftime("%Y-%m-%dT%H:%M")
  198. c.execute('''UPDATE games SET endtime = "''' + time + '''" WHERE gameID = ''' + str(gameID))
  199. conn.commit()
  200. printStatus(tilestats=False)
  201. #### Is there a way to capture "ineffective" uses? For example,
  202. #### meeples that don't score points because they end up in a meadow that's
  203. #### controled by someone else?
  204. return 0
  205. def printStatus(self, tilestats=False):
  206. """
  207. Print the total score (current or final) for the specified gameID
  208. """
  209. for playerID in self.playerIDs:
  210. pname = c.execute('SELECT name FROM players WHERE playerID={0:d}'.format(playerID[0])).fetchall()[0]
  211. a = c.execute('SELECT points FROM scores WHER gameID={0:d} and playerID={1:d}'.format(self.gameID, playerID[0]))
  212. res = a.fetchall()
  213. score = _np.sum(res)
  214. print(pname + ': {0:d}'.format(score))
  215. print("{0:d} tiles played out of {1:d} total ({2:d} remaining).".format(self.ntiles,
  216. self.totaltiles,
  217. self.totaltiles - self.ntiles))