cgame.py 19 KB

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