cgame.py 22 KB

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