cgame.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. #!/usr/bin/env python
  2. """
  3. Class definition 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. self.tokens = ["Meeple"]
  56. self.tiletypes = []
  57. self.scoretypes = ["Meadow", "City", "Road", "Monastery"]
  58. # get players for this game
  59. _sys.stdout.write("Collecting player information...\n")
  60. while self.getPlayers():
  61. continue
  62. # get expansions used for this game
  63. _sys.stdout.write("Collecting expansion information...\n")
  64. while self.getExpansions():
  65. continue
  66. # get general game info (do this after expansions because
  67. # expansion info is entered into the game table)
  68. while self.gameInfo():
  69. continue
  70. def gameInfo(self):
  71. """
  72. Load basic game info
  73. """
  74. location = input("Where is the game being played? ")
  75. starttime = _datetime.utcnow().strftime("%Y-%m-%dT%H:%M")
  76. self.cur.execute('INSERT INTO games (location, starttime, expansions) VALUES ("' + location + '","' + starttime + '","' + ','.join(["{0:d}".format(x) for x in self.expansionIDs]) + '")')
  77. gID = self.cur.execute('select last_insert_rowid();').fetchall()[0]
  78. self.conn.commit()
  79. self.gameID = gID[0]
  80. def getPlayers(self):
  81. """
  82. Get a list of possible players from the database
  83. """
  84. self.players = []
  85. dbplayers = self.cur.execute('''SELECT * FROM players''').fetchall()
  86. if len(dbplayers):
  87. for dbplayer in dbplayers:
  88. _sys.stdout.write("{0:d}) ".format(dbplayer[0]) + dbplayer[1] + '\n')
  89. playerinput = input("Please list the IDs for the players in this game (in order of play): ")
  90. playerIDs = [int(x) for x in playerinput.split()]
  91. if len(playerIDs) < 2:
  92. _sys.stderr.write("Playing alone? You need at least one opponent!\n")
  93. return 1
  94. for playerID in playerIDs:
  95. matched = False
  96. for dbplayer in dbplayers:
  97. if playerID == dbplayer[0]:
  98. self.players.append((playerID, dbplayer[1]))
  99. matched = True
  100. continue
  101. if not matched:
  102. _sys.stderr.write("Error: player ID {0:d} does not match an option from the list.\n".format(playerID))
  103. return 1
  104. else:
  105. _sys.stderr.write("Error: players table empty. Exiting.\n")
  106. _sys.exit(-1)
  107. return 0
  108. def getExpansions(self):
  109. """
  110. Get a list of playable expansions
  111. """
  112. self.expansionIDs = []
  113. for minisel in range(0, 2):
  114. if minisel:
  115. exptype = "mini"
  116. else:
  117. exptype = "large"
  118. dbexpans = self.cur.execute('''SELECT expansionID,name,tokens,Ntiles,tiletypes,scoretypes FROM expansions WHERE active==1 and mini=={0:d}'''.format(minisel)).fetchall()
  119. if len(dbexpans):
  120. for dbexpan in dbexpans:
  121. _sys.stdout.write("{0:d}) ".format(dbexpan[0]) + dbexpan[1] + '\n')
  122. expaninput = input("Please list the numbers for the " + exptype + " used in this game: ")
  123. expanIDs = [int(x) for x in expaninput.split()]
  124. for expanID in expanIDs:
  125. matched = False
  126. # add the builder cmd if Traders & Builders is used
  127. if expanID == 2:
  128. self.commands.append(('b', 'additional turn for a player due to a builder (use for the 2nd play by a player)'))
  129. for dbexpan in dbexpans:
  130. if expanID == dbexpan[0]:
  131. self.expansionIDs.append(expanID)
  132. self.totaltiles += dbexpan[3]
  133. ttypes = dbexpan[2].split(',')
  134. if len(ttypes):
  135. # add new types of tokens
  136. for token in ttypes:
  137. if token:
  138. self.tokens.append(token)
  139. tiletypes = dbexpan[4].split(',')
  140. if len(tiletypes):
  141. # add special tiles
  142. for tile in tiletypes:
  143. if tile:
  144. self.tiletypes.append(tile)
  145. stypes = dbexpan[5].split(',')
  146. if len(stypes):
  147. # add new types of scoring
  148. for stype in stypes:
  149. if stype:
  150. self.scoretypes.append(stype)
  151. matched = True
  152. continue
  153. if not matched:
  154. _sys.stderr.write("Error: expansion ID {0:d} does not match an option from the list.\n".format(expanID))
  155. return 1
  156. else:
  157. _sys.stdout.write("No active " + exptype + " expansions found. Continuing.\n")
  158. return 0
  159. def recordScore(self):
  160. """
  161. Record a score event in the game
  162. """
  163. score = {'playerIDs': -1,
  164. 'ingame' : 1,
  165. 'points' : 0,
  166. 'scoretype': '',
  167. 'sharedscore': 0,
  168. 'tokens': '',
  169. 'extras': '',
  170. 'comments': ''}
  171. if self.state:
  172. score['ingame'] = 0
  173. # ask the user which player scored
  174. VALID = False
  175. while not VALID:
  176. for player in self.players:
  177. _sys.stdout.write("{0:d}) ".format(player[0]) + player[1] + "\n")
  178. scoreplayers = input("Please enter the numbers for the players who scored: ")
  179. try:
  180. score['playerIDs'] = [int(x) for x in scoreplayers.split()]
  181. if len(score['playerIDs']):
  182. VALID = True
  183. else:
  184. _sys.stderr.write("There must be at least one player.\n")
  185. except:
  186. _sys.stderr.write("Error, could not parse players list.\n")
  187. continue
  188. if len(score['playerIDs']) > 1:
  189. score['sharedscore'] = 1
  190. # get points for score
  191. VALID = False
  192. while not VALID:
  193. points = input("Enter the total number of points: ")
  194. try:
  195. score['points'] = int(points)
  196. VALID = True
  197. except:
  198. _sys.stderr.write("'" + points + "' is not a valid score.\n")
  199. continue
  200. # get the score type
  201. VALID = False
  202. while not VALID:
  203. for i, stype in enumerate(self.scoretypes):
  204. _sys.stdout.write("{0:d}) ".format(i+1) + stype + "\n")
  205. # here i want a list of valid score types
  206. stype = input("Please select the score type: ")
  207. try:
  208. score['scoretype'] = self.scoretypes[int(stype)-1]
  209. VALID = True
  210. except:
  211. _sys.stderr.write("'" + stype + "' is not a valid score type.\n")
  212. continue
  213. # see which token scored
  214. # really this should be expanded to allow multiple token types for one score
  215. if len(self.tokens) > 1:
  216. VALID = False
  217. while not VALID:
  218. for i, token in enumerate(self.tokens):
  219. _sys.stdout.write("{0:d}) ".format(i+1) + token + "\n")
  220. tID = input("Please select the token type(s): ")
  221. try:
  222. score['tokens'] = ','.join(self.tokens[int(x)-1] for x in tID.split())
  223. VALID = True
  224. except:
  225. _sys.stderr.write("'" + tID + "' is not a valid token.\n")
  226. continue
  227. else:
  228. score['tokens'] = self.tokens[0]
  229. score['comments'] = input("Enter any comments you would like saved (a single line): ")
  230. # now construct a SQL query
  231. for player in score['playerIDs']:
  232. command = 'INSERT INTO scores VALUES ({0:d},'.format(self.gameID)
  233. command = command + '{0:d},'.format(player)
  234. command = command + '{0:d},{1:d},'.format(self.ntile,
  235. self.nscore)
  236. command = command + '{0:d},{1:d},'.format(score['ingame'],
  237. score['points'])
  238. command = command + '"' + score['scoretype'] + '",'
  239. command = command + '{0:d},'.format(score['sharedscore'])
  240. command = command + '"' + score['tokens'] + '",'
  241. command = command + '"' + score['extras'] + '",'
  242. command = command + '"' + score['comments'] + '")'
  243. self.cur.execute(command)
  244. self.conn.commit()
  245. # now increment the score number
  246. self.nscore += 1
  247. return 0
  248. def advanceTurn(self, builder=False):
  249. """
  250. Make a new entry in the turns table
  251. """
  252. cmdtime = _datetime.utcnow().strftime("%Y-%m-%dT%H:%M")
  253. command = '''INSERT INTO turns VALUES ({0:d}, {1:d}, "'''.format(self.gameID, self.ntile)
  254. command = command + cmdtime + '"'
  255. if builder:
  256. bID = 1
  257. else:
  258. bID = 0
  259. # compute playerID based on the turn number minus nbuilders / number of players
  260. player = self.getCurrentPlayer()
  261. command = command + ', {0:d}, {1:d})'.format(bID, player[0])
  262. self.cur.execute(command)
  263. self.conn.commit()
  264. self.ntile += 1
  265. if builder:
  266. self.nbuilder += 1
  267. def runGame(self):
  268. """
  269. Main routine for entering games
  270. """
  271. # here wait for input for scores, advancing to next round, or completion of game
  272. # for each step of entry, present a series of options, based on the list
  273. # of playerIDs and expansions
  274. while self.state < 2:
  275. # set up prompt based on current round
  276. if self.state:
  277. prompt = "postgame > "
  278. else:
  279. player = self.getCurrentPlayer()
  280. prompt = "round: {0:d}, turn: {1:d} ".format(int(_np.floor((self.ntile-self.nbuilder) / len(self.players))),
  281. self.ntile-self.nbuilder)
  282. prompt = prompt + "(" + player[1] + ") > "
  283. try:
  284. cmd = input(prompt)
  285. except (EOFError, KeyboardInterrupt):
  286. _sys.stderr.write('Improper input. Please retry\n')
  287. self.showCommands()
  288. if _re.match('e', cmd, _re.IGNORECASE):
  289. self.advanceState()
  290. elif _re.match('q', cmd, _re.IGNORECASE):
  291. _sys.exit(0)
  292. elif _re.match('s', cmd, _re.IGNORECASE):
  293. if self.state:
  294. self.printStatus(tilestats=False)
  295. else:
  296. self.printStatus(tilestats=True)
  297. elif _re.match('n', cmd, _re.IGNORECASE):
  298. self.advanceTurn(builder=False)
  299. elif _re.match('r', cmd, _re.IGNORECASE):
  300. self.recordScore()
  301. elif _re.match('b', cmd, _re.IGNORECASE):
  302. self.advanceTurn(builder=True)
  303. elif _re.match('\?', cmd, _re.IGNORECASE):
  304. self.showCommands()
  305. else:
  306. _sys.stderr.write('Command not understood. Please try again.\n')
  307. self.showCommands()
  308. if self.state == 2:
  309. #game is over. write end time to the games table
  310. time = _datetime.utcnow().strftime("%Y-%m-%dT%H:%M")
  311. self.cur.execute('''UPDATE games SET endtime = "''' + time + '''" WHERE gameID = ''' + str(self.gameID))
  312. self.conn.commit()
  313. _sys.stdout.write("Game over!\n")
  314. self.printStatus(tilestats=False, sort=True)
  315. self.conn.close()
  316. #### Is there a way to capture "ineffective" uses? For example,
  317. #### meeples that don't score points because they end up in a meadow that's
  318. #### controled by someone else?
  319. return 0
  320. def advanceState(self):
  321. """
  322. End the main part of play or finish the game
  323. """
  324. self.state += 1
  325. if self.state < 2:
  326. self.commands = [('r', 'record score'),
  327. ('e', 'end game (or end play if already in postgame scoring)'),
  328. ('s', '(current) score and game status'),
  329. ('?', 'print help')]
  330. _sys.stdout.write("At the end of regulation... ")
  331. self.printStatus(tilestats=False, sort=True)
  332. def printStatus(self, tilestats=False, sort=False):
  333. """
  334. Print the total score (current or final) for the specified gameID
  335. tilestats controls printing info on the number of tiles played/remaining
  336. sort will trigger sorting by score
  337. """
  338. _sys.stdout.write('\nScore\n')
  339. for player in self.players:
  340. a = self.cur.execute('SELECT points FROM scores WHERE gameID={0:d} and playerID={1:d}'.format(self.gameID, player[0]))
  341. res = a.fetchall()
  342. score = _np.sum(res)
  343. _sys.stdout.write('\t' + player[1]+ ': {0:1.0f}'.format(score) + '\n')
  344. if tilestats:
  345. _sys.stdout.write("{0:1.0f} tiles played, {1:1.0f} remaining.\n\n".format(self.ntile,
  346. self.totaltiles - self.ntile))
  347. def getCurrentPlayer(self):
  348. """
  349. Return the current player, determined by the turn number
  350. """
  351. return self.players[int((self.ntile - self.nbuilder) % len(self.players))]