cgame.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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 os as _os
  17. import re as _re
  18. import sys as _sys
  19. import configparser as _configparser
  20. from datetime import datetime as _datetime
  21. import sqlite3 as _sqlite3
  22. import numpy as _np
  23. class cgame:
  24. """
  25. Carcassonne game object
  26. """
  27. def __init__(self, config='CarcassonneScore.db'):
  28. """
  29. Initialize some variables and set up a game
  30. """
  31. self.commands = [('r', 'record score'),
  32. ('n', 'next turn'),
  33. ('e', 'end game (or end play if already in postgame scoring)'),
  34. ('s', '(current) score and game status'),
  35. ('q', 'quit (will be removed for real gameplay'),
  36. ('?', 'print help')]
  37. self.loadConfig(config)
  38. self.conn = _sqlite3.connect(self.config.get('CarcassonneScore', 'DBNAME'))
  39. self.cur = self.conn.cursor()
  40. self.timefmt = "%Y-%m-%dT%H:%M:%S"
  41. self.setupGame()
  42. def loadConfig(self, cfile):
  43. """
  44. Load configuration file
  45. """
  46. if not _os.path.isfile(cfile):
  47. _sys.stderr.write("Error: could not find configuration file '" + cfile + "'\n")
  48. _sys.exit()
  49. self.config = _configparser.RawConfigParser()
  50. self.config.read(cfile)
  51. def showCommands(self):
  52. """
  53. Print out a list of valid commands for in-game play.
  54. """
  55. _sys.stderr.write('Possible commands:\n')
  56. for entry in self.commands:
  57. _sys.stderr.write('\t' + entry[0] + ': ' + entry[1] + '\n')
  58. def setupGame(self):
  59. """
  60. Initialize a game
  61. """
  62. # game state information
  63. self.state = 0 # 0 for main game, 1 for postgame, 2 for ended game
  64. self.nscore = 0
  65. self.ntile = 1 # number of tiles played
  66. self.nbuilder = 0 # number of tiles placed due to builders
  67. self.totaltiles = 72 # may be increased by expansions
  68. self.tokens = ["Meeple"]
  69. self.tiletypes = []
  70. self.scoretypes = ["Meadow", "City", "Road", "Monastery"]
  71. # get players for this game
  72. _sys.stdout.write("Collecting player information...\n")
  73. while self.getPlayers():
  74. continue
  75. # get expansions used for this game
  76. _sys.stdout.write("Collecting expansion information...\n")
  77. while self.getExpansions():
  78. continue
  79. # get general game info (do this after expansions because
  80. # expansion info is entered into the game table)
  81. while self.gameInfo():
  82. continue
  83. def gameInfo(self):
  84. """
  85. Load basic game info
  86. """
  87. location = input("Where is the game being played? ")
  88. starttime = _datetime.utcnow().strftime(self.timefmt)
  89. self.cur.execute('INSERT INTO games (location, starttime, expansions) VALUES ("' + location + '","' + starttime + '","' + ','.join(["{0:d}".format(x) for x in self.expansionIDs]) + '")')
  90. gID = self.cur.execute('select last_insert_rowid();').fetchall()[0]
  91. self.conn.commit()
  92. self.gameID = gID[0]
  93. def getPlayers(self):
  94. """
  95. Get a list of possible players from the database
  96. """
  97. self.players = []
  98. dbplayers = self.cur.execute('''SELECT * FROM players''').fetchall()
  99. if len(dbplayers):
  100. for dbplayer in dbplayers:
  101. _sys.stdout.write("{0:d}) ".format(dbplayer[0]) + dbplayer[1] + '\n')
  102. VALID = False
  103. while not VALID:
  104. playerinput = input("Please list the IDs for the players in this game (in order of play): ")
  105. try:
  106. playerIDs = [int(x) for x in playerinput.split()]
  107. VALID = True
  108. except:
  109. _sys.stderr.write("Error: input must be a list of integers separated by spaces.\n")
  110. if len(playerIDs) < 2:
  111. _sys.stderr.write("Playing alone? You need at least one opponent!\n")
  112. return 1
  113. for playerID in playerIDs:
  114. matched = False
  115. for dbplayer in dbplayers:
  116. if playerID == dbplayer[0]:
  117. self.players.append((playerID, dbplayer[1]))
  118. matched = True
  119. continue
  120. if not matched:
  121. _sys.stderr.write("Error: player ID {0:d} does not match an option from the list.\n".format(playerID))
  122. return 1
  123. else:
  124. _sys.stderr.write("Error: players table empty. Exiting.\n")
  125. _sys.exit(-1)
  126. return 0
  127. def getExpansions(self):
  128. """
  129. Get a list of playable expansions.
  130. Ask the user which ones are active.
  131. Based on the list, add token, tile, and score types to the basic list.
  132. """
  133. self.expansionIDs = []
  134. for minisel in range(0, 2):
  135. if minisel:
  136. exptype = "mini"
  137. else:
  138. exptype = "large"
  139. dbexpans = self.cur.execute('''SELECT expansionID,name,tokens,Ntiles,tiletypes,scoretypes FROM expansions WHERE active==1 and mini=={0:d}'''.format(minisel)).fetchall()
  140. if len(dbexpans):
  141. for dbexpan in dbexpans:
  142. _sys.stdout.write("{0:d}) ".format(dbexpan[0]) + dbexpan[1] + '\n')
  143. VALID = False
  144. while not VALID:
  145. expaninput = input("Please list the numbers for the " + exptype + " used in this game: ")
  146. try:
  147. expanIDs = [int(x) for x in expaninput.split()]
  148. VALID = True
  149. except:
  150. _sys.stderr.write("Error: input must be a list of integers separated by spaces.\n")
  151. for expanID in expanIDs:
  152. matched = False
  153. # add the builder cmd if Traders & Builders is used
  154. if expanID == 2:
  155. self.commands.append(('b', 'additional turn for a player due to a builder (use for the 2nd play by a player)'))
  156. for dbexpan in dbexpans:
  157. if expanID == dbexpan[0]:
  158. self.expansionIDs.append(expanID)
  159. self.totaltiles += dbexpan[3]
  160. ttypes = dbexpan[2].split(',')
  161. if len(ttypes):
  162. # add new types of tokens
  163. for token in ttypes:
  164. if token:
  165. self.tokens.append(token)
  166. tiletypes = dbexpan[4].split(',')
  167. if len(tiletypes):
  168. # add special tiles
  169. for tile in tiletypes:
  170. if tile:
  171. self.tiletypes.append(tile)
  172. stypes = dbexpan[5].split(',')
  173. if len(stypes):
  174. # add new types of scoring
  175. for stype in stypes:
  176. if stype:
  177. self.scoretypes.append(stype)
  178. matched = True
  179. continue
  180. if not matched:
  181. _sys.stderr.write("Error: expansion ID {0:d} does not match an option from the list.\n".format(expanID))
  182. return 1
  183. else:
  184. _sys.stdout.write("No active " + exptype + " expansions found. Continuing.\n")
  185. return 0
  186. def recordScore(self):
  187. """
  188. Record a score event in the game
  189. """
  190. score = {'playerIDs': -1,
  191. 'ingame' : 1,
  192. 'points' : 0,
  193. 'scoretype': '',
  194. 'sharedscore': 0,
  195. 'tokens': '',
  196. 'extras': '',
  197. 'comments': ''}
  198. if self.state:
  199. score['ingame'] = 0
  200. # ask the user which player scored
  201. VALID = False
  202. while not VALID:
  203. for player in self.players:
  204. _sys.stdout.write("{0:d}) ".format(player[0]) + player[1] + "\n")
  205. scoreplayers = input("Please enter the numbers for the players who scored: ")
  206. try:
  207. score['playerIDs'] = [int(x) for x in scoreplayers.split()]
  208. if not len(score['playerIDs']):
  209. _sys.stderr.write("There must be at least one player.\n")
  210. continue
  211. elif self.checkPlayers(score['playerIDs']):
  212. _sys.stderr.write("At least one player entered is not playing this game.\n")
  213. else:
  214. VALID = True
  215. except:
  216. _sys.stderr.write("Error, could not parse players list.\n")
  217. continue
  218. if len(score['playerIDs']) > 1:
  219. score['sharedscore'] = 1
  220. # see which token scored
  221. # really this should be expanded to allow multiple token types for one score
  222. if score['scoretype'] == 'Trade token':
  223. score['tokens'] = 'none'
  224. elif len(self.tokens) > 1:
  225. VALID = False
  226. while not VALID:
  227. for i, token in enumerate(self.tokens):
  228. _sys.stdout.write("{0:d}) ".format(i+1) + token + "\n")
  229. tID = input("Please select the token type(s): ")
  230. try:
  231. score['tokens'] = ','.join(self.tokens[int(x)-1] for x in tID.split())
  232. VALID = True
  233. except:
  234. _sys.stderr.write("'" + tID + "' is not a valid token.\n")
  235. continue
  236. else:
  237. score['tokens'] = self.tokens[0]
  238. # get the score type
  239. VALID = False
  240. while not VALID:
  241. for i, stype in enumerate(self.scoretypes):
  242. _sys.stdout.write("{0:d}) ".format(i+1) + stype + "\n")
  243. # here i want a list of valid score types
  244. stype = input("Please select the score type: ")
  245. try:
  246. score['scoretype'] = self.scoretypes[int(stype)-1]
  247. VALID = True
  248. except:
  249. _sys.stderr.write("'" + stype + "' is not a valid score type.\n")
  250. continue
  251. # get points for score
  252. VALID = False
  253. while not VALID:
  254. points = input("Enter the total number of points: ")
  255. try:
  256. score['points'] = int(points)
  257. VALID = True
  258. except:
  259. _sys.stderr.write("'" + points + "' is not a valid score.\n")
  260. continue
  261. score['comments'] = input("Enter any comments you would like saved (a single line): ")
  262. # check score input to make sure it's correct
  263. _sys.stdout.write('Player {0:d} scores {1:d} points on a '.format(score['playerIDs'][0], score['points']) + score['scoretype'] + '.\n')
  264. answer = input("Is this correct? (y/n) ")
  265. if not _re.match('y', answer, _re.IGNORECASE):
  266. return 1
  267. # now construct a SQL query
  268. for player in score['playerIDs']:
  269. command = 'INSERT INTO scores VALUES ({0:d},'.format(self.gameID)
  270. command = command + '{0:d},'.format(player)
  271. command = command + '{0:d},{1:d},'.format(self.ntile,
  272. self.nscore)
  273. command = command + '{0:d},{1:d},'.format(score['ingame'],
  274. score['points'])
  275. command = command + '"' + score['scoretype'] + '",'
  276. command = command + '{0:d},'.format(score['sharedscore'])
  277. command = command + '"' + score['tokens'] + '",'
  278. command = command + '"' + score['extras'] + '",'
  279. command = command + '"' + score['comments'] + '")'
  280. self.cur.execute(command)
  281. self.conn.commit()
  282. # now increment the score number
  283. self.nscore += 1
  284. return 0
  285. def advanceTurn(self, builder=False):
  286. """
  287. Make a new entry in the turns table
  288. """
  289. cmdtime = _datetime.utcnow().strftime(self.timefmt)
  290. command = '''INSERT INTO turns VALUES ({0:d}, {1:d}, "'''.format(self.gameID, self.ntile)
  291. command = command + cmdtime + '"'
  292. if builder:
  293. bID = 1
  294. else:
  295. bID = 0
  296. # compute playerID based on the turn number minus nbuilders / number of players
  297. player = self.getCurrentPlayer()
  298. command = command + ', {0:d}, {1:d})'.format(bID, player[0])
  299. self.cur.execute(command)
  300. self.conn.commit()
  301. self.ntile += 1
  302. if builder:
  303. self.nbuilder += 1
  304. def runGame(self):
  305. """
  306. Main routine for entering games
  307. """
  308. # here wait for input for scores, advancing to next round, or completion of game
  309. # for each step of entry, present a series of options, based on the list
  310. # of playerIDs and expansions
  311. while self.state < 2:
  312. # set up prompt based on current round
  313. if self.state:
  314. prompt = "postgame > "
  315. else:
  316. player = self.getCurrentPlayer()
  317. prompt = "round: {0:d}, turn: {1:d} ".format(int(_np.floor((self.ntile-self.nbuilder-1) / len(self.players))),
  318. self.ntile-self.nbuilder)
  319. prompt = prompt + "(" + player[1] + ") > "
  320. try:
  321. cmd = input(prompt)
  322. except (EOFError, KeyboardInterrupt):
  323. _sys.stderr.write('Improper input. Please retry\n')
  324. self.showCommands()
  325. if _re.match('e', cmd, _re.IGNORECASE):
  326. self.advanceState()
  327. elif _re.match('q', cmd, _re.IGNORECASE):
  328. _sys.exit(0)
  329. elif _re.match('s', cmd, _re.IGNORECASE):
  330. if self.state:
  331. self.printStatus(tilestats=False)
  332. else:
  333. self.printStatus(tilestats=True)
  334. elif _re.match('n', cmd, _re.IGNORECASE):
  335. self.advanceTurn(builder=False)
  336. elif _re.match('r', cmd, _re.IGNORECASE):
  337. self.recordScore()
  338. elif _re.match('b', cmd, _re.IGNORECASE):
  339. self.advanceTurn(builder=True)
  340. elif _re.match('\?', cmd, _re.IGNORECASE):
  341. self.showCommands()
  342. else:
  343. _sys.stderr.write('Command not understood. Please try again.\n')
  344. self.showCommands()
  345. if self.state == 2:
  346. #game is over. write end time to the games table
  347. time = _datetime.utcnow().strftime(self.timefmt)
  348. self.cur.execute('''UPDATE games SET endtime = "''' + time + '''" WHERE gameID = ''' + str(self.gameID))
  349. self.conn.commit()
  350. _sys.stdout.write("Game over!\n")
  351. self.printStatus(tilestats=False, sort=True)
  352. self.conn.close()
  353. #### Is there a way to capture "ineffective" uses? For example,
  354. #### meeples that don't score points because they end up in a meadow that's
  355. #### controled by someone else?
  356. return 0
  357. def advanceState(self):
  358. """
  359. End the main part of play or finish the game
  360. """
  361. self.state += 1
  362. if self.state < 2:
  363. self.commands = [('r', 'record score'),
  364. ('e', 'end game (or end play if already in postgame scoring)'),
  365. ('s', '(current) score and game status')]
  366. # add trade token scoring to the game scoring options
  367. if 2 in self.expansionIDs:
  368. self.scoretypes.append('Trade token')
  369. self.commands.append(('?', 'print help'))
  370. _sys.stdout.write("At the end of regulation... ")
  371. self.printStatus(tilestats=False, sort=True)
  372. def printStatus(self, tilestats=False, sort=False):
  373. """
  374. Print the total score (current or final) for the specified gameID
  375. tilestats controls printing info on the number of tiles played/remaining
  376. sort will trigger sorting by score
  377. """
  378. _sys.stdout.write('\nScore\n')
  379. for player in self.players:
  380. a = self.cur.execute('SELECT points FROM scores WHERE gameID={0:d} and playerID={1:d}'.format(self.gameID, player[0]))
  381. res = a.fetchall()
  382. score = _np.sum(res)
  383. _sys.stdout.write('\t' + player[1]+ ': {0:1.0f}'.format(score) + '\n')
  384. if tilestats:
  385. _sys.stdout.write("{0:1.0f} tiles played, {1:1.0f} remaining.\n\n".format(self.ntile,
  386. self.totaltiles - self.ntile))
  387. def getCurrentPlayer(self):
  388. """
  389. Return the current player, determined by the turn number
  390. """
  391. return self.players[int((self.ntile - self.nbuilder - 1) % len(self.players))]
  392. def checkPlayers(self, trial):
  393. """
  394. Check to make sure all members of `trial` are in `comp`. If so, return
  395. 0. Otherwise return a list containing the missing members.
  396. """
  397. playerIDs = [x[0] for x in self.players]
  398. missing = []
  399. for obj in trial:
  400. if obj not in playerIDs:
  401. missing.append(obj)
  402. if len(missing):
  403. return missing
  404. else:
  405. return 0