コード例 #1
0
 def enemy_turn(player, enemy, run_away):
     # If run away is not true, continue the fight
     if run_away == 0:
         if player.current_hitpoints <= 0:
             bad_end()
         elif enemy.hitpoints >= 1:
             print("================================= \nENEMY TURN:")
             time.sleep(1)
             combat_damage = enemy.damage
             combat_damage -= player.armor
             if combat_damage > 0:
                 player.current_hitpoints -= combat_damage
                 print("The " + str(enemy.name) + " hit you for " +
                       str(combat_damage) + " damage after " +
                       str(player.armor) + " was blocked by your armor!")
                 time.sleep(1)
                 print("Player HP: " + str(player.current_hitpoints) + "/" +
                       str(player.max_hitpoints))
                 # check if player is dead
                 if player.current_hitpoints <= 0:
                     print("================================= \n")
                     bad_end()
                 else:
                     print("================================= \n")
                     clear(1)
                     players_turn(player, enemy, run_away)
             else:
                 print("Your armor protects you from the " +
                       str(enemy.name) + "! ")
                 clear(1)
                 players_turn(player, enemy, run_away)
         else:
             print("the enemy should be dead!")
     else:
         print("the player should have ran away!")
コード例 #2
0
def guestLogin():
    utility.clear()
    print(
        "------------------------------WELCOME Guest----------------------------"
    )
    guest = Guest()
    utility.guestOperations(guest)
コード例 #3
0
def home():
    choice = 10
    while choice != '4':
        utility.clear()
        print(
            "----------------------------WELCOME TO SUPERMARKET--------------------------"
        )
        print("")
        print("Tell us who you are? (Press the number)")
        print("\t1.Guest?")
        print("\t2.Customer?")
        print("\t3.Admin?")
        print("\t4.Exit?")
        choice = raw_input()
        if choice == '1':
            guestLogin()
            # raw_input()
        elif choice == '2':
            customerLogin()
            raw_input()
        elif choice == '3':
            adminLogin()
            raw_input()
        # utility.clear()
    else:
        utility.clear()
        utility.persist()
        print("Thanks for shopping..")
コード例 #4
0
def adminLogin():
    admin = login("admin")
    if admin:
        utility.clear()
        print("------------------------------WELCOME ADMIN " +
              (admin.name).upper() + "----------------------------")
        utility.adminOperations(admin)
    else:
        print("Invalid Id/Id should be a number")
コード例 #5
0
 def encounter(player):
     global active_game
     """Encounter is the function that initiates the combat scene between the player and an enemy."""
     # Set run away to 0, which is no.
     run_away = 0
     # Create a randomized enemy.
     create_random_enemy()
     print("\nA " + str(enemy.name) + " has appeared! \n")
     time.sleep(0.5)
     # Decide who goes first influenced by player age.
     turn_order = randint(1, 100)
     print("Deciding turn order...")
     time.sleep(0.5)
     print("You rolled: " + str(turn_order) + " out of 100. ")
     clear(1)
     if player.age <= 16:
         if turn_order <= 90:
             player_first = 1
         else:
             player_first = 0
     elif player.age <= 30:
         if turn_order <= 50:
             player_first = 1
         else:
             player_first = 0
     elif player.age <= 60:
         if turn_order <= 35:
             player_first = 1
         else:
             player_first = 0
     elif player.age <= 80:
         if turn_order <= 20:
             player_first = 1
         else:
             player_first = 0
     # Check who goes first.
     if player_first == 0:
         print("The " + str(enemy.name) +
               " takes action before you can react! \n")
         time.sleep(0.5)
         enemy_turn(player, enemy, run_away)
     elif player_first == 1:
         print("You're able to act before the " + str(enemy.name) +
               " realizes! \n")
         time.sleep(0.5)
         players_turn(player, enemy, run_away)
     print("The encounter is over! ")
     print("=================================")
     clear(2)
     # break out of the game loop if player is dead.
     if active_game == 1:
         wilderness()
コード例 #6
0
 def details(self):
     """This is a clear description of player information."""
     print("CHARACTER SHEET: \nName: " +
           str(self.name).capitalize() + ". \nAge: " +
           str(self.age) + ". \nClass: " + str(self.char_class) +
           ". \nEndurance: " + str(self.endurance) +
           ". \nStrength: " + str(self.strength) +
           ". \nHitpoints: " + str(self.current_hitpoints) + "/" +
           str(self.max_hitpoints) + ". \nDamage: " +
           str(self.damage) + ". \nArmor: " + str(self.armor) +
           ". \nLevel: " + str(self.level) +
           ". \nAttribute Points: " + str(self.attribute_points) +
           ". \nCurrent Experience: " +
           str(self.current_experience) +
           ". \nExp to next Level: " + str(self.next_level_exp) +
           ". \nGold: " + str(self.gold) + ". \nCurrent Weapon: " +
           str(self.current_weapon) + ". \nCurrnet Armor: " +
           str(self.current_armor) + ". \nInventory: " +
           str(self.inventory))
     clear(1)
コード例 #7
0
def keyInvCheck():
    keyInvQuery = '''
    SELECT * 
    FROM keyInventory
    GROUP BY keyNum, invCount;
    '''

    try:
        clear()
        print('Connecting to database...')
        db = pyodbc.connect(Driver= DVNAME,
                            Server= SVNAME,
                            Database=DBNAME,
                            trusted_connection='yes')      
        c1 = db.cursor()
        c1.execute(keyInvQuery)
        results = c1.fetchall()
        clear()
        print(tabulate(results, headers=['Key #', 'Inventory ct.'], tablefmt='psql'))
        input("Press enter to return to previous menu...")
        db.close()
        clear()
    except Exception:
        raise
        input("Press enter to close...")
        db.close()
