1
0

manage_database.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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. if os.path.isfile('CarcassonneScore.conf.example'):
  29. sys.stderr.write("Copying 'CarcassonneScore.conf.example' to 'CarcassonneScore.conf'.\n")
  30. import shutil
  31. shutil.copyfile('CarcassonneScore.conf.example',
  32. 'CarcassonneScore.conf')
  33. else:
  34. sys.stderr.write("Error: cannot find default configuration file 'CarcassonneScore.conf.example' to copy.\n")
  35. config = configparser.RawConfigParser()
  36. config.read(cfile)
  37. return config
  38. def parseArgs():
  39. """
  40. Command line arguments
  41. """
  42. parser = argparse.ArgumentParser(description="Update the Carcassonne \
  43. scoring database.")
  44. parser.add_argument('-c', '--config', default='CarcassonneScore.conf',
  45. help='Location of the configuration file.')
  46. cmds = parser.add_mutually_exclusive_group(required=True)
  47. cmds.add_argument('--init', default=False, action='store_true',
  48. help='Create a fresh database.')
  49. cmds.add_argument('--migrate', default=False, action='store_true',
  50. help='Update database to a new version.')
  51. cmds.add_argument('-n', '--newplayer', type=str, default=None,
  52. nargs='+',
  53. help='Add a new player.')
  54. cmds.add_argument('-pa', '--playeractivate', action='store_true',
  55. default=False,
  56. help='activate a player.')
  57. cmds.add_argument('-pd', '--playerdeactivate', action='store_true',
  58. default=False,
  59. help='Deactivate a player.')
  60. cmds.add_argument('-e', '--enableexpansion', action='store_true',
  61. default=False,
  62. help='Enable an expansion.')
  63. cmds.add_argument('-d', '--disableexpansion', action='store_true',
  64. default=False,
  65. help='Disable an expansion.')
  66. return parser.parse_args()
  67. def initializeDB(c, DBVER):
  68. """
  69. Initialize Database
  70. """
  71. # player table
  72. c.execute('''CREATE TABLE players (playerID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
  73. name TEXT NOT NULL DEFAULT "")''')
  74. # player names
  75. c.execute('''INSERT INTO players values (0,
  76. "John Smith")''')
  77. c.execute('''INSERT INTO players values (1,
  78. "Jane Doe")''')
  79. # games table
  80. # gameID - unique ID
  81. # location - free text
  82. # starttime - timecode
  83. # endtime - timecode
  84. # expansions - comma-separated list of expansions used (by expansionID)
  85. c.execute('''CREATE TABLE games (gameID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
  86. location TEXT NOT NULL DEFAULT "",
  87. starttime TEXT NOT NULL DEFAULT "",
  88. endtime TEXT NOT NULL DEFAULT "",
  89. expansions TEXT NOT NULL DEFAULT "")''')
  90. # turns table
  91. # gameID - corresponds to games table
  92. # turnNum - incremented turn number (corresponds to a tile placement)
  93. # time - time at which the placement was made
  94. # builder - 0 if tile was placed as part of normal turn, 1 if placed
  95. # as a result of a builder token
  96. # playerID - player who made the turn
  97. c.execute('''CREATE TABLE turns (gameID INTEGER NOT NULL,
  98. turnNum INTEGER NOT NULL,
  99. time TEXT NOT NULL,
  100. builder INTEGER NOT NULL,
  101. playerID INTEGER NOT NULL)''')
  102. # individual scores
  103. # gameID - unique per game
  104. # playerID - corresponds to entry from players table
  105. # turnNum - turn number (corresponds to number in turns table)
  106. # scoreID - ID number for the score (unique to game?)
  107. # ingame - 1 if scored during regular play, 0 if scored after tiles are gone
  108. # points - number of points awarded
  109. # scoretype - road, city, meadow, etc.
  110. # sharedscore - was this score shared with another player?
  111. # token - token(s) used for score (e.g., meeple, wagon, pig)
  112. # extras - any other items (e.g., trade goods)
  113. # comments - text annotation
  114. c.execute('''CREATE TABLE scores (gameID INTEGER NOT NULL,
  115. playerID INTEGER NOT NULL,
  116. turnNum INTEGER NOT NULL,
  117. scoreID INTEGER NOT NULL,
  118. ingame INTEGER NOT NULL,
  119. points INTEGER NOT NULL,
  120. scoretype TEXT NOT NULL,
  121. sharedscore INTEGER NOT NULL,
  122. token TEXT NOT NULL,
  123. extras NOT NULL,
  124. comments TEXT)''')
  125. # list of expansions
  126. # mini - 1 if a mini expanion, otherwise 0
  127. # active - 1 if it can be played, otherwise 0
  128. # tokens - additional tokens provided beyond the base game
  129. # scoretypes - additional classes of scoring enabled
  130. # Ntiles - number of tiles added
  131. # tiletypes - special scorable tiles added
  132. c.execute('''CREATE TABLE expansions (expansionID INTEGER PRIMARY KEY,
  133. name TEXT NOT NULL,
  134. mini INTEGER,
  135. active INTEGER,
  136. tokens TEXT,
  137. scoretypes TEXT,
  138. Ntiles INTEGER,
  139. tiletypes TEXT)''')
  140. # large expansions
  141. # taken from http://carcassonne.wikia.com/wiki/Official_expansions
  142. # Only 1, 2, and 5 are currently populated
  143. c.execute('''INSERT INTO expansions values (1,
  144. "Inns & Cathedrals",
  145. 0,
  146. 1,
  147. "BigMeeple",
  148. "",
  149. 18,
  150. "Cathedral,InnonLake")''')
  151. c.execute('''INSERT INTO expansions values (2,
  152. "Traders & Builders",
  153. 0,
  154. 1,
  155. "Pig,Builder",
  156. "",
  157. 24,
  158. "TradeGoods")''')
  159. c.execute('''INSERT INTO expansions values (3,
  160. "Princess & Dragon",
  161. 0,
  162. 0,
  163. "Dragon,Fairy",
  164. "",
  165. 30,
  166. "")''')
  167. c.execute('''INSERT INTO expansions values (4,
  168. "The Tower",
  169. 0,
  170. 0,
  171. "",
  172. "",
  173. 0,
  174. "")''')
  175. c.execute('''INSERT INTO expansions values (5,
  176. "Abbey & Mayor",
  177. 0,
  178. 1,
  179. "Mayor,Wagon,Barn",
  180. "Abbey",
  181. 12,
  182. "Abbey")''')
  183. c.execute('''INSERT INTO expansions values (6,
  184. "Count, King & Robber",
  185. 0,
  186. 0,
  187. "",
  188. "",
  189. 0,
  190. "")''')
  191. c.execute('''INSERT INTO expansions values (7,
  192. "The Catapult",
  193. 0,
  194. 0,
  195. "",
  196. "",
  197. 0,
  198. "")''')
  199. c.execute('''INSERT INTO expansions values (8,
  200. "Bridges, Castles & Bazaars",
  201. 0,
  202. 0,
  203. "",
  204. "",
  205. 0,
  206. "")''')
  207. c.execute('''INSERT INTO expansions values (9,
  208. "Hills & Sheep",
  209. 0,
  210. 0,
  211. "Shepherd",
  212. "Flock",
  213. 18,
  214. "Hill,Vineyard")''')
  215. c.execute('''INSERT INTO expansions values (10,
  216. "Under the Big Top",
  217. 0,
  218. 0,
  219. "",
  220. "",
  221. 0,
  222. "")''')
  223. #mini expansions
  224. c.execute('''INSERT INTO expansions values(101,
  225. "The River",
  226. 1,
  227. 1,
  228. "",
  229. "",
  230. 12,
  231. "")''')
  232. c.execute('''INSERT INTO expansions values(102,
  233. "The Abbott",
  234. 1,
  235. 1,
  236. "Abbott",
  237. "Garden",
  238. 0,
  239. "")''')
  240. c.execute('PRAGMA user_version={0:1.0f}'.format(DBVER))
  241. def getPlayers(cur, active=True):
  242. """
  243. Get a list of (in)active expansions
  244. """
  245. command = 'SELECT playerID,name FROM players WHERE active='
  246. if active:
  247. command = command + '1'
  248. else:
  249. command = command + '0'
  250. return cur.execute(command).fetchall()
  251. def togglePlayer(cur, ID, activate=True):
  252. """
  253. Change the active status for a player
  254. """
  255. command = 'UPDATE players SET active='
  256. if activate:
  257. command = command + '1'
  258. elif not activate:
  259. command = command + '0'
  260. else:
  261. sys.stderr.write("What have you done?\n")
  262. sys.exit(-1)
  263. command = command + ' where playerID={0:1.0f}'.format(ID)
  264. cur.execute(command)
  265. def getExpans(cur, active=True):
  266. """
  267. Get a list of (in)active expansions
  268. """
  269. command = 'SELECT expansionID,name FROM expansions WHERE active='
  270. if active:
  271. command = command + '1'
  272. else:
  273. command = command + '0'
  274. return cur.execute(command).fetchall()
  275. def toggleExpan(cur, ID, activate=True):
  276. """
  277. Change the active status for an expansion
  278. """
  279. command = 'UPDATE expansions SET active='
  280. if activate:
  281. command = command + '1'
  282. elif not activate:
  283. command = command + '0'
  284. else:
  285. sys.stderr.write("What have you done?\n")
  286. sys.exit(-1)
  287. command = command + ' where expansionID={0:1.0f}'.format(ID)
  288. cur.execute(command)
  289. def migratedb(cur, newDBVER):
  290. """
  291. Automatically migrate a Carcassonne sqlite database to a newer schema
  292. """
  293. # get USER_VERSION from the Sqlite3 database
  294. curDBVER = cur.execute("PRAGMA user_version").fetchall()[0][0]
  295. # Check if it is the same as the new version
  296. # - If it is, print a message that no migration is needed, then exit
  297. if curDBVER == newDBVER:
  298. sys.stderr.write("Database schema is up to date, no migration needed.\n")
  299. sys.exit()
  300. # If migration is needed, step through each upgrade step and execute it
  301. if curDBVER == 0:
  302. # make changes from DBVER 0 to DBVER 1
  303. cur.execute("ALTER TABLE players ADD COLUMN active INTEGER NOT NULL DEFAULT 1;")
  304. cur.execute("PRAGMA user_version={0:d}".format(1))
  305. curDBVER = 1
  306. def main():
  307. """
  308. main routine
  309. """
  310. args = parseArgs()
  311. copts = loadConfig(args.config)
  312. DBNAME = 'CarcassonneScore.db'
  313. DBVER = 1
  314. if args.init and os.path.isfile(DBNAME):
  315. sys.stderr.write("Error: '" + DBNAME + "' already exists. Exiting.\n")
  316. sys.exit()
  317. conn = sqlite3.connect(DBNAME)
  318. cur = conn.cursor()
  319. VALID = False
  320. if args.init:
  321. # create initial database
  322. initializeDB(cur, 0)
  323. # migrate it to the current version
  324. migratedb(cur, DBVER)
  325. if args.migrate:
  326. migratedb(cur, DBVER)
  327. elif args.newplayer:
  328. pname = ' '.join(args.newplayer)
  329. sys.stdout.write("Adding new player: " + pname)
  330. sys.stdout.write(" to the database.\n")
  331. while not VALID:
  332. ans = input("Is this correct (y/n)? ")
  333. if re.match('y', ans, re.IGNORECASE):
  334. cur.execute('INSERT INTO players (name) VALUES ("' + \
  335. pname + '")')
  336. sys.stdout.write(pname + ' added to the database.\n')
  337. VALID = True
  338. elif re.match('n', ans, re.IGNORECASE):
  339. sys.stdout.write('Canceling.\n')
  340. VALID = True
  341. elif args.playeractivate:
  342. players = getPlayers(cur, active=False)
  343. kwds = ("enable", "inactive")
  344. activate = True
  345. elif args.playerdeactivate:
  346. players = getPlayers(cur, active=True)
  347. kwds = ("disable", "active")
  348. activate = False
  349. elif args.enableexpansion:
  350. expans = getExpans(cur, active=False)
  351. kwds = ("enable", "inactive")
  352. activate = True
  353. elif args.disableexpansion:
  354. expans = getExpans(cur, active=True)
  355. kwds = ("disable", "active")
  356. activate = False
  357. # handle expansion toggling
  358. if args.enableexpansion or args.disableexpansion:
  359. expnumlist = []
  360. for expan in expans:
  361. expnumlist.append(int(expan[0]))
  362. sys.stdout.write("{0:1.0f}) ".format(expan[0]) + expan[1] + "\n")
  363. try:
  364. toggleexp = input("Please enter the " + kwds[1] + ' expansion to ' + kwds[0] + ': ')
  365. if not list:
  366. sys.stderr.write("No expansions specified. Exiting.\n")
  367. except (EOFError, KeyboardInterrupt):
  368. conn.close()
  369. sys.exit()
  370. try:
  371. toggleexp = int(toggleexp)
  372. except:
  373. sys.stderr.write("Error: invalid input. Please enter a number from the list next time.\n")
  374. sys.exit()
  375. if toggleexp not in expnumlist:
  376. sys.stderr.write("Error: invalid input. Please enter a number from the list next time.\n")
  377. sys.exit()
  378. toggleExpan(cur, toggleexp, activate=activate)
  379. # handle player toggling
  380. if args.playeractivate or args.playerdeactivate:
  381. playernumlist = []
  382. for player in players:
  383. playernumlist.append(int(player[0]))
  384. sys.stdout.write("{0:1.0f}) ".format(player[0]) + player[1] + "\n")
  385. try:
  386. toggleplayer = input("Please enter the " + kwds[1] + ' player to ' + kwds[0] + ': ')
  387. if not list:
  388. sys.stderr.write("No player specified. Exiting.\n")
  389. except (EOFError, KeyboardInterrupt):
  390. conn.close()
  391. sys.exit()
  392. try:
  393. toggleplayer = int(toggleplayer)
  394. except:
  395. sys.stderr.write("Error: invalid input. Please enter a number from the list next time.\n")
  396. sys.exit()
  397. if toggleplayer not in playernumlist:
  398. sys.stderr.write("Error: invalid input. Please enter a number from the list next time.\n")
  399. sys.exit()
  400. togglePlayer(cur, toggleplayer, activate=activate)
  401. conn.commit()
  402. conn.close()
  403. if __name__ == "__main__":
  404. main()