cgame.py 17 KB

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