def arrest(people_list):
    """
    Arrest function
    Parameters:
        people_list: list: contains all of the people
    Returns:
        None: NoneType: Means that the user went to arrest, and then decided
            against it. Continue as if this function was not called
        0: Means that the user guessed wrong. Give score of 0
        1: Means that the user guessed correctly. Give a score above 0
    """
    certainty = four.validate("Are you sure that you are ready to make an " +
                              "arrest? This will end the game. [y/n], lowe" +
                              "rcase, please.",
                              str,
                              string_whitelist=["y", "n"])  # input
    if certainty in ["n"]:
        return None  # the user decided not to make an arrest just yet
    print("You gather everyone in the yard. There is a heavy police presence" +
          ", in case the culprit tries to escape. The mood is tense. You" +
          " raise your arm, point, and say:\n\"It\'s you! You committed " +
          "the crime!\"")  # worldbuilding and user interaction (ui)
    prompt = "Who were you pointing at?"  # initialisation
    for person in range(len(people_list)):  # this handles people
        if people_list[person] != "":  # my nobody's here, my mr ghost
            prompt += "\n" + str(person) + ": " + people_list[person][0]  # add
    accused = people_list[four.validate(prompt,
                                        int,
                                        convert=True,
                                        num_min=1,
                                        num_max=len(people_list) - 1)]  # who?
    if accused[1]:  # they were the murderer, user was right
        print("A fine days work from the best detective in the world. Anothe" +
              "r criminal behind bars. You have earned your salary.")  # ui
        return 1
    else:  # they arent the murderer, user was wrong
        print("Ooo. That's going to leave a mark when they are found innoc" +
              "ent in court. You might even go to jail yourself for malpract" +
              "ice. People won't trust you as much anymore, as an innocent" +
              " is going on trial due to you.")  # ui
        return 0
def navigation(map, room):
    """
    Navigation function
    Parameters:
        map: list: a list of rooms each of which has
            str: A name in first position (map[n][0])
            int: A series of connections, the rooms which are connected to it.
                 These are represented by the room's index in the map list
        room: int: The room the player is currently in, represented as the
            index of that room in the larger map list
    Returns:
        room: int: the new room number that the player is in
    """
    option_number = 0  # this is just for numbering - for the options
    print("You are currently in the", map[room][0])  # ui
    print("Where would you like to go?")  # ui
    for adjacent_room in map[room][1]:  # go through the connections in room
        print("  ", option_number, ": ", map[adjacent_room][0], sep="")  # ui
        option_number += 1  # distuinguish numbering for adjacent rooms
    user_choice = four.validate("", int, convert=True, num_min=0, num_max=len(map[room][1]))  # user input
    room = map[room][1][user_choice]  # move the user
    print("You are now in the", map[room][0])  # ui
    return room
Beispiel #3
0
def main():
    """
    Main function
    Parameters:
        None
    Returns:
        arrest: int:
            0: they were wrong
            1: they correctly identified the murderer
        user: str: the username of the user
        evidence: list: the evidence list that is happening
    """

    try:  # just for the connection close, doesn't catch anything
        connection = two.connect_to_database()  # connect to the database
        user = two.login(connection)  # log the user in
        if user is 0:  # neutrality response is baaaaaad
            user = "******"  # make good for ui later
        emotional_states = ["angry", "neutral", "nervous"]  # used for people
        people_list = [
            "",  # nobody, mr ghost
            ["Jim", False, emotional_states[rand(0, 2)]],
            ["Mary", False, emotional_states[rand(0, 2)]],
            ["Michael", False, emotional_states[rand(0, 2)]],
            ["Penny", False, emotional_states[rand(0, 2)]]
        ]  # generate people
        people_list[rand(1, len(people_list) - 1)][1] = True  # make a murderer
        # map = five.generate_map()  # generate map.
        map = [["lounge", (1, 2, 4), 1], ["kitchen", (4, 0), 0],
               ["bedroom", (3, 0, 4, 5), 0], ["cheese room", (2, 4, 5), 2],
               ["hallway", (0, 1, 2, 3), 3],
               ["empty elevator shaft", (3, 2),
                4]]  # so it turns out map generation is hard the way I wanted
        # to do it? here's a hard-coded map. I'll fix it if I have time.
        room = 1  # which room are they in?
        evidence = [["murder weapon", "???",
                     "physical"]]  # there's no evidence
        print("You are in the", map[room][0])  # ui
        gameplay_flag = True  # hmm. multiple turns. what are those?
        while gameplay_flag:  # without these two lines, no idea!
            """
            options = {0: nine.display_dialogue(),
                       1: seven.navigation(map, 0)}[four.validate("", int)]
            """
            prompt = "What do you want to do?\n 0: Go to another room" + \
                     "\n 1: Observe the room\n 2: Make an arrest"  # for option
            if map[room][2] != 0:  # if there's a person in the room
                prompt += "\n 3: Talk to the person in the room"  # talk?
                decision = four.validate(prompt, int, num_min=0,
                                         num_max=3)  # get what they want to do
            else:  # there's nobody in the room
                decision = four.validate(prompt, int, num_min=0,
                                         num_max=2)  # get what they want to do
            if decision == 3 and map[room] != 0:  # they want to talk
                nine.display_dialogue(people_list[map[room][2]], evidence,
                                      user)  # talk
            elif decision == 0:  # they want to move
                room = seven.navigation(map, room)  # navigate
            elif decision == 1:  # they want to observe the room
                evidence.append(eight.observe(evidence, people_list))  # append
                print(f"You look around the room and find: {evidence[-1][0]}")
            elif decision == 2:
                arrest = ten.arrest(people_list)  # make an arrest
                if arrest is not None:  # they went through with the arrest
                    return arrest, user, evidence  # exit function
            else:  # four.validate() shouldn't allow this to happen
                print("hmm. this shouldn't happen. this shouldn't happen. th-")
    finally:  # close the connection, even if an error occurs
        try:  # if there's an error too quickly, connection might be undefined
            connection.close()  # close the connection
        except:
            print("An error occured.")  # well, it did
Beispiel #4
0
# end function definitions-----------------------------------------------------

# main routine-----------------------------------------------------------------
if __name__ == "__main__":  # is this code being called directly?
    start_time = time.time()  # start timer
    success, user, evidence = main()  # just function named main, not __main__
    connection = two.connect_to_database()  # connect to db
    if user != "Guest":  # guests dont get their score in the db
        score = int((999 - (time.time() - start_time)) * success)  # score calc
        evidence = str(evidence)  # to put into db later
        user = connection.cursor().execute(
            "SELECT id FROM users WHERE use" + "rname = ?",
            (user, )).fetchone()[0]
        # get id of user for foreign key
        three.data_into_database([score, user, evidence], "scores", connection)
    end_view_flag = True  # while True is bad, apparently
    while end_view_flag:  # this handles the score view at the end
        three.display(connection)
        if four.validate("Do you want to view the scores again?", str,
                         string_whitelist=["y", "n", "e", "s", "o", "Y", "E",
                                           "S", "N", "O"]).lower()\
        in ["n", "no"]:  # stop
            break  # stop
    print("Thanks for playing!")  # ui
    connection.close()  # close the database
    # conn = two.connect_to_database()
    # three.display(conn)

# end main routine-------------------------------------------------------------
Beispiel #5
0
def login(conn):
    """
    Logs the user into the database.
    Parameters:
        conn: an sqlite3 connection object
    Returns/Yields:
        username: str: represents a username
    """
    login_flag = True  # login loop
    while login_flag:  # begin login loop (so as we can get failability)
        login_type_choice = four.validate(
            """Would you like to:
                            Login as a [g]uest,
                            [L]ogin to a pre-existing account,
                            Or create a [n]ew account?""",
            str,
            string_whitelist=["g", "l", "L", "G", "n", "N"]).lower()  # ui
        if login_type_choice in ["g", "guest"]:  # they want to play as guest
            print("Welcome, guest. We hope you enjoy yourself")  # ui
            return 0  # 0 = no account / guest account
            login_flag = False  # this should never run, but just in case :)
        elif login_type_choice in ["l", "login"]:  # pre-existing account
            username = four.validate(
                "Please enter your username (not case-sensitive)",
                str,
                string_blacklist=["~"]).lower()  # get username
            password = bytes(
                four.validate("Please enter your password " +
                              "(case-sensitive)",
                              str,
                              string_blacklist=["~"]), "utf-8")
            password_hash = hashlib.sha224(password).hexdigest()  # hash it
            cursor = conn.cursor()  # for interacting with the database
            cursor.execute("""
            SELECT password
            FROM users
            WHERE username = ?
            """, (username, ))  # get password hash at entered username
            correct_hash = cursor.fetchall()  # move results out of cursor
            if correct_hash != []:  # [] is the no results response from cursor
                correct_hash = correct_hash[0][0]  # removing boilerplate
            conn.commit()  # debind cursor results (more secure)
            if password_hash == correct_hash:  # this is the most important
                return username  # account is referred to by username
            elif correct_hash in [[], "", None]:  # many kinds of empty
                print("That user is not in our records, try again")  # ui
                continue  # give the user opportunity to correct typos
            else:
                print("Password does not match username, try again.")  # ui
                continue  # give the user opportunity to correct typos
        elif login_type_choice in ["n", "new"]:  # user creating new account
            username = four.validate("Enter your new username (not case sens" +
                                     "itive): ",
                                     str,
                                     max_length=12,
                                     string_blacklist=["~"]).lower()
            cursor = conn.cursor()  # need this to interact with database
            cursor.execute("""
            SELECT username
            FROM users
            WHERE username = ?
            """, (username, ))  # this should be empty, if username isn't in db
            prior_usernames = cursor.fetchall()  # moving results out of cursor
            if prior_usernames != []:  # cursor returns [] if no results
                print("Sorry! That username has been taken")  # ui
                continue  # return to start of loop (give user another chance)
            check = four.validate("Please enter the username again, to avoid" +
                                  " typos and whatnot",
                                  str,
                                  string_blacklist=["~"]).lower()  # no typo
            if check != username:  # there was a typo somewhere
                print("Oops! Those don't match. Please try again")  # ui
                continue
            password = four.validate("Please enter your desired password:"******"~"])  # reusing
            check = four.validate("Please reenter your desired password:"******"~"])  # variables
            if password != check:  # these should match, else they've made typo
                print("Oops! Those do not match. Please try again")  # ui
                continue  # yeaaaaa. this sends them back to the top. bad.
            password = hashlib.sha224(bytes(password, "utf-8")).hexdigest()
            cursor.execute("""INSERT INTO users (username, password)
                              VALUES (?,?)""", (username, password))  # into db
            conn.commit()  # data persistence
            print("Your account has been created")  # ui
            return username  # log them into their new account
        else:  # we don't have a condition here
            print("That's not an option we have. Please try again")  # ui
            continue  # go to the top of the loop (in case program gets bigger)
def display(conn):
    """
    Function for getting data out of the database
    Please note that only data from the scores table is visible to the user,
    data from the users table is not avaliable. As such, the "FROM scores"
    section of the query is hard coded.
    Parameters:
        conn: sqlite3 connection object
    Returns/Yields:
        None
    """
    filter = None  # this would else only be init-ed conditionally
    user_options = {
        "sort": {
            1: None,
            2: "score ASC",
            3: "score DESC",
            4: "owner ASC",
            5: "owner DESC"
        }[four.validate("How do you want to" + " sort the sco" +
                        "res?\n    1: No sorti" + "ng, just raw data.\n " +
                        "   2: By score, ascen" + "ding.\n    3: By scor" +
                        "e, descending.\n    4" + ": By user, alphabetic" +
                        "ally, ascending.\n   " + " 5: By user, alphabet" +
                        "ically, descending.",
                        int,
                        convert=True,
                        num_min=1,
                        num_max=5)],
        "duplicate":
        four.validate("Do you want to allow duplica" +
                      "te data?\n    1: Yes." + "\n    2: No.",
                      int,
                      convert=True,
                      num_min=1,
                      num_max=2) - 1,
        "filter":
        four.validate("Is there anything you want to " +
                      "filter?\n    1: Yes." + "\n    2: No.",
                      int,
                      convert=True,
                      num_min=1,
                      num_max=2) - 1
    }  # get user input
    if user_options["filter"] == 0:  #remember to make "0" into 0
        filter = [
            {
                1: "score = ?",
                2: "owner = ?",
                3: "owner != ?",
                4: "score != ?",
                5: "score > ?",
                6: "score < ?",
                7: "score >= ?",
                8: "score <= ?",
            }[four.validate(
                "Which comparison do you want?" + "\n    1: score =" +
                "\n    2: owner =" + "\n    3: owner is not =" +
                "\n    4: score is not =" + "\n    5: score >" +
                "\n    6: score <" + "\n    7: score >=" + "\n    8: score <=",
                int,
                convert=True,
                num_min=1,
                num_max=8)],
            four.validate("What do you want to compare to?",
                          str,
                          string_blacklist=["~"])
        ]  #temp, will be comp 4 later. of which I am glad, because this is a hhhhaaaaaaaack. Oh, and don't forget to make "0" -> 0
    query = "SELECT"
    if user_options["duplicate"] in [0]:  # they don't want duplicates
        query += " DISTINCT"  # the distinct clause ensures distinct records
    query += (" scores.score, users.username, scores.evidence " +
              "FROM scores INNER JOIN users ON users.id = scores.owner")
    if filter is not None:  # sometimes we don't need a where clause
        query += " WHERE " + filter[0]  # sometimes we do need a where clause
    if user_options["sort"] is not None:  # sometimes we don't need an order by
        query += " ORDER BY " + str(user_options["sort"])  # sometimes we do
    cursor = conn.cursor()  # need cursor object to interact with db
    if filter is None:  # sometimes the execute doesn't need the extra arg
        cursor.execute(query)  # execute the query
    else:  # sometimes the execute needs the extra arg of filter
        cursor.execute(query, (filter[1], ))  # execute the query
    results = cursor.fetchall()  # save results
    print(
        "Score       Owner        Evidence Name                          Evidence Owner       "
        + "                    Evidence Type")  # headings
    for row in results:  # iterate over results to extract one record at once
        output = "  "  # indentation
        output += str(row[0])  # score
        output += " " * (12 - len(str(row[0])))  # column difference
        output += row[1][0].upper() + row[1][1:]  # name of user who owns score
        output += " " * (13 - len(str(row[1])))  # column difference
        evidence_list = row[2].split("'")  # split the string
        for piece in range(1, len(evidence_list) - 1):  # iterate over
            if evidence_list[piece] == ", ":  # builtin seperator! we can input
                output += " " * (40 - len(evidence_list[piece - 1])
                                 )  # whitespace!
            elif evidence_list[piece] == "], [":  # new evidence piece
                output += "\n"  # new line via newline
                output += " " * 27  # move to correct column (and indent)
            else:  # we don't want our semantics
                output += evidence_list[piece]  # add it to output
        print(output)  # just print it out
Beispiel #7
0
    finally:  # close the connection, even if an error occurs
        try:  # if there's an error too quickly, connection might be undefined
            connection.close()  # close the connection
        except:
            print("An error occured.")  # well, it did


# end function definitions-----------------------------------------------------

# main routine-----------------------------------------------------------------
if __name__ == "__main__":  # is this code being called directly?
    start_time = time.time()  # start timer
    success, user, evidence = main()  # just function named main, not __main__
    score = int((999 - (time.time() - start_time)) * success)  # score calc
    evidence = str(evidence)  # to put into db later
    connection = two.connect_to_database()
    user = connection.cursor().execute(
        "SELECT id FROM users WHERE username " + "= ?", (user, )).fetchone()[0]
    # get id of user for foreign key
    three.data_into_database([score, user, evidence], "scores", connection)
    end_view_flag = True  # while True is bad, apparently
    while end_view_flag:  # this handles the score view at the end
        three.display(connection)
        if four.validate("Do you want to view the scores again?", str).lower()\
           in ["n", "no"]:  # stop
            break  # stop
    print("Thanks for playing!")  # ui
    # conn = two.connect_to_database()
    # three.display(conn)

# end main routine-------------------------------------------------------------
def display_dialogue(person, evidence, user):
    """
    Display of and interaction with dialogue
    Parameters:
        person: list: contains in the order shown:
            the persons name: str
            the persons murderous quality (are they the murderer?): boolean
            the persons personality: str (angry, neutral, nervous)
        evidence:
            a list containing all the evidence you can confront them with
        user: str: the users username
    Returns:
        None
    """
    dialogue_loop = True  # loop variable
    while dialogue_loop:  # dialogue loop
        print("What would you like to do in the conversation?")  # ui
        print(" [a] Leave")  # ui
        print(" [b] Confront with your evidence")  # ui
        print(" [c] Neutral question")  # ui
        choice = four.validate("",
                               str,
                               max_length=1,
                               min_length=1,
                               string_whitelist=["a", "b", "c"])  # input
        if choice in ["a"]:  # leaving conversation
            print(user, ":", sep="")  # print username
            print("  Goodbye")  # illusion of conversation
            print(person[0], ":    ")  # print person's name
            print("  ", generate_response(person, None, 0))  # response
            dialogue_loop = False  # conversation is over
        elif choice in ["b"]:  # confrontation
            print("Which evidence piece would you like to confront them with?")
            for piece in range(len(evidence)):  # display the options
                print(" [", piece, "] ", evidence[piece][0], sep="")  # display
            evidence_choice = four.validate("",
                                            int,
                                            convert=True,
                                            num_min=0,
                                            num_max=len("evidence"))  # input
            evidence_choice = evidence[evidence_choice]  # not index, piece
            print(user, ":", sep="")  # print username
            if evidence_choice[2] == "physical":  # is this physical?
                print("  Do you recognise this ",
                      evidence_choice[0],
                      "?",
                      sep="")  # illusion of convo
                print(person[0], ":", sep="")  # person's name
                print("  ", generate_response(person, evidence_choice, 1))
            else:  # it's conversational in nature, this evidence
                print("  I have it on good authority that as a result of " +
                      "your words, something interesting has come to " +
                      "light regarding ",
                      evidence_choice[0],
                      ". What do you think of this?",
                      sep="")
                print(person[0], ":", sep="")  # person's name
                print("  ", generate_response(person, evidence_choice, 2))
        elif choice in ["c"]:
            print(user, ":", sep="")  # print username
            neutral_questions = [
                "Where were you during the murder?",
                "What time did the murder occur?",
                "What is your favorite colour?", "How old are you?",
                "How long did you know the victim?",
                "Have you lost anything recently?"
            ]
            question_number = rand(0,
                                   len(neutral_questions) - 1)  # index select
            print("  ", neutral_questions[question_number])  # illusion of talk
            print(person[0], ":", sep="")  # who's talking? person[0] is!
            response, evidence = generate_response(person, evidence,
                                                   (3, question_number),
                                                   user)  # get response
            print("  ", response)  # show response to user
        else:
            pass
def display(conn):
    """
    Function for getting data out of the database
    Please note that only data from the scores table is visible to the user,
    data from the users table is not avaliable. As such, the "FROM scores"
    section of the query is hard coded.
    Parameters:
        conn: sqlite3 connection object
    Returns/Yields:
        None
    """
    filter = []  # this would else only be init-ed conditionally
    user_options = {
        "sort": {
            0: None,
            1: "score ASC",
            2: "score DESC",
            3: "owner ASC",
            4: "owner DESC"
        }[four.validate("How do you want to" + " sort the scores?" +
                        "\n    0: No sorting," + "just raw data.\n    1" +
                        ": By score, ascending" + ".\n    2: By score," +
                        " descending.\n    3: " + "By user, alphabetical" +
                        "ly, ascending.\n    4" + ": By user, alphabetic" +
                        "ally, descending.",
                        int,
                        convert=True,
                        num_min=0,
                        num_max=4)],
        "duplicate":
        four.validate("Do you want to allow duplicate data?" +
                      "\n    0: Yes." + "\n    1: No.",
                      int,
                      convert=True,
                      num_min=0,
                      num_max=1),
        "filter":
        four.validate("Is there anything you want to filter?" +
                      "\n    0: Yes." + "\n    1: No.",
                      int,
                      convert=True,
                      num_min=0,
                      num_max=1)
    }  # get user input
    if user_options["filter"] == 0:  #remember to make "0" into 0
        filter = [{
            0: "score = ?",
            1: "owner = ?",
            2: "owner != ?",
            3: "score != ?",
            4: "score > ?",
            5: "score < ?",
            6: "score >= ?",
            7: "score <= ?",
        }[four.validate("Which comparison do you want?" + "\n    0: score =" +
                        "\n    1: owner =" + "\n    2: owner is not =" +
                        "\n    3: score is not =" + "\n    4: score >" +
                        "\n    5: score <" + "\n    6: score >=" +
                        "\n    7: score <=",
                        int,
                        convert=True,
                        num_min=0,
                        num_max=7)],
                  four.validate("What do you want to compare to?", str)]
        # select.
        if four.validate(
                "Would you like to combine that with another filter? [y/n]",
                str,
                max_length=3,
                min_length=1) in ["y", "yes"
                                  ]:  # do they want to add another condition
            print("in conditional")  #temp
            conjunction = {
                "0": " AND",
                "1": " OR",
                "2": " NOT AND",
                "3": " NOT OR"
            }[four.validate(
                "What relationship would you like two queries to have?\n    0: AND\n    1: OR\n    2: NOT AND\n    3: NOT OR",
                str)]  # which relationship do they want
            filter[0] += conjunction  # add it to the query
            secondary_filter = [{
                0: "score = ?",
                1: "owner = ?",
                2: "owner != ?",
                3: "score != ?",
                4: "score > ?",
                5: "score < ?",
                6: "score >= ?",
                7: "score <= ?",
            }[four.validate(
                "Which comparison do you want?" + "\n    0: score =" +
                "\n    1: owner =" + "\n    2: owner is not =" +
                "\n    3: score is not =" + "\n    4: score >" +
                "\n    5: score <" + "\n    6: score >=" + "\n    7: score <=",
                int,
                convert=True,
                num_min=0,
                num_max=7)],
                                four.validate(
                                    "What do you want to compare to?", str)]
            filter[0] += " " + secondary_filter[0]  # add it in
            filter.append(secondary_filter[1])  # add variable data
        else:
            print("not in conditional")  #temp
    query = "SELECT"
    if user_options["duplicate"] in [0]:  # they don't want duplicates
        query += " DISTINCT"  # the distinct clause ensures distinct records
    query += (" scores.score, users.username, scores.evidence " +
              "FROM scores INNER JOIN users ON users.id = scores.owner")
    if filter != []:  # sometimes we don't need a where clause
        query += " WHERE " + filter[0]  # sometimes we do need a where clause
    if user_options["sort"] is not None:  # sometimes we don't need an order by
        query += " ORDER BY " + str(user_options["sort"])  # sometimes we do
    cursor = conn.cursor()  # need cursor object to interact with db
    if filter == []:  # sometimes the execute doesn't need the extra arg
        cursor.execute(query)  # execute the query
        print("Just executed query: ", query)  #temp
    elif len(filter) == 2:  # sometimes the execute needs single extra arg
        print("In single arg conditional")  #temp
        print("query: ", query, "\nfilter: ", filter)
        cursor.execute(query, (filter[1], ))  # execute the query
    elif len(filter) == 3:  # sometimes it needs two extra args
        print("In double arg conditional")  #temp
        cursor.execute(query, (filter[1], filter[2]))  # execute query
    results = cursor.fetchall()  # save results
    print("Score       Owner       Evidence Name       Evidence Owner       " +
          "Evidence Type")  # headings
    for row in results:  # iterate over results to extract one record at once
        output = "  "  # indentation
        output += str(row[0])  # score
        output += " " * (12 - len(str(row[0])))  # column difference
        output += row[1][0].upper() + row[1][1:]  # name of user who owns score
        output += " " * (12 - len(str(row[1])))  # column difference
        evidence_list = row[2].split("'")  # split the string
        for piece in range(1, len(evidence_list) - 1):  # iterate over
            if evidence_list[piece] == ", ":  # builtin seperator! we can input
                output += " " * (20 - len(evidence_list[piece - 1])
                                 )  # whitespace!
            elif evidence_list[piece] == "], [":  # new evidence piece
                output += "\n"  # new line via newline
                output += " " * 26  # move to correct column (and indent)
            else:  # we don't want our semantics
                output += evidence_list[piece]  # add it to output
        print(output)  # just print it out