cgame.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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'),
  30. ('n', 'next turn'),
  31. ('e', 'end game (or end play if already in postgame scoring)'),
  32. ('s', '(current) score and game status'),
  33. ('q', 'quit (will be removed for real gameplay'),
  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. # game state information
  50. self.state = 0 # 0 for main game, 1 for postgame, 2 for ended game
  51. self.nscore = 0
  52. self.ntile = 0 # number of tiles played
  53. self.nbuilder = 0 # number of tiles placed due to builders
  54. self.totaltiles = 72 # may be increased by expansions
  55. # get players for this game
  56. _sys.stdout.write("Collecting player information...\n")
  57. while self.getPlayers():
  58. continue
  59. # get expansions used for this game
  60. _sys.stdout.write("Collecting expansion information...\n")
  61. while self.getExpansions():
  62. continue
  63. # get general game info (do this after expansions because
  64. # expansion info is entered into the game table)
  65. while self.gameInfo():
  66. continue
  67. def gameInfo(self):
  68. """
  69. Load basic game info
  70. """
  71. location = input("Where is the game being played? ")
  72. starttime = _datetime.utcnow().strftime("%Y-%m-%dT%H:%M")
  73. self.cur.execute('INSERT INTO games (location, starttime, expansions) VALUES ("' + location + '","' + starttime + '","' + ','.join(["{0:d}".format(x) for x in self.expansionIDs]) + '")')
  74. gID = self.cur.execute('select last_insert_rowid();').fetchall()[0]
  75. self.conn.commit()
  76. self.gameID = gID[0]
  77. def getPlayers(self):
  78. """
  79. Get a list of possible players from the database
  80. """
  81. self.players = []
  82. dbplayers = self.cur.execute('''SELECT * FROM players''').fetchall()
  83. if len(dbplayers):
  84. for dbplayer in dbplayers:
  85. _sys.stdout.write("{0:d}) ".format(dbplayer[0]) + dbplayer[1] + '\n')
  86. playerinput = input("Please list the IDs for the players in this game (in order of play): ")
  87. playerIDs = [int(x) for x in playerinput.split()]
  88. for playerID in playerIDs:
  89. matched = False
  90. for dbplayer in dbplayers:
  91. if playerID == dbplayer[0]:
  92. self.players.append((playerID, dbplayer[1]))
  93. matched = True
  94. continue
  95. if not matched:
  96. _sys.stderr.write("Error: player ID {0:d} does not match an option from the list.\n".format(playerID))
  97. return 1
  98. else:
  99. _sys.stderr.write("Error: players table empty. Exiting.\n")
  100. _sys.exit(-1)
  101. return 0
  102. def getExpansions(self):
  103. """
  104. Get a list of playable expansions
  105. """
  106. self.expansionIDs = []
  107. self.tokens = ["Meeple"]
  108. self.tiletypes = []
  109. for minisel in range(0, 2):
  110. if minisel:
  111. exptype = "mini"
  112. else:
  113. exptype = "large"
  114. dbexpans = self.cur.execute('''SELECT expansionID,name,tokens,Ntiles,tiletypes FROM expansions WHERE active==1 and mini=={0:d}'''.format(minisel)).fetchall()
  115. if len(dbexpans):
  116. for dbexpan in dbexpans:
  117. _sys.stdout.write("{0:d}) ".format(dbexpan[0]) + dbexpan[1] + '\n')
  118. expaninput = input("Please list the numbers for the " + exptype + " used in this game: ")
  119. expanIDs = [int(x) for x in expaninput.split()]
  120. for expanID in expanIDs:
  121. matched = False
  122. # only add the additional builder command if Traders &
  123. # Builders is being played
  124. if expanID == 2:
  125. self.commands.append(('b', 'additional turn for a player due to a builder (use for the 2nd play by a player)'))
  126. for dbexpan in dbexpans:
  127. if expanID == dbexpan[0]:
  128. self.expansionIDs.append(expanID)
  129. self.totaltiles += dbexpan[3]
  130. ttypes = dbexpan[2].split(',')
  131. if len(ttypes):
  132. for token in ttypes:
  133. self.tokens.append(token)
  134. tiletypes = dbexpan[4].split(',')
  135. if len(tiletypes):
  136. for tile in tiletypes:
  137. self.tiletypes.append(tile)
  138. matched = True
  139. continue
  140. if not matched:
  141. _sys.stderr.write("Error: expansion ID {0:d} does not match an option from the list.\n".format(expanID))
  142. return 1
  143. else:
  144. _sys.stdout.write("No active " + exptype + " expansions found. Continuing.\n")
  145. return 0
  146. def recordScore(self):
  147. """
  148. Record a score event in the game
  149. """
  150. score = {'gameID': self.gameID,
  151. 'playerID': -1,
  152. 'turnNum': self.ntile,
  153. 'scoreID': self.nscore,
  154. 'ingame' : 1,
  155. 'points' : 0,
  156. 'scoretype': '',
  157. 'sharedscore': 0,
  158. 'token': '',
  159. 'extras': '',
  160. 'comments': ''}
  161. if self.state:
  162. score['ingame'] = 0
  163. # ask the user which player scored
  164. score['playerID'] = ...
  165. # get points for score
  166. VALID = False
  167. while not VALID:
  168. score = input("Enter the total number of points: ")
  169. try:
  170. score['points'] = int(score)
  171. VALID = True
  172. except:
  173. _sys.stderr.write("'" + commnd + "' is not a valid score.\n")
  174. continue
  175. # get the score type
  176. VALID = False
  177. while not VALID:
  178. # here i want a list of valid score types
  179. stype = input("Please select the score type: ")
  180. # shared score?
  181. VALID = False
  182. while not VALID:
  183. shared = input("Was this score shared with another player (y/n)? ")
  184. # see which token scored
  185. # really this should be expanded to allow multiple token types for one score
  186. if len(self.tokens) > 1:
  187. VALID = False
  188. while not VALID:
  189. for i, token in enumerate(self.tokens):
  190. sys.stdout.write("{0:d}) ".format(i+1) + token + "\n")
  191. tID = input("Please select the token type: ")
  192. try:
  193. score['token'] += self.tokens[int(tID-1)]
  194. VALID = True
  195. except:
  196. _sys.stderr.write("'" + command + "' is not a valid token.\n")
  197. continue
  198. else:
  199. score['token'] = self.tokens[0]
  200. # now construct a SQL query
  201. command = 'INSERT INTO scores VALUE ({0:d},'.format(self.gameID)
  202. command = command + '{0:d}, {1:d},'.format(self.ntile,
  203. self.nscore)
  204. if score['sharedscore']:
  205. # get the other player(s) who scored and construct SQL inserts for
  206. # scores
  207. # now increment the score number
  208. self.nscore += 1
  209. return 0
  210. def advanceTurn(self, builder=False):
  211. """
  212. Make a new entry in the turns table
  213. """
  214. cmdtime = _datetime.utcnow().strftime("%Y-%m-%dT%H:%M")
  215. command = '''INSERT INTO turns VALUES ({0:d}, {1:d}, "'''.format(self.gameID, self.ntile)
  216. command = command + cmdtime + '"'
  217. if builder:
  218. bID = 1
  219. else:
  220. bID = 0
  221. # compute playerID based on the turn number minus nbuilders / number of players
  222. player = self.getCurrentPlayer()
  223. command = command + ', {0:d}, {1:d})'.format(bID, player[0])
  224. self.cur.execute(command)
  225. self.conn.commit()
  226. self.ntile += 1
  227. if builder:
  228. self.nbuilder += 1
  229. def runGame(self):
  230. """
  231. Main routine for entering games
  232. """
  233. # here wait for input for scores, advancing to next round, or completion of game
  234. # for each step of entry, present a series of options, based on the list
  235. # of playerIDs and expansions
  236. while self.state < 2:
  237. # set up prompt based on current round
  238. if self.state:
  239. prompt = "postgame > "
  240. else:
  241. player = self.getCurrentPlayer()
  242. prompt = "round: {0:d}, turn: {1:d} ".format(int(_np.floor((self.ntile-self.nbuilder) / len(self.players))),
  243. self.ntile-self.nbuilder)
  244. prompt = prompt + "(" + player[1] + ") > "
  245. try:
  246. cmd = input(prompt)
  247. except (EOFError, KeyboardInterrupt):
  248. _sys.stderr.write('Improper input. Please retry\n')
  249. self.showCommands()
  250. if _re.match('e', cmd, _re.IGNORECASE):
  251. self.advanceState()
  252. elif _re.match('q', cmd, _re.IGNORECASE):
  253. _sys.exit(0)
  254. elif _re.match('s', cmd, _re.IGNORECASE):
  255. self.printStatus(tilestats=True)
  256. elif _re.match('n', cmd, _re.IGNORECASE):
  257. self.advanceTurn(builder=False)
  258. elif _re.match('r', cmd, _re.IGNORECASE):
  259. self.recordScore()
  260. elif _re.match('b', cmd, _re.IGNORECASE):
  261. self.advanceTurn(builder=True)
  262. elif _re.match('\?', cmd, _re.IGNORECASE):
  263. self.showCommands()
  264. else:
  265. _sys.stderr.write('Command not understood. Please try again.\n')
  266. self.showCommands()
  267. if state == 2:
  268. #game is over. write end time to the games table
  269. time = _datetime.utcnow().strftime("%Y-%m-%dT%H:%M")
  270. self.cur.execute('''UPDATE games SET endtime = "''' + time + '''" WHERE gameID = ''' + str(gameID))
  271. conn.commit()
  272. printStatus(tilestats=False)
  273. #### Is there a way to capture "ineffective" uses? For example,
  274. #### meeples that don't score points because they end up in a meadow that's
  275. #### controled by someone else?
  276. return 0
  277. def printStatus(self, tilestats=False):
  278. """
  279. Print the total score (current or final) for the specified gameID
  280. """
  281. _sys.stdout.write('\nCurrent Score\n')
  282. for player in self.players:
  283. a = self.cur.execute('SELECT points FROM scores WHERE gameID={0:d} and playerID={1:d}'.format(self.gameID, player[0]))
  284. res = a.fetchall()
  285. score = _np.sum(res)
  286. _sys.stdout.write('\t' + player[1]+ ': {0:1.0f}'.format(score) + '\n')
  287. _sys.stdout.write("{0:1.0f} tiles played, {1:1.0f} remaining.\n\n".format(self.ntile,
  288. self.totaltiles - self.ntile))
  289. def getCurrentPlayer(self):
  290. """
  291. Return the current player, determined by the turn number
  292. """
  293. return self.players[int((self.ntile - self.nbuilder) % len(self.players))]