Python Forum
Logic error - I need User_1 and User_2 to become true when both users sign in.
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Logic error - I need User_1 and User_2 to become true when both users sign in.
#1
Hi all,

I have been asked to design a basic dice roll game over the course of 20 hours, and all was swell until I came across a logic error. The code does function (2 players are able to log in), but the variables User_1 and User_2 don't become true. This means that even if I have created a game, users wouldn't be able to access it.

### ------------------------------------------------------------------------------------------------------------------------------ ###
Users = open("Usernames.txt","r+") # Users opens a text file, a+ so it can append and read
Passwords = open("Passwords.txt","r+") # Passwords opens a text file, a+ so it can append and read
User_array = Users.read().splitlines() # Splits file into array
Password_array = Passwords.read().splitlines() # Splits file into array
User_1 = False # Decalring global variables
User_2 = False # Decalring global variables
### ------------------------------------------------------------------------------------------------------------------------------ ###
def SignUp(): # Creating function for Sign up system
    SignUp = True # Declares SignUp true (for WHILE loop)
    while SignUp == True: # Sets while loop
        user = input('Create Username: ') # Prompts user to create username
        password = input('Create Password: ') # Prompts user to create password
        if user in User_array: 
            print("That user already exsist") # If user already exists output an error message 
        else: # Otherwise
            Users.write(user) # Writes new Username into file
            Users.write("\n") # Goes down a line
            Passwords.write(password) # Writes new Password into file
            Passwords.write("\n") # Goes down a line
            Users.close() # Saves Usernames
            Passwords.close() # Saves Passwords
            print("WELCOME, ",user,", PLEASE RESTART BEFORE SIGNING IN") # Outputs welcome message
            SignUp = False # Terminates while loop
### ------------------------------------------------------------------------------------------------------------------------------ ###        
def LogIn(): # Creating function for log in system
    userguess = input("Player 1, please input your username >>> ") #assigning a user input to the userguess variable
    passwordguess = input("Player 1, please input your password >>> ") #assigning a user input to the passwordguess variable
    while (userguess not in User_array) or (passwordguess not in Password_array): 
        print("INCORRECT DETAILS >>> ") #if the usernames and passwords don't match up, an error message is given
        userguess = input("Player 1, please input your username >>> ") # Asks for guesses again
        passwordguess = input("Player 1, please input your password >>> ") # Asks for guesses again
    else: # Otherwise
        player_1 = userguess
        print ("Welcome player 1, player 2 please sign in") # Output a welcome message
        User_1 = True


    userguess = input("Player 2, please input your username >>> ") #assigning a user input to the userguess variable
    passwordguess = input("Player 2, please input your password >>> ") #assigning a user input to the passwordguess variable
    while (userguess not in User_array) or (passwordguess not in Password_array) or (userguess == player_1): 
        print("INCORRECT DETAILS >>> ") #if the usernames and passwords don't match up, an error message is given
        userguess = input("Player 2, please input your username >>> ") # Asks for guesses again
        passwordguess = input("Player 2, please input your password >>> ") # Asks for guesses again
    else:
        player_2 = userguess
        print ("Welcome player 2") # Output a welcome message
        User_2 = True
### ------------------------------------------------------------------------------------------------------------------------------ ### 
### ------------------------------------------------------------------------------------------------------------------------------ ###
### ------------------------------------------------------------------------------------------------------------------------------ ###
def rules():
    print("""THE RULES ARE:
           >>> Points rolled on each player’s dice are added to their score.
           >>> If the total is an even number, an additional 10 points are added to their score.
           >>> If the total is an odd number, 5 points are subtracted from their score.
           >>> If they roll a double, they get to roll one extra die and get the number of points rolled added to their score.
           >>> The score of a player cannot go below 0 at any point.
           >>> The person with the highest score at the end of the 5 rounds wins.
           >>> If both players have the same score at the end of the 5 rounds, it will all come down to first blood.
           >>> Most importantly, have fun!
           """)
### ------------------------------------------------------------------------------------------------------------------------------ ### 
### ------------------------------------------------------------------------------------------------------------------------------ ###
### ------------------------------------------------------------------------------------------------------------------------------ ###
def menu():
    print("""WELCOME TO DOUBLE OR NOTHING... PLEASE SELECT ONE OF THE FOLLOWING OPTIONS >>>
                                                 ___________
                                                /\  .     . \ 
                                               /  \  .     . \ 
                                              /    \__________\ 
                                             /  .  /  .    .  / 
                                             \    /     .    / 
                                              \  /  .    .  / 
                                               \/__________/ 
                                         ___________
                                        /\  .     . \ 
                                       /  \  .     . \ 
                                      /    \__________\ 
                                     /  .  /  .    .  / 
                                     \    /     .    / 
                                      \  /  .    .  / 
                                       \/__________/ 
           1 >>> Register
           2 >>> Log in
           3 >>> Rules
           4 >>> Play
           5 >>> Quit
           """)

def choice():
    UserChoice = input("CHOOSE OPTION 1, 2, 3, 4, OR 5 >>> ")
    if UserChoice == "1":
        SignUp()
        choice()
    elif UserChoice == "2":
        LogIn()
        choice()
    elif UserChoice == "3":
        rules()
        choice()
    elif UserChoice == "4":
        if User_1 == True and User_2 == True:
            print("game coming soon")
        else:
            print("DOUBLE OR NOTHING REQUIRES TWO PLAYERS, PLEASE LOGIN FIRST >>> ")
            choice()
    elif UserChoice == "5":
        quit()
    elif UserChoice != 1 or 2 or 3 or 4 or 5:
        print (">>> NOT A VALID OPTION... TRY AGAIN")
        choice()

        

menu()
choice()
I would really appreciate any help I receive!

Cordially,
Hamza.
Reply
#2
This is a scope problem. You have global variables User_1 and User_2.
User_1 = False # Decalring global variables
User_2 = False # Decalring global variables
These variables can be seen by any function inside the same module (file). Inside LogIn() you have local variables User_1 and User_2.
 else: # Otherwise
        player_1 = userguess
        print ("Welcome player 1, player 2 please sign in") # Output a welcome message
        User_1 = True # Similar for User_2
These variables only exist within the context of the function.

By default a Python variable exists in the context where I is assigned. If you do User_1 = False outside of any function, the User_1 variable is a global variable, If you do User_1 = True inside a function then User_1 is a local variable defined in the function scope. Though the global User_1 and the local User_1 have the same they are not the same variable.

There are two things you can do to get around this local variable problem. The easy/ugly solution is to use the "global" keyword to tell Python that the variable is in the global scope not the local scope.
def LogIn(): # Creating function for log in system
    global User_1, User_2
A better solution is to use a mutable data type like a list, dictionary or object to hold the values. For example, it might be nice to remember the player names to be used as a prompt while playing you game. You use a list to hold the names:
players = [] # List for players names
In the LogIn() function you would add a name to the players list after a successful login.
players.append(userguess)
And in choice() you would change this:
    elif UserChoice == "4":
        if User_1 == True and User_2 == True:
to this:
    elif UserChoice == "4":
        if len(players) >= 2:
The reason that modifying a mutable datatype works is that you are not assigning a variable, you are modifying the Python object referenced by the variable. "players.append(userguess) does not change the variable "players". "players" references the same Python list before and after the append(). The append() only modifies the list that "players" references. You cannot do this trick with immutable (unchangeable) data types like numbers, Booleans or strings.
BruhMoments likes this post
Reply
#3
I think it is really awkward that you force the user to restart the application between signing up and logging in. Your program should not open the username file at the start of the program and leave it open for the life of the program. Instead you should open the file when needed, load the file into a data structure, and close the file.

I would also combine the username and password information into one file and use a dictionary in my program to keep the account information (username:password). This example saves an account dictionary to a json format file.
import json

def save_accounts(accounts):
    """Save user account info"""
    with open("mygame.txt", "w") as file:
        json.dump(accounts, file)

accounts = {'Jimmy Dean':'X11_84', 'Mary Jane':'John Lives'}
save_accounts(accounts)
After running the program the "mygame.txt" file contains:
Output:
{"Jimmy Dean": "X11_84", "Mary Jane": "John Lives"}
The file is opened inside a context manager. The file closes immediately after the accounts are read from the file.

You would need to write a load_accounts() function to load information from the json file into the accounts dictionary. Then you would use these two functions whenever you want to get up-to-date user account info.
# Add an account
accounts = load(accounts)
accounts[input('User ')] = input('Password ')
save_accounts(accounts)
BruhMoments likes this post
Reply
#4
Thank you for the help. I've made a few adjustments here and there, and now have a functioning login system.

The whole restart thing is okay. At this moment in time, I'm just doing the bare minimum needed, but when I finish the project, I will add it in along with some more graphical features!

Once again, I would to express my gratitude for your support.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Homework, works but has logic error goldielocks789 3 1,188 Apr-24-2023, 11:52 AM
Last Post: Larz60+
  problem with ‘>’ (i.e. greater than) sign AOCL1234 2 1,936 Jun-30-2020, 09:32 PM
Last Post: Yoriz
  A sign-Reversal Puzzle HY2000 2 2,460 Dec-05-2019, 11:55 AM
Last Post: HY2000
  Making a calculator with just the + sign gerardmanken 1 2,844 Feb-01-2018, 03:18 PM
Last Post: buran
  User sign up and login system tesilstudent112 1 5,062 Oct-22-2017, 10:14 AM
Last Post: metulburr
  I have a logic error. forumer444 3 3,210 Sep-06-2017, 10:27 PM
Last Post: forumer444

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020