manage_database.py 14 KB

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