1
0

cgame.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. #!/usr/bin/env python
  2. """
  3. Class defenition 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 = [('n', 'next round'),
  30. ('r', 'record score and advance turn'),
  31. ('t', 'advance turn, no score'),
  32. ('b', 'additional turn for a player due to a builder'),
  33. ('e', 'end game (or play if already in postgame scoring'),
  34. ('s', '(current) score and game status'),
  35. ('?', 'print help')]
  36. self.conn = sqlite3.connect('CarcassonneScore.db')
  37. self.cur = self.conn.cursor()
  38. 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. # check to see if there's a game which has not yet been finished (i.e., has a starttime but no endtime). If there is, resume it. Otherwise:
  51. # generate a new game ID and enter a start time
  52. # get a list of players (from database list)
  53. # have user input which expansions are being used
  54. time = _datetime.utcnow().strftime("%Y-%m-%dT%H:%M")
  55. # insert this into the database
  56. # get players for this game
  57. dbplayers = getPlayers()
  58. for dbplayer in dbplayers:
  59. print("{0:d}) ".format(dbplayer[0]) + dbplayer[1])
  60. playerinput = input("Please list the IDs for the players in this game (in order of play): ")
  61. playerIDs = [int(x) for x in playerinput.split()]
  62. self.players = []
  63. for playerID in playerIDs:
  64. for dbplayer in dbplayers:
  65. if playerID == dbplayer[0]:
  66. self.players.append((playerID, dbplayer[1]))
  67. # general information
  68. self.gameID =
  69. # get expansions used for this game
  70. getExpansions()
  71. # game state information
  72. self.state = 0 # 0 for main game, 1 for postgame, 2 for ended game
  73. self.ntile = 1 # number of tiles played
  74. self.nbuilder = 0 # number of tiles placed due to builders
  75. def getPlayers(self):
  76. """
  77. Get a list of possible players from the database
  78. """
  79. players = self.cur.execute('''SELECT * FROM players''').fetchall()
  80. if not len(players):
  81. _sys.stderr.write("Error: players table empty. Exiting.\n")
  82. _sys.exit(-1)
  83. return players
  84. def getExpansions(self):
  85. """
  86. Get a list of playable expansions
  87. """
  88. self.expansionIDs = []
  89. for minisel in range(0, 2):
  90. if minisel:
  91. exptype = "mini"
  92. else:
  93. exptype = "large"
  94. expans = self.cur.execute('''SELECT expansionID,name FROM expansions WHERE active==1 and mini=={0:d}'''.format(minisel)).fetchall()
  95. if len(expans):
  96. for dbexpan in dbexpan:
  97. print("{0:d}) ".format(dbexpan[0]) + dbexpan[1])
  98. expaninput = input("Please list the numbers for the " + exptype + " used in this game: ")
  99. expanIDs = [int(x) for x in expanplayer.input.split()]
  100. for expanID in expanID:
  101. for dbexpan in dbexpan:
  102. if expanID == dbexpan[0]:
  103. self.expansionIDs.append(expanID)
  104. else:
  105. sys.stdout.write("No active " + exptype + " expansions found. Continuing.\n")
  106. def recordScore(gameID, playerIDs, expansionIDs, cround, state):
  107. """
  108. Record a score event in the game
  109. """
  110. if state:
  111. ingame = 0
  112. pname = getPlayerNames(playerIDs)
  113. # for i, pname in enumerate(pname):
  114. pID = input("")
  115. # if the builder was used
  116. BUILDERUSED = True
  117. advanceTurn(cmdtime, gameID, playerID, nturn, builder=BUILDERUSED)
  118. return 0
  119. def advanceTurn(self, builder=False):
  120. """
  121. Make a new entry in the turns table
  122. """
  123. command = '''INSERT INTO turns VALUES ({0:d}, {1:d}, '''.format(self.gameID, self.nturn)
  124. command = command + cmdtime
  125. if builder:
  126. bID = 1
  127. else:
  128. bID = 0
  129. # compute playerID based on the turn number minus nbuilders / number of players
  130. playerID = playerIDs[(nturns - nbuilder) / lnen(playerIDs)]
  131. command = command + ', {0:d}, {1:d})'.format(bID, playerID)
  132. c.execute(command)
  133. self.nturn += 1
  134. if builder:
  135. self.nbuilder += 1
  136. def runGame(self):
  137. """
  138. Main routine for entering games
  139. """
  140. # here wait for input for scores, advancing to next round, or completion of game
  141. # for each step of entry, present a series of options, based on the list
  142. # of playerIDs and expansions
  143. while self.state < 2:
  144. # set up prompt based on current round
  145. if self.state:
  146. prompt = "postgame > "
  147. else:
  148. prompt = "round: {0:d}, turn: {1:d} > ".format(1 + _np.floor((self.nturn-self.nbuilder) / len(self.playerIDs)),
  149. self.nturn-self.nbuilder)
  150. try:
  151. text = input(prompt)
  152. except (EOFError, KeyboardInterrupt):
  153. _sys.stderr.write('Improper input. Please retry\n')
  154. showCommands()
  155. if _re.match('e', cmd, _re.IGNORECASE):
  156. advanceState()
  157. elif _re.match('s', cmd, _re.IGNORECASE):
  158. printStatus(tilestats=True)
  159. elif _re.match('n', cmd, _re.IGNORECASE):
  160. advanceTurn()
  161. elif _re.match('r', cmd, _re.IGNORECASE):
  162. recordScore()
  163. elif _re.match('t', cmd, _re.IGNORECASE):
  164. advanceTurn(builder=False)
  165. elif _re.match('b', cmd, _re.IGNORECASE):
  166. advanceTurn(builder=True)
  167. elif _re.match('?'. cmd, _re.IGNORECASE):
  168. showCommands()
  169. else:
  170. _sys.stderr.write('Command not understood. Please try again.\n')
  171. showCommands()
  172. if state == 2:
  173. #game is over. write end time to the games table
  174. time = _datetime.utcnow().strftime("%Y-%m-%dT%H:%M")
  175. c.execute('''UPDATE games SET endtime = "''' + time + '''" WHERE gameID = ''' + str(gameID))
  176. conn.commit()
  177. printStatus(tilestats=False)
  178. #### Is there a way to capture "ineffective" uses? For example,
  179. #### meeples that don't score points because they end up in a meadow that's
  180. #### controled by someone else?
  181. return 0
  182. def printStatus(self, tilestats=False):
  183. """
  184. Print the total score (current or final) for the specified gameID
  185. """
  186. for playerID in self.playerIDs:
  187. pname = c.execute('SELECT name FROM players WHERE playerID={0:d}'.format(playerID[0])).fetchall()[0]
  188. a = c.execute('SELECT points FROM scores WHER gameID={0:d} and playerID={1:d}'.format(self.gameID, playerID[0]))
  189. res = a.fetchall()
  190. score = _np.sum(res)
  191. print(pname + ': {0:d}'.format(score))
  192. print("{0:d} tiles played out of {1:d} total ({2:d} remaining).".format(self.ntiles,
  193. self.totaltiles,
  194. self.totaltiles - self.ntiles)