コード例 #8
0
def avgBalPop():
    insertAvgBal = '''
    INSERT INTO ordersFilled
    VALUES ('{}-01 13:13:13.130', 'avgBal', {}, 9999, 0, 9999);
    '''

    keyInventory = '''
    SELECT keyNum from keyInventory;
    '''

    try:
        clear()
        # Connect to db
        print('Connecting to database...')
        db = pyodbc.connect(Driver= DVNAME,
                            Server= SVNAME,
                            Database=DBNAME,
                            trusted_connection='yes')

        # Get all keyNums in inventory and store in an array
        c1 = db.cursor()
        c1.execute(keyInventory)
        c1results = c1.fetchall()

        # Get current YYYY-MM
        c3 = db.cursor()
        c3.execute("SELECT CONVERT(CHAR(7),GETDATE(),120) AS YYYY_MM")
        c3result = c3.fetchone()
        currentYearMonth = c3result.YYYY_MM

        # Check to see if avgBal orders have already been created this month
        c4 = db.cursor()
        c4.execute("SELECT keyNum FROM ordersFilled WHERE orderNum = 'avgBal' AND CONVERT(CHAR(7),submit_time,120) = CONVERT(CHAR(7),GETDATE(),120)")
        c4result = c4.fetchone()
        # if avgBal's already exist this month, do nothing
        # otherwise, create one for every key
        if c4result:
            db.close()
            clear()
        else:
            for i in c1results:
                targetKey = i.keyNum
                c2 = db.cursor()
                c2.execute(insertAvgBal.format(currentYearMonth, targetKey))
                c2.commit()
            db.close()
            clear()

    except Exception:
        raise
        input("Press enter to close...")
        db.close()
コード例 #9
0
def dbMenu():
    dbMenu = True

    while dbMenu == True:
        print("Database: {}".format(DBNAME))
        divider()
        u_Action = None
        u_Action = input("What would you like to check? \n\nOptions:  Key Inv. - Low stock keys - Key stats - View Orders - Manual Inv Update | Back\n \n    ")
        if "Low" in u_Action or "low" in u_Action or "LOW" in u_Action:
                lowStockCheck()
        elif "Inv" in u_Action or "inv" in u_Action or "INV" in u_Action:
                keyInvCheck()
        elif "stats" in u_Action or "Stats" in u_Action or "STATS" in u_Action:
                invStats()
        elif "man" in u_Action or "MAN" in u_Action or "Man" in u_Action:
                manUpdate()
        elif "back" in u_Action or "Back" in u_Action or "BACK" in u_Action:
            clear()
            dbMenu = False
        elif u_Action == "quit" or u_Action == "QUIT" or "Quit" in u_Action:
            clear()
            sys.exit()
        elif u_Action == "help" or u_Action == "HELP" or u_Action == "Help":
            clear()
            divider()
            print('Command Guide:\n\n'
                '(Key) Inv(.): Displays all keys tracked in inventory and their current inv. count. \n'
                '\nLow (stock keys): Use this to check which keys need to be resupplied. \n'
                '\n(Key) Stats: Use this to view various stats for each key. \n'
                '\nView (orders): Use this to view order history. \n'
                '\nMan(ual Inv Update): Use this to manual update inventory count for a key without logging it as an order filled. \n'
                '\nBack: Return to the previous menu. \n'
                '\nQuit: Close the program. Duh! \n')
            divider()
        elif "view" in u_Action or "View" in u_Action or "VIEW" in u_Action:
            orderHistory()
        else:
            clear()
            print('Input not valid.\n'
             'TIP: If you don''t know what to type, try entering, \"help\".')
            divider()
コード例 #10
0
    def church():
        """The Church function is the only mechanic implemented where the player can recover lost hitpoints
		   but they have to pay gold."""
        if player.current_hitpoints <= 0:
            bad_end()
        else:
            action = ""
            heal_cost = player.level + 10
            print("=================================")
            print("You entered the church and are greeted by a priest. ")
            time.sleep(1)
            print("Priest: 'Do you want to be healed?' ")
            time.sleep(1)
            print("Priest: 'It only costs " + str(heal_cost) +
                  " gold for you.' ")
            time.sleep(1)
            print("Current gold: " + str(player.gold) + ". ")
            while action != "yes" or "no":
                action = input(str(player.name) + ": ").lower()
                clear(1)
                if "yes" in action:
                    if player.gold >= heal_cost:
                        player.gold -= heal_cost
                        clear(1)
                        print("Current HP: " + str(player.current_hitpoints) +
                              "/" + str(player.max_hitpoints))
                        heal_amount = player.max_hitpoints - player.current_hitpoints
                        player.current_hitpoints += heal_amount
                        print("The priest is tending to your wounds... ")
                        clear(3)
                        print("You recovered " + str(heal_amount) + "HP. ")
                        print("\nCurrent HP: " +
                              str(player.current_hitpoints) + "/" +
                              str(player.max_hitpoints))
                        print("Current gold: " + str(player.gold))
                        print("=================================")
                        clear(2)
                        town()
                        break
                    elif player.gold < heal_cost:
                        clear(1)
                        print(
                            "You don't have enough gold. But Please come back when you do. "
                        )
                        print("You leave the church. ")
                        print("=================================")
                        clear(2)
                        town()
                        break
                elif "no" in action:
                    print(
                        "Priest: 'Maybe next time...' \nYou leave the church. "
                    )
                    print("=================================")
                    clear(2)
                    town()
                    break
                else:
                    print(
                        "Priest: 'Sorry, I'm hard of hearing. Did you say yes or no? "
                    )
