manage_database.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. #!/usr/bin/env python
  2. """
  3. Database management 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 sys
  17. import os
  18. import argparse
  19. import configparser
  20. import re
  21. import sqlite3
  22. def loadConfig(cfile):
  23. """
  24. Load configuration file
  25. """
  26. if not os.path.isfile(cfile):
  27. sys.stderr.write("Error: could not find configuration file '" + cfile + "'\n")
  28. sys.exit()
  29. config = configparser.read(cfile)
  30. return config
  31. def parseArgs():
  32. """
  33. Command line arguments
  34. """
  35. parser = argparse.ArgumentParser(description="Update the Carcassonne \
  36. scoring database.")
  37. parser.add_argument('-c', '--config', default='CarcassonneScore.conf',
  38. help='Location of the configuration file.')
  39. cmds = parser.add_mutually_exclusive_group(required=True)
  40. cmds.add_argument('--init', default=False, action='store_true',
  41. help='Create a fresh database.')
  42. cmds.add_argument('-n', '--newplayer', type=str, default=None,
  43. nargs='+',
  44. help='Add a new player.')
  45. cmds.add_argument('-e', '--enableexpansion', action='store_true',
  46. default=False,
  47. help='Enable an expansion.')
  48. cmds.add_argument('-d', '--disableexpansion', action='store_true',
  49. default=False,
  50. help='Disable an expansion.')
  51. return parser.parse_args()
  52. def initializeDB(c, DBVER):
  53. """
  54. Initialize Database
  55. """
  56. # player table
  57. c.execute('''CREATE TABLE players (playerID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
  58. name TEXT NOT NULL DEFAULT "")''')
  59. # player names
  60. c.execute('''INSERT INTO players values (0,
  61. "John Smith")''')
  62. c.execute('''INSERT INTO players values (1,
  63. "Jane Doe")''')
  64. # games table
  65. # gameID - unique ID
  66. # location - free text
  67. # starttime - timecode
  68. # endtime - timecode
  69. # expansions - comma-separated list of expansions used (by expansionID)
  70. c.execute('''CREATE TABLE games (gameID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
  71. location TEXT NOT NULL DEFAULT "",
  72. starttime TEXT NOT NULL DEFAULT "",
  73. endtime TEXT NOT NULL DEFAULT "",
  74. expansions TEXT NOT NULL DEFAULT "")''')
  75. # turns table
  76. # gameID - corresponds to games table
  77. # turnNum - incremented turn number (corresponds to a tile placement)
  78. # time - time at which the placement was made
  79. # builder - 0 if tile was placed as part of normal turn, 1 if placed
  80. # as a result of a builder token
  81. # playerID - player who made the turn
  82. c.execute('''CREATE TABLE turns (gameID INTEGER NOT NULL,
  83. turnNum INTEGER NOT NULL,
  84. time TEXT NOT NULL,
  85. builder INTEGER NOT NULL,
  86. playerID INTEGER NOT NULL)''')
  87. # individual scores
  88. # gameID - unique per game
  89. # playerID - corresponds to entry from players table
  90. # turnNum - turn number (corresponds to number in turns table)
  91. # scoreID - ID number for the score (unique to game?)
  92. # ingame - 1 if scored during regular play, 0 if scored after tiles are gone
  93. # points - number of points awarded
  94. # scoretype - road, city, meadow, etc.
  95. # sharedscore - was this score shared with another player?
  96. # token - token(s) used for score (e.g., meeple, wagon, pig)
  97. # extras - any other items (e.g., trade goods)
  98. # comments - text annotation
  99. c.execute('''CREATE TABLE scores (gameID INTEGER NOT NULL,
  100. playerID INTEGER NOT NULL,
  101. turnNum INTEGER NOT NULL,
  102. scoreID INTEGER NOT NULL,
  103. ingame INTEGER NOT NULL,
  104. points INTEGER NOT NULL,
  105. scoretype TEXT NOT NULL,
  106. sharedscore INTEGER NOT NULL,
  107. token TEXT NOT NULL,
  108. extras NOT NULL,
  109. comments TEXT)''')
  110. # list of expansions
  111. # mini - 1 if a mini expanion, otherwise 0
  112. # active - 1 if it can be played, otherwise 0
  113. # tokens - additional tokens provided beyond the base game
  114. # scoretypes - additional classes of scoring enabled
  115. # Ntiles - number of tiles added
  116. # tiletypes - special scorable tiles added
  117. c.execute('''CREATE TABLE expansions (expansionID INTEGER PRIMARY KEY,
  118. name TEXT NOT NULL,
  119. mini INTEGER,
  120. active INTEGER,
  121. tokens TEXT,
  122. scoretypes TEXT,
  123. Ntiles INTEGER,
  124. tiletypes TEXT)''')
  125. # large expansions
  126. # taken from http://carcassonne.wikia.com/wiki/Official_expansions
  127. # Only 1, 2, and 5 are currently populated
  128. c.execute('''INSERT INTO expansions values (1,
  129. "Inns & Cathedrals",
  130. 0,
  131. 1,
  132. "BigMeeple",
  133. "",
  134. 18,
  135. "Cathedral,InnonLake")''')
  136. c.execute('''INSERT INTO expansions values (2,
  137. "Traders & Builders",
  138. 0,
  139. 1,
  140. "Pig,Builder",
  141. "",
  142. 24,
  143. "TradeGoods")''')
  144. c.execute('''INSERT INTO expansions values (3,
  145. "Princess & Dragon",
  146. 0,
  147. 0,
  148. "",
  149. "",
  150. 0,
  151. "")''')
  152. c.execute('''INSERT INTO expansions values (4,
  153. "The Tower",
  154. 0,
  155. 0,
  156. "",
  157. "",
  158. 0,
  159. "")''')
  160. c.execute('''INSERT INTO expansions values (5,
  161. "Abbey & Mayor",
  162. 0,
  163. 1,
  164. "Mayor,Wagon,Barn",
  165. "",
  166. 12,
  167. "Abbey")''')
  168. c.execute('''INSERT INTO expansions values (6,
  169. "Count, King & Robber",
  170. 0,
  171. 0,
  172. "",
  173. "",
  174. 0,
  175. "")''')
  176. c.execute('''INSERT INTO expansions values (7,
  177. "The Catapult",
  178. 0,
  179. 0,
  180. "",
  181. "",
  182. 0,
  183. "")''')
  184. c.execute('''INSERT INTO expansions values (8,
  185. "Bridges, Castles & Bazaars",
  186. 0,
  187. 0,
  188. "",
  189. "",
  190. 0,
  191. "")''')
  192. c.execute('''INSERT INTO expansions values (9,
  193. "Hills & Sheep",
  194. 0,
  195. 0,
  196. "",
  197. "",
  198. 0,
  199. "")''')
  200. c.execute('''INSERT INTO expansions values (10,
  201. "Under the Big Top",
  202. 0,
  203. 0,
  204. "",
  205. "",
  206. 0,
  207. "")''')
  208. #mini expansions
  209. c.execute('''INSERT INTO expansions values(101,
  210. "The River",
  211. 1,
  212. 1,
  213. "",
  214. "",
  215. 12,
  216. "")''')
  217. c.execute('''INSERT INTO expansions values(102,
  218. "The Abbott",
  219. 1,
  220. 1,
  221. "Abbott",
  222. "Garden",
  223. 0,
  224. "")''')
  225. c.execute('PRAGMA user_version={0:1.0f}'.format(DBVER))
  226. def getExpans(cur, active=True):
  227. """
  228. Get a list of (in)active expansions
  229. """
  230. command = 'SELECT expansionID,name FROM expansions WHERE active='
  231. if active:
  232. command = command + '1'
  233. else:
  234. command = command + '0'
  235. return cur.execute(command).fetchall()
  236. def toggleExpan(cur, ID, activate=True):
  237. """
  238. Change the active status for an expansion
  239. """
  240. command = 'UPDATE expansions SET active='
  241. if activate:
  242. command = command + '1'
  243. elif not activate:
  244. command = command + '0'
  245. else:
  246. sys.stderr.write("What have you done?\n")
  247. sys.exit(-1)
  248. command = command + ' where expansionID={0:1.0f}'.format(ID)
  249. cur.execute(command)
  250. def main():
  251. """
  252. main routine
  253. """
  254. args = parseArgs()
  255. copts = loadConfig(args.config)
  256. DBNAME = 'CarcassonneScore.db'
  257. DBVER = 0
  258. if args.init and os.path.isfile(DBNAME):
  259. sys.stderr.write("Error: '" + DBNAME + "' already exists. Exiting.\n")
  260. sys.exit()
  261. conn = sqlite3.connect(DBNAME)
  262. cur = conn.cursor()
  263. VALID = False
  264. if args.init:
  265. initializeDB(cur, DBVER)
  266. elif args.newplayer:
  267. pname = ' '.join(args.newplayer)
  268. sys.stdout.write("Adding new player: " + pname)
  269. sys.stdout.write(" to the database.\n")
  270. while not VALID:
  271. ans = input("Is this correct (y/n)? ")
  272. if re.match('y', ans, re.IGNORECASE):
  273. cur.execute('INSERT INTO players (name) VALUES ("' + \
  274. pname + '")')
  275. sys.stdout.write(pname + ' added to the database.\n')
  276. VALID = True
  277. elif re.match('n', ans, re.IGNORECASE):
  278. sys.stdout.write('Canceling.\n')
  279. VALID = True
  280. elif args.enableexpansion:
  281. expans = getExpans(cur, active=False)
  282. kwds = ("enable", "inactive")
  283. activate = True
  284. elif args.disableexpansion:
  285. expans = getExpans(cur, active=True)
  286. kwds = ("disable", "active")
  287. activate = False
  288. if args.enableexpansion or args.disableexpansion:
  289. expnumlist = []
  290. for expan in expans:
  291. expnumlist.append(int(expan[0]))
  292. sys.stdout.write("{0:1.0f}) ".format(expan[0]) + expan[1] + "\n")
  293. try:
  294. toggleexp = input("Please enter the " + kwds[1] + ' expansion to ' + kwds[0] + ': ')
  295. if not list:
  296. sys.stderr.write("No expansions specified. Exiting.\n")
  297. except (EOFError, KeyboardInterrupt):
  298. conn.close()
  299. sys.exit()
  300. #TODO actually update the expansions
  301. try:
  302. toggleexp = int(toggleexp)
  303. except:
  304. sys.stderr.write("Error: invalid input. Please enter a number from the list next time.\n")
  305. sys.exit()
  306. if toggleexp not in expnumlist:
  307. sys.stderr.write("Error: invalid input. Please enter a number from the list next time.\n")
  308. sys.exit()
  309. toggleExpan(cur, toggleexp, activate=activate)
  310. conn.commit()
  311. conn.close()
  312. if __name__ == "__main__":
  313. main()