manage_database.py 15 KB

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