cgame.py 21 KB

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