コード例 #11
0
def invStats():
    invStatsQuery = '''
    WITH t1 AS
    (
    SELECT keyNum, keysUsed, CONVERT(CHAR(7),submit_time,120) Dates
    FROM ordersFilled
    WHERE CONVERT(CHAR(7),submit_time,120) != CONVERT(CHAR(7),GETDATE(),120)
    GROUP BY keyNum, submit_time, keysUsed
    ),
    t2 AS
    (
    SELECT keyNum, (count(keyNum)-1) ordersPerMonth, Dates
    FROM t1
    GROUP BY keyNum, Dates
    ),
    t3 AS
    (
    SELECT keyNum, AVG(ordersPerMonth) avgOrdersPerMonth
    FROM t2
    GROUP BY keyNum
    ),
    t4 AS
    (
    SELECT keyNum, MAX(submit_time) lastSubmission
    FROM ordersFilled
    WHERE orderNum != 'avgBal'
    GROUP BY keyNum
    ),
    t5 AS
    (
    SELECT keyNum, keysUsed, COUNT(keysUsed) countVal
    FROM ordersFilled
    WHERE orderNum != 'avgBal'
    GROUP BY keyNum, keysUsed
    ),
    t6 AS
    (
    SELECT keyNum, MAX(countVal) maxCountVal
    FROM t5
    GROUP BY keyNum
    ),
    t7 AS
    (
    SELECT x.keyNum, y.keysUsed
    FROM t5 y, t6 x
    WHERE countVal = maxCountVal AND x.keyNum = y.keyNum
    ),
    t8 AS
    (
    SELECT keyNum, commonOrderSize
    FROM
    (
    select keyNum, max(keysUsed) commonOrderSize
    FROM t7
    GROUP BY keyNum
    ) a
    GROUP BY keyNum, commonOrderSize
    ),
    t9 AS
    (
    SELECT keyNum, SUM(keysUsed) totalUsed, Dates
    FROM t1
    GROUP BY Dates, keyNum
    ),
    t10 AS
    (
    SELECT keyNum, AVG(totalUsed) avgTotalPerMonth
    FROM t9
    GROUP BY keyNum
    )
    SELECT a.keyNum, e.avgTotalPerMonth, d.commonOrderSize, c.avgOrdersPerMonth, b.lastSubmission
    FROM t1 a, t4 b, t3 c, t8 d, t10 e
    WHERE a.keyNum = b.keyNum AND b.keyNum = c.keyNum AND c.keyNum = d.keyNum AND d.keyNum = e.keyNum
    GROUP BY a.keyNum, e.avgTotalPerMonth, c.avgOrdersPerMonth, d.commonOrderSize, b.lastSubmission;
    '''

    try:
        clear()
        print('Connecting to database...')
        db = pyodbc.connect(Driver= DVNAME,
                            Server= SVNAME,
                            Database=DBNAME,
                            trusted_connection='yes')               
        c1 = db.cursor()
        c1.execute(invStatsQuery)
        results = c1.fetchall()
        clear()
        print(tabulate(results, headers=['Key #', 'Avg. Lased Monthly', 'Popular Order Size', 'Avg. Orders Monthly', 'Most Recent Date Lased'], tablefmt='psql'))
        input("Press enter to return to previous menu...")
        db.close()
        clear()
    except Exception:
        raise
        input("Press enter to close...")
        db.close()
コード例 #12
0
def newKey():
    #Controls all encompassing loop
    moreToAdd = True

    #Controls while loop to decide if the user is going to add more keys to the inventory
    addMore = None

    #Determines wether user has approved the information to be committed
    confirmed = None

    #Contains entire script, loops until user says they don't have anymore keys to add
    while moreToAdd != False:
        try:
            #Prompt user for new key information
            clear()
            #Loop runs until user confirms the information they entered is correct
            while confirmed !="yes":
                print('Add a new key to the inventory by entering the key info below.')
                divider()
                u_keyNum = input('Key ID # (i.e. key #29): #')
                clear()
                print('Add a new key to the inventory by entering the key info below.')
                divider()
                u_invCount = input('How many {}''s do we have to start with? '.format(u_keyNum,))
                clear()
                #Display info and have user confirm if it's correct before continuing
                divider()
                print( " Create and track Key #{} starting at a inventory count of {}?".format(
                    u_keyNum, u_invCount,) )
                divider()
                confirmed = input("Are you sure the information above is correct? ")
                #If yes then insert this information into the database
                if confirmed == 'yes':
                    clear()
                elif confirmed == 'no':
                    clear()
                    print('Re-enter the information. \n')
                else:
                    clear()
                    print("Must answer yes or no, it's case sensitive because I'm lazy! \n")
            #Reset confirmed for future runs through the loop
            confirmed = "no"
            #Convert the user input to integer values for database compatibility
            u_keyNum = int(u_keyNum)
            u_invCount = int(u_invCount)
            #connect to db
            print('Connecting to database...')
            db = pyodbc.connect(Driver= DVNAME,
                                Server= SVNAME,
                                Database=DBNAME,
                                trusted_connection='yes')
            #Tracks wether or not there is currently an open connection to the database
            openConn = True
            #cursor 1 to ensure that the key doesn't already exist in the database
            c1 = db.cursor()
            c1.execute("SELECT keyNum FROM keyInventory WHERE keyNum = ?;", (u_keyNum,))
            #Check to see if c1 got any results, if it did, the key already exists in DB
            try:
                if (c1.fetchall()[0][0]) > 0:
                    #clear()
                    if openConn ==True:
                        db.close()
                        openConn = False
                    divider()
                    print("Error: It looks like a key with this ID # is already being tracked in the database!")
                    divider()
                    input("Press enter to close...")
                    sys.exit()
            except IndexError:
                #clear()
                pass
            #As long as c1 didn't return anything, the code will continue
            #cursor 2 Insert the new key info into the database
            c2 = db.cursor()
            c2.execute("INSERT INTO keyInventory VALUES (?, ?);", (u_keyNum, u_invCount,))
            c2.commit()
            print("Success! This new key has been added to the database.\n")
            divider()
            #Loop to ask if user would like to add more new keys to the database
            #ensure moreToAdd value is clear
            addMore = None
            while addMore != "yes" and addMore != "no":
                addMore = input("Would you like to add more new keys to the database? ")
                if addMore == 'yes':
                    moreToAdd = True
                elif addMore == 'no':
                    moreToAdd = False
                    clear()
                else:
                    clear()
                    print("Must answer yes or no, it's case sensitive because I'm lazy!")
        except Exception:
            #clear()
            if openConn ==True:
                db.close()
                openConn = False
            divider()
            raise
            divider()
            sys.exit()
        finally:
            if openConn ==True:
                db.close()
                openConn = False
コード例 #13
0
def orderFill():
    openConn = False

    #Determines wether the user has confirmed the information was typed correctly
    confirmed = None

    #Determines wether the code should loop for more key entries
    orderComplete = False

    #Marks that it's not the first loop, so don't ask for order number again
    multiKeyOrder = False

    #Used to navigate loop where user decides to loop code or not
    addMore = None

    u_date = datetime.now()

    while orderComplete == False:
        try:
            #Taking order info from user
            clear()
            while confirmed != "yes":
                print('Update the key inventory by entering the order information below.')
                divider()
                if multiKeyOrder == False:
                    u_orderNum = input('Order #: ')
                u_keyNum = input('Key used (i.e. #29): #')
                u_keysUsed = input('# of keys lased: ')
                clear()
                #Display info and have user confirm if it's correct before committing
                divider()
                print( "Lase {} key {}'s for order {} on {}?".format(
                    u_keysUsed, u_keyNum, u_orderNum, u_date))
                divider()
                confirmed = input("Is the information above correct? ")
                #If yes then insert this information into the database
                if confirmed == "yes":
                    clear()
                #If no prompt them to re-enter the information properly
                elif confirmed == "no":
                    clear()
                    print('Re-enter the information. \n')
                #If they enter anything other than yes or no, ask again
                else:
                    clear()
                    print("Must answer yes or no, it's case sensitive because I'm lazy! \n")
            #Reset confirmed for future while loops
            confirmed = "no"
            #Convert some of the user input values to int
            u_keyNum = int(u_keyNum)
            u_keysUsed = int(u_keysUsed)
            #connect to db
            print('Connecting to database...')
            db = pyodbc.connect(Driver= DVNAME,
                                Server= SVNAME,
                                Database=DBNAME,
                                trusted_connection='yes')
            openConn = True
            #cursor 1 to get preCount value
            c1 = db.cursor()
            c1.execute("SELECT invCount FROM keyInventory WHERE keyNum = '%s';" % (u_keyNum,))
            try: 
                #Check to see if cursor one has A result.
                u_preCount = (c1.fetchall()[0][0])
            except IndexError:
                divider()
                print("ERROR: The key number you entered doesn't exist in the keyInventory table.")
                print("TIP: If you know you've typed it correctly, you'll have to add it to the Database with newKey.py") 
                divider()
                input("Press Enter to close...")
                if openConn == True:
                    db.close()
                    openConn = False
                sys.exit()
            except Exception:
                if openConn == True:
                    db.close()
                    openConn = False
                    divider()
                    raise
                    divider()
                    input("Press Enter to close...")
                sys.exit()
            #Grab datetime for this commit
            u_date = datetime.now()
            #Calculate postCount
            u_postCount = u_preCount - u_keysUsed
            #Insert all the information into ordersFilled Table
            c2 = db.cursor()
            c2.execute("INSERT INTO ordersFilled (submit_time, orderNum, keyNum, keysUsed, preCount, postCount) VALUES (?, ?, ?, ?, ?, ?);", (u_date, u_orderNum,  u_keyNum, u_keysUsed, u_preCount, u_postCount,))
            c2.commit()
            #Insert the new inventory count into keyInv Table
            c3 = db.cursor()
            c3.execute("UPDATE keyInventory SET invCount = ? WHERE keyNum = ?;", (u_postCount, u_keyNum,))
            c3.commit()
            clear()
            print('Success! Database has been updated.')
            addMore = None
            #While loop to ask user if they want to remove more keys from inventory
            while addMore != "yes" and addMore != "no": 
                addMore = input('Are there more keys on this order? ')
                if addMore == 'yes':
                    multiKeyOrder = True
                    if openConn == True:
                        db.close()
                        openConn = False
                elif addMore == 'no':
                    orderComplete = True
                    clear()
                else:
                    clear()
                    print("Must answer yes or no, it's case sensitive because I'm lazy!")
        except Exception:
            raise
        finally:
            if openConn == True:
                db.close()
                openConn = False\
コード例 #14
0
def resupply():
    #This variable is used throughout the code to track wether the connection is still
    #open, and generally that check will close it and set to false if it is.
    openConn = False

    #Bool to determine wether code should loop or not.
    resupplyComplete = False

    #Bool to confirm user input is correct.
    confirmed = None

    #Determines wether user wants to add more keys to inventory.
    addMore = None

    #If encapsulates the code, re-runs it if you say you want to enter more resupply info.
    while resupplyComplete == False:
        try:
            clear()
            print('Update the key inventory by entering the key resupply info below.')
            divider()
            u_keyNum = input('Key # to add (i.e. Key #29): #')
            u_keysAdded = input('# of keys to add to inventory: ')
            clear()
            while confirmed != "yes":
                divider()
                print( "Adding {} key {}'s to the inventory. \nIs this correct?".format(u_keysAdded, u_keyNum))
                divider()
                confirmed = input('Please enter ''yes'' or ''no'': ')
                if confirmed == "yes":
                    #Do nothing
                    clear()
                elif confirmed == "no":
                    clear()
                    print('Re-enter the information.')
                    u_keyNum = input('Key # used (i.e. Key #29): #')
                    u_keysAdded = input('# of keys to add to inventory:')
                else:
                    clear()
                    print("Must answer yes or no, it's case sensitive because I'm lazy!")
            #If yes then proceed to insert this information into the database
            #First reset confirmed status in case user adds more keys later.
            confirmed = "no"
            #Convert user input values to type int
            u_keyNum = int(u_keyNum)
            u_keysAdded = int(u_keysAdded)
            #connect to db
            print('Connecting to database...')
            db = pyodbc.connect(Driver= DVNAME,
                                Server= SVNAME,
                                Database=DBNAME,
                                trusted_connection='yes')
            openConn = True
            #cursor 1 to get preCount value
            c1 = db.cursor()
            c1.execute("SELECT invCount FROM keyInventory WHERE keyNum = '%s';" % (u_keyNum,))
            try:
                #Check to see if cursor has A result
                u_preCount = (c1.fetchall()[0][0])
            except IndexError:
                #If sql select statement gets no result
                divider()
                print("ERROR: The key number you entered doesn't exist in the keyInventory table.")
                print("TIP: If you know you've typed it correctly, you'll have to add it to the Database with newKey.py") 
                divider()
                input("Press enter to close...")
                if openConn == True:
                    db.close() 
                    openConn = False
                sys.exit()
            except Exception:
                #All other exceptions
                if openConn == True:
                    db.close()
                    openConn = False
                divider()
                raise
                divider()
                input("Press enter to close...")
                sys.exit()
            #If Sql result DOES contain a result, get datetime for this resupply
            u_date = datetime.now()
            #Calculate post resupply Count
            u_postCount = u_preCount + u_keysAdded
            #Insert the resupply information into the resupply table
            c2 = db.cursor()
            c2.execute("INSERT INTO resupply (submit_time, keyNum, keysAdded, preCount, postCount) VALUES (?, ?, ?, ?, ?);", (u_date, u_keyNum, u_keysAdded, u_preCount, u_postCount,))
            c2.commit()
            #Update the new inventory count into keyInv Table
            c3 = db.cursor()
            c3.execute("UPDATE keyInventory SET invCount = ? WHERE keyNum = ?;", (u_postCount, u_keyNum,))
            c3.commit()
            print('Success! Database has been updated.')
            divider()
            addMore = None
            while addMore != "yes" and addMore != "no": 
                addMore = input('Would you like to add more keys to the inventory? ')
                if addMore == 'yes':
                    #do nothing
                    if openConn == True:
                        db.close()
                        openConn = False
                elif addMore == 'no':
                    resupplyComplete = True;
                    clear()
                else:
                    clear()
                    print("Must answer yes or no, it's case sensitive because I'm lazy!")
        except Exception:
            if openConn == True:
                db.close()
                openConn = False
            divider()
            raise
            divider()
            input("Press enter to close...")
            sys.exit()
        finally:
            if openConn == True:
                db.close()
                openConn = False
コード例 #15
0
def lowStockCheck():
    modeQuery = '''
    WITH t1 AS
    (
    SELECT keyNum, keysUsed, CONVERT(CHAR(7),submit_time,120) Dates
    FROM ordersFilled x
    WHERE CONVERT(CHAR(7),submit_time,120) != CONVERT(CHAR(7),GETDATE(),120)
    GROUP BY keyNum, submit_time, keysUsed
    ),
    t2 AS
    (
    SELECT keyNum, SUM(keysUsed) keysUsed, Dates
    FROM t1
    GROUP BY Dates, keyNum
    ),
    t3 AS
    (
    SELECT keyNum, AVG(keysUsed) avgUsedPerMonth
    FROM t2
    GROUP BY keyNum
    ),
    t4 AS
    (
    SELECT *
    FROM keyInventory
    GROUP BY keyNum, invCount
    ),
    t5 AS
    (
    SELECT keyNum, MAX(submit_time) lastSubmission
    FROM ordersFilled
    WHERE orderNum != 'avgBal'
    GROUP BY keyNum
    ),
    t6 AS
    (
    SELECT keyNum, keysUsed, COUNT(keysUsed) countVal
    FROM ordersFilled
    WHERE orderNum != 'avgBal'
    GROUP BY keyNum, keysUsed
    ),
    t7 AS
    (
    SELECT keyNum, MAX(countVal) maxCountVal
    FROM t6
    GROUP BY keyNum
    ),
    t8 AS
    (
    SELECT x.keyNum, y.keysUsed
    FROM t6 y, t7 x
    WHERE countVal = maxCountVal AND x.keyNum = y.keyNum
    ),
    t9 AS
    (
    SELECT keyNum, commonOrderSize
    FROM
    (
    SELECT keyNum, max(keysUsed) commonOrderSize
    FROM t8
    GROUP BY keyNum
    ) a
    GROUP BY keyNum, commonOrderSize
    )
    SELECT x.keyNum, x.invCount, a.commonOrderSize, y.avgUsedPerMonth, z.lastSubmission
    FROM t4 x, t3 y, t5 z, t9 a
    WHERE x.keyNum = y.keyNum AND x.keyNum = z.keyNum AND x.keyNum = a.keynum AND x.invCount <= (a.commonOrderSize * 3)
    GROUP BY x.keyNum, x.invCount, a.commonOrderSize, y.avgUsedPerMonth, z.lastSubmission;
    '''

    try:
        clear()
        print('Connecting to database...')
        db = pyodbc.connect(Driver= DVNAME,
                            Server= SVNAME,
                            Database=DBNAME,
                            trusted_connection='yes')        
        c1 = db.cursor()
        c1.execute(modeQuery)
        results = c1.fetchall()
        clear()
        print(tabulate(results, headers=['Key #', 'Inventory ct.', 'Common Order Size', 'Avg. per month', 'Date last lased'], tablefmt='psql'))
        input("Press enter to return to previous menu...")
        db.close()
        clear()
    except Exception:
        raise
        input("Press enter to close...")
        db.close()
コード例 #16
0
def manUpdate():
    manualUpdateQuery = '''
    UPDATE keyInventory
    SET invCount = '{}'
    WHERE keyNum = '{}'
    '''
    try:
        clear()
        confirmed = None
        newCount = None
        keyToUpdate = None
        keyToUpdate = input('What key would you like to update the count for? ')
        clear()
        print('Connecting to database...')
        db = pyodbc.connect(Driver= DVNAME,
                            Server= SVNAME,
                            Database=DBNAME,
                            trusted_connection='yes')        
        c1 = db.cursor()
        c1.execute("SELECT invCount FROM keyInventory WHERE keyNum = {}".format(keyToUpdate))
        currentCount = c1.fetchone()[0]
        clear()
        print("Tip: Enter a blank value to return to the main menu without changing anything.\n")
        divider()
        newCount = input("The current inventory count for that key is {}, what would you like to change it to? ".format(currentCount))
        clear()
        confirmed = input("Update key {} to {} in inventory?\n".format(keyToUpdate, newCount))
        clear()
        if confirmed == "YES" or confirmed == "Yes" or confirmed == "yes":
            c2 = db.cursor()
            c2.execute(manualUpdateQuery.format(newCount, keyToUpdate))
            c2.commit()
            input("Press enter to return to previous menu...")
            db.close()
            clear()
        else:
            print("Update didn't go through, you have to answer yes!")
            db.close()
            input("Press enter to return to main menu...")     
    except Exception:
        raise
        input("Press enter to close...")
        db.close()
コード例 #17
0
 def wilderness():
     """The wilderness is where the player is able to get into fights and earn rewards."""
     if player.current_hitpoints <= 0:
         bad_end()
     else:
         action = ""
         print("=================================")
         print("You are in the wilderness! ")
         print(
             "You can use the following commands: \n\nEXPLORE - fight enemies \nTOWN - leave wilderness "
             + "\nPLAYER - inventory, equipment management, skill points ")
         while action != "explore" or "town" or "player":
             action = input(str(player.name).capitalize() + ": ").lower()
             clear(1)
             if "explore" in action:
                 print("You wander around the wilderness... ")
                 print("=================================")
                 clear(4)
                 encounter(player)
                 break
             elif "town" in action:
                 print("Travelling back to town... ")
                 print("=================================")
                 clear(4)
                 town()
                 break
             elif "player" in action:
                 player.details()
                 # print(str(player.inventory))
                 print(
                     "Available Commands: \nEQUIP - doesn't work yet. \nUNEQUIP - doesn't work yet."
                     +
                     " \nATTRIBUTE - spend points to increase stats. \nCANCEL - go back \n"
                 )
                 while player != "equip" or "unequip" or "attribute" or "cancel":
                     sub_action = input(str(player.name) + ": ").lower()
                     clear(1)
                     if "equip" in sub_action:
                         player.details()
                         # equip_an_item()
                         print("this doesn't work yet")
                         print("=================================")
                         clear(1)
                         wilderness()
                         break
                     elif "unequip" in sub_action:
                         player.details()
                         # unequip_an_item()
                         print("this doesn't work yet")
                         print("=================================")
                         clear(1)
                         wilderness()
                         break
                     elif "attribute" in sub_action:
                         print("=================================")
                         from_location = "from wilderness"
                         print(
                             "going to attribute spend scene from wilderness"
                         )
                         print("from_location is set to: " +
                               str(from_location))
                         spend_attributes(from_location)
                         break
                     elif "cancel" in sub_action:
                         print(
                             "Canceled. \n================================="
                         )
                         clear(1)
                         wilderness()
                         break
                     else:
                         print(
                             "Available Commands: \nEQUIP - doesn't work yet. \nUNEQUIP - doesn't work yet."
                             +
                             " \nATTRIBUTE - spend points to increase stats. \nCANCEL - go back ---- inside wilderness function, sub command -player\n"
                         )
             else:
                 print(
                     "You can use the following commands: \n\nEXPLORE - fight enemies \nTOWN - leave wilderness "
                     +
                     "\nPLAYER - inventory, equipment management, skill points ---- inside wilderness function"
                 )
コード例 #18
0
def orderHistory():
    recentHistoryQuery = '''
    SELECT * 
    FROM ordersFilled
    WHERE CONVERT(CHAR(7),submit_time,120) = CONVERT(CHAR(7),GETDATE(),120) AND orderNum != 'avgBal'
    '''
    orderNumHistoryQuery = '''
    SELECT * 
    FROM ordersFilled
    WHERE orderNum = '{}' AND orderNum != 'avgBal'
    '''

    dateHistoryQuery = '''
    SELECT * 
    FROM ordersFilled
    WHERE CONVERT(CHAR(7),submit_time,120) = '{}' AND orderNum != 'avgBal'
    '''

    keyHistoryQuery = '''
    SELECT *
    FROM ordersFilled
    WHERE keyNum = '{}' AND orderNum != 'avgBal'
    '''

    try:
        clear()
        searchFor = None
        print("Enter a Year/Month(ex. '2019-05'), key number(ex. 'k22'),\norder number, or leave blank to pull the current months history.")
        divider()
        searchFor = input("Search for:")
        if searchFor.startswith('0') or searchFor.startswith('w') or searchFor.startswith('t'):
            try:
                #SEARCH FOR ORDER NUM
                clear()
                print('Connecting to database...')
                db = pyodbc.connect(Driver= DVNAME,
                                    Server= SVNAME,
                                    Database=DBNAME,
                                    trusted_connection='yes')        
                c1 = db.cursor()
                c1.execute(orderNumHistoryQuery.format(searchFor))
                results = c1.fetchall()
                clear()
                print(tabulate(results, headers=['Date', 'Order #', 'Key #', 'preCount', 'keysUsed', 'postCount'], tablefmt='psql'))
                input("Press enter to return to previous menu...")
                db.close()
                clear()
            except:
                raise
                input("Press enter to close...")
                db.close()
        elif searchFor == "":
            try:
                clear()
                print('Connecting to database...')
                db = pyodbc.connect(Driver= DVNAME,
                                    Server= SVNAME,
                                    Database=DBNAME,
                                    trusted_connection='yes')        
                c1 = db.cursor()
                c1.execute(recentHistoryQuery)
                results = c1.fetchall()
                clear()
                print(tabulate(results, headers=['Date', 'Order #', 'Key #', 'preCount', 'keysUsed', 'postCount'], tablefmt='psql'))
                input("Press enter to return to previous menu...")
                db.close()
                clear()
            except:
                raise
                input("Press enter to close...")
                db.close()
        elif searchFor.startswith('k') or searchFor.startswith('K'):
            #Search for full order history of the individual key Number.
            try:
                searchFor = (searchFor[1:])
                clear()
                print('Connecting to database...')
                db = pyodbc.connect(Driver= DVNAME,
                                    Server= SVNAME,
                                    Database=DBNAME,
                                    trusted_connection='yes')        
                c1 = db.cursor()
                c1.execute(keyHistoryQuery.format(searchFor))
                results = c1.fetchall()
                clear()
                print(tabulate(results, headers=['Date', 'Order #', 'Key #', 'preCount', 'keysUsed', 'postCount'], tablefmt='psql'))
                input("Press enter to return to previous menu...")
                db.close()
                clear()
            except:
                raise
                input("Press enter to close...")
                db.close()
        else:
            #Search for the date entered
            try:
                clear()
                print('Connecting to database...')
                db = pyodbc.connect(Driver= DVNAME,
                                    Server= SVNAME,
                                    Database=DBNAME,
                                    trusted_connection='yes')        
                c1 = db.cursor()
                c1.execute(dateHistoryQuery.format(searchFor))
                results = c1.fetchall()
                clear()
                print(tabulate(results, headers=['Date', 'Order #', 'Key #', 'preCount', 'keysUsed', 'postCount'], tablefmt='psql'))
                input("Press enter to return to previous menu...")
                db.close()
                clear()
            except:
                raise
                input("Press enter to close...")
                db.close()
            
    except Exception:
        raise
        input("Press enter to close...")
        db.close()
コード例 #19
0
    add_patient('@p162', 'abc', 10, 98188, 'ABC', 'XYZ')
    add_patient('@p462', 'abc', 10, 92188, 'BBC', 'QYZ')
    add_patient('@p463', 'abc', 43, 92128, 'BCC', 'QEZ')
    add_patient('@p412', 'abc', 12, 98128, 'ACC', 'XEZ')
    add_patient('@p162', 'abc', 10, 98188, 'ABC', 'XYZ')
    print('Blocks after patient have been added!')
    # get_block()
    add_patient('@p162', 'abc', 10, 98188, 'ABC', 'XXXYZ')
    # get_block()
    save_block(filename='output.block')


if __name__ == '__main__':
    run_app = True
    run_test()
    clear()
    # load_block()
    while run_app:
        # clear()
        print('1. Load file!')
        print('2. Save file!')
        print('3. Add employee')
        print('4. Add patient')
        print('5. Get data of block!')
        print('q. Quit')

        # try:
        #     load_block()
        #     print('Block loaded sucessfully :)')
        # except ():
        #     print('loading failed :(')
コード例 #20
0
    def town():
        """The Town function is the main hub of operations. This is where the player can find the
		   church and eventually manage their inventory and sell items."""
        if player.current_hitpoints <= 0:
            bad_end()
        else:
            action = ""
            print("=================================")
            print("You enter the town center. ")
            clear(1)
            print(
                "Available Commands: \nSHOP - buy and sell items. \nCHURCH - recover hitpoints "
                +
                "\nWILDERNESS - fight enemies \nPLAYER - inventory, equipment management, skill points "
            )
            while (action) != "shop" or "church" or "wilderness" or "player":
                action = input(str(player.name).capitalize() + ": ").lower()
                if "shop" in action:
                    print("Travelling to the shop... ")
                    print("=================================")
                    clear(2)
                    shop()
                    break
                elif "church" in action:
                    print("Travelling to the church... ")
                    print("=================================")
                    clear(2)
                    church()
                    break
                elif "wilderness" in action:
                    print("Travelling to the wilderness... ")
                    print("=================================")
                    clear(4)
                    wilderness()
                    break
                elif "player" in action:
                    player.details()
                    # print(str(player.inventory))
                    print(
                        "Available Commands: \nEQUIP - doesn't work yet. \nUNEQUIP - doesn't work yet."
                        +
                        " \nATTRIBUTE - spend points to increase stats. \nCANCEL - go back \n"
                    )
                    while player != "equip" or "unequip" or "attribute" or "cancel":
                        sub_action = input(str(player.name) + ": ").lower()
                        clear(1)
                        if "equip" in sub_action:
                            player.details()
                            # equip_an_item()
                            print("this doesn't work yet")
                            print("=================================")
                            town()
                            break
                        elif "unequip" in sub_action:
                            player.details()
                            # unequip_an_item()
                            print("this doesn't work yet")
                            print("=================================")
                            town()
                            break
                        elif "attribute" in sub_action:
                            print("=================================")
                            from_location = "from town"
                            print("going to attrbute spend scene from town")
                            print("from_location is set to: " +
                                  str(from_location))
                            spend_attributes(from_location)
                            break
                        elif "cancel" in sub_action:
                            print(
                                "Canceled. \n================================="
                            )
                            town()
                            break
                        else:
                            if player.current_hitpoints <= 0:
                                bad_end()
                            else:
                                print(
                                    "Invalid command. ---- inside town function sub command - player"
                                )
                else:
                    if player.current_hitpoints <= 0:
                        bad_end()
                    else:
                        print(
                            "Invalid command. ---- inside town function main command "
                        )

    #  Eventually a set of commands that allows the player to swap out equipment, spend skillpoints, and use items.
    # def player_command():
        """This is where the player will be able to check their character details, spend their attribute points,
コード例 #21
0
    def players_turn(player, enemy, run_away):
        """This is where combat happens. The player takes an action and based on the results,
		   they win, die, or the enemy takes a turn."""
        print(
            "================================= \n" +
            (player.name).capitalize() +
            "'s TURN: \nYou can use the following commands: \nATTACK - deal damage \nRUN - attempt to run \nITEM - not implemented yet\n "
        )
        if run_away == 0:
            if player.current_hitpoints <= 0:
                bad_end()
            # elif enemy.hitpoints <= 0:
            # clear(2)
            elif enemy.hitpoints >= 1:
                action = ""
                while action != "attack" or "run" or "item":
                    action = input(str(player.name).capitalize() +
                                   ": ").lower()
                    clear(1)
                    if "attack" in (action):
                        combat_damage = player.damage
                        combat_damage -= enemy.armor
                        if combat_damage > 0:
                            enemy.hitpoints -= combat_damage
                            clear(1)
                            print("You struck the enemy for " +
                                  str(combat_damage) + " damage after " +
                                  str(enemy.armor) +
                                  " was blocked by their armor! ")
                            if enemy.hitpoints >= 1:
                                print("================================= \n")
                                time.sleep(3)
                                enemy_turn(player, enemy, run_away)
                                break
                            # check if enemy is dead
                            elif enemy.hitpoints <= 0:
                                clear(2)
                                print("You defeated the " + str(enemy.name) +
                                      "! ")
                                if enemy.gold > 0:
                                    print("You found: " + str(enemy.gold) +
                                          " gold! ")
                                    player.gold += enemy.gold
                                    print("You now have a total of: " +
                                          str(player.gold) + " gold! ")
                                    player.current_experience += enemy.experience_reward
                                    print("You earned: " +
                                          str(enemy.experience_reward) +
                                          " experience! ")
                                    print("You now have a total of: " +
                                          str(player.current_experience) +
                                          " experience! ")
                                    level_up_check(player)
                                    break
                                else:
                                    player.current_experience += enemy.experience_reward
                                    print("You earned: " +
                                          str(enemy.experience_reward) +
                                          " experience! ")
                                    print("You now have a total of: " +
                                          str(player.current_experience) +
                                          " experience! ")
                                    level_up_check(player)
                                    break
                            else:
                                break
                        else:
                            clear(1)
                            print("The " + str(enemy.name) +
                                  "'s armor is too high! ")
                            print("================================= \n")
                            enemy_turn(player, enemy, run_away)
                            break
                    elif "run" in (action):
                        clear(1)
                        run_chance = randint(1, 100)
                        print("You attempt to run away: \nYou rolled: " +
                              str(run_chance) + " out of 100. ")
                        if player.age <= 16:
                            if run_chance <= 90:
                                run_away = 1
                                print(
                                    "You succesfully escaped the " +
                                    str(enemy.name) +
                                    "! \n================================= \n")
                                break
                            else:
                                run_away = 0
                                print("The " + str(enemy.name) +
                                      " prevented you from escaping! \n")
                                enemy_turn(player, enemy, run_away)
                                break
                        elif player.age <= 30:
                            if run_chance <= 50:
                                run_away = 1
                                print(
                                    "You succesfully escaped the " +
                                    str(enemy.name) +
                                    "! \n================================= \n")
                                break
                            else:
                                run_away = 0
                                print("The " + str(enemy.name) +
                                      " prevented you from escaping! \n")
                                enemy_turn(player, enemy, run_away)
                                break
                        elif player.age <= 60:
                            if run_chance <= 30:
                                run_away = 1
                                print(
                                    "You succesfully escaped the " +
                                    str(enemy.name) +
                                    "! \n================================= \n")
                                break
                            else:
                                run_away = 0
                                print("The " + str(enemy.name) +
                                      " prevented you from escaping! \n")
                                enemy_turn(player, enemy, run_away)
                                break
                        elif player.age <= 80:
                            if run_chance <= 10:
                                run_away = 1
                                print(
                                    "You succesfully escaped the " +
                                    str(enemy.name) +
                                    "! \n================================= \n")
                                break
                            else:
                                run_away = 0
                                print("The " + str(enemy.name) +
                                      " prevented you from escaping! \n")
                                enemy_turn(player, enemy, run_away)
                                break
                    # Below commented out code is to be reworked.
                    # run(player, enemy)
                    # break
                    # elif "item" in (action):
                    # 	# loop through actons with items can take off an item, but need to equip an item.
                    # 	print(player.inventory)
                    # 	item_action = input("use, item name ")
                    # 	# if item_action = How to check for weapon/armor/or other item?
                    # 	break
                    else:
                        print(
                            "Please type 'attack' 'run' or 'item' into the console. "
                        )
コード例 #22
0
 def shop():
     print("The shop is closed (not created yet)")
     print("Heading back to town.")
     print("=================================")
     clear(2)
     town()
コード例 #23
0
    def input_age(age, name):
        """This takes in user input and determines what the player's age will be.
		   It impacts gameplay and dialogue."""
        if age <= 0:
            clear(1)
            print(str(age) + "? ")
            clear(1)
            print(
                "You're not even born yet... Come back when you exist. \nThe End. "
            )
        # 1-8
        elif age <= 8:
            clear(1)
            print(str(age) + "? ")
            clear(1)
            print(
                "You are too young too young for this adventure. Go take a nap, kid. \nThe End. "
            )
        # 9-16
        elif age <= 16:
            clear(1)
            print(str(age) + "? ")
            clear(1)
            print(
                "? You are rather young. But you can make it with some luck. ")
            strength = 4
            endurance = 4
            input_class(age, name, endurance, strength)
        # 17-30
        elif age <= 30:
            clear(1)
            print(str(age) + "? ")
            clear(1)
            print(
                "You've got some experience but there's an entire world left to explore."
            )
            strength = 8
            endurance = 8
            input_class(age, name, endurance, strength)
        # 31-60
        elif age <= 60:
            clear(1)
            print(str(age) + "? ")
            clear(1)
            print(
                "You're not as young as you once were but you've got experience and know your way around the world."
            )
            strength = 6
            endurance = 6
            input_class(age, name, endurance, strength)
        # 61-80
        elif age <= 80:
            clear(1)
            print(str(age) + "? ")
            clear(1)
            print(
                "Wow. You are at the end of your days... This is probably your last adventure. Lets make it good!"
            )
            strength = 2
            endurance = 2
            input_class(age, name, endurance, strength)
        # 81+
        elif age >= 81:
            clear(1)
            print(str(age) + "? ")
            clear(1)
            print(
                "You are too old! You already had your adventure. Go take a nap. \nThe End. "
            )