1
0

cgame.py 23 KB

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