Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sqlite3
- from random import randint
- from time import time
- import sys
- def getConnection():
- #create connection to the database
- print('Creating connection to the Database')
- conn = ''
- try:
- conn = sqlite3.connect('computer_cards.db')
- except Exception as ex:
- print('Failed to establish connection to database - {}'.format(ex))
- conn = ''
- return conn
- def closeConnection(conn):
- #close connection to database
- print('Closing connection to the Database')
- try:
- conn.close()
- except Exception as ex:
- print('Error closing connection {}'.format(ex))
- def clearTable(conn):
- #clear all records from the picked table
- try:
- sql = "DELETE FROM picked"
- cursor = conn.execute(sql)
- conn.commit()
- print('Rows deleted - {}'.format(cursor.rowcount))
- except Exception as ex:
- print('Failed to clear table - {}'.format(ex))
- def getCards(conn):
- #create list of all card names from the computer table
- try:
- result = conn.execute("SELECT name FROM computer")
- return result.fetchall()
- except Exception as ex:
- print('Failed to get table - {}'.format(ex))
- return ''
- def displayRecords(conn):
- cursor = conn.execute('SELECT * FROM picked')
- records = cursor.fetchall()
- for record in records:
- print(record)
- def pickAnotherCard(conn):
- response = input('Pick Another Card? ').strip().upper()
- if response == 'D':
- displayRecords(conn)
- response = 'Y'
- return (response == 'Y')
- def addCard(conn,name):
- #add card to the picked table
- try:
- sql = "INSERT INTO picked(name, time) VALUES ('{}', {})".format(name,time())
- cursor = conn.execute(sql)
- conn.commit()
- print('Added {}'.format(name))
- except Exception as ex:
- print('Failed to enter card {} - {}'.format(name, ex))
- def getLastCard(conn):
- try:
- result = conn.execute("SELECT name FROM picked ORDER BY time DESC")
- return result.fetchone()[0]
- except Exception as ex:
- print('Error getting last card picked, table empty - {}'.format(ex))
- return ''
- def mainLoop(conn):
- #pick random cards and add to picked table
- pickCard = True
- while pickCard:
- cards = getCards(conn)
- if cards != '':
- lastCard = getLastCard(conn)
- random_card = cards[randint(0, len(cards) - 1)][0]
- while lastCard == random_card:
- print('LOOPING')
- random_card = cards[randint(0, len(cards) - 1)][0]
- addCard(conn,random_card)
- pickCard = pickAnotherCard(conn)
- else:
- pickCard = False
- #Main Program
- conn = getConnection()
- if conn != '':
- clearTable(conn)
- mainLoop(conn)
- displayRecords(conn)
- closeConnection(conn)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement