Python Forum
important work. need help urgently please
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
important work. need help urgently please
#1
can someone help with this please it keeps saying player_1 isn't defined?

what I need to do for this is authenticate a user after they create an account then allow them to see scores IF they want and/or let them play the game. the bit for the winners isn't working and its due tomorrow and my teacher isn't answering his email (please no one copy this if you are doing the same work our stuff has been submitted to the board its only being re submitted so you will fail :(
how do I extract the players name from the file to store the winner? idk if that makes sense


import random
import time
import re
i = 0
Player1Points = 0
Player2Points = 0
Player1Tiebreaker = 0
Player2Tiebreaker = 0
Winner_Points = 0

Users = open ("Usernames.txt.", "r+")
Passwords = open ("Passwords.txt.", "r+")
User_array = Users.read().splitlines()
Password_array = Passwords.read().splitlines()
User1 = False
User2 = False

def registration_p1(): # using a function to allow player 1 and 2 to create an account
registration_p1 = True
while registration_p1 == True:
user_1 = input("Enter username for p1")#asks user to create username
password_1 = input("Enter password for p1")#asks user to create password
if user_1 in User_array: # if the details are already found in the text files, the program will inform them
print("That account is already taken, sorry :(")
else:
Users.write(user_1) #saving username to usernames text file
Users.write("\n")
Passwords.write(password_1)#saving password to passwords text file
Passwords.write("\n")
print("Thanks")
registration_1 = False
break
Users = open ("Usernames.txt.", "r+") #reopens the files
Passwords = open ("Passwords.txt.", "r+")
def registration_p2():
registration_p2 = True# this function does the exact same except this time its for player 2
while registration_p2 == True:
user_2= input("Enter username for p2")
password_2 = input("Enter password for p2")
if user_2 in User_array:
print("That account is already taken, sorry :(")
else:
Users.write(user_2)
Users.write("\n")
Passwords.write(password_2)
Passwords.write("\n")
Users.close()
Passwords.close()
print("Great now you can log in :)")
registration_2 = False
break


def LoggingIn_1(): # function to authenticate player 1
user_1guess = input("Player One, please enter your username: ")
password_1guess = input("Player One, please enter your password: ")
while (user_1guess not in User_array) or (password_1guess not in Password_array):
print("Wrong, closing program ") #if the array cannot find the users supposed log in details it informs them
quit()
user_1guess = input("Player One, please enter your username: ")
password_1guess = input("Player One, please enter your password: ")
else:
player_1 = user_1guess
print ("Hi Player One, I hope you enjoy the game!") #if it is found, the player can move on
User_1 = True


def LoggingIn_2(): #this function does the same for player 2
user_2guess = input("Player Two, please enter your username: ")
password_2guess = input("Player Two, please enter your password: ")
while (user_2guess not in User_array) or (password_2guess not in Password_array):
print("Wrong, closing program ")
quit()
user_2guess = input("Player Two, please enter your username: ")
password_2guess = input("Player Two, please enter your password: ")
else:
player_2 = user_2guess
print ("Hi Player Two, I hope you enjoy the game too!")
User_2 = True



def roll():
Player1Points = 0
Player2Points = 0
points = 0
die1 = random.randint(1,6)
die2 = random.randint(1,6)
dietotal = die1 + die2
points = points + dietotal
if dietotal % 2 == 0:
points = points + 10
else:
points = points - 5
if die1 == die2:
die3 = random.randint(1,6)
points = points +die3
return(points)



for i in range(1,5):
Player1Points += roll()
print('After this round ',player_1, 'you now have: ',Player1Points,' Points')
time.sleep(1)
Player2Points += roll()
print('After this round ',player_2, 'you now have: ',Player2Points,' Points')
time.sleep(1)

if Player1Points == Player2Points:
while Player1Tiebreaker == Player2Tiebreaker:
Player1Tiebreaker = random.randint(1,6)
Player2Tiebreaker = random.randint(1,6)
if Player1Tiebreaker > Player2Tiebreaker:
Player2Points = 0
elif Player2Tiebreaker > Player1Tiebreaker:
Player1Points = 0



if Player1Points>Player2Points:
Winner_Points = Player1Points
winner_User = player_1
winner = (Winner_Points, player_1)
elif Player2Points>Player1Points:
Winner_Points = Player2Points
winner = (Winner_Points, player_2)
winner_User = player_2

print('\nWell done, ', winner_User,' you won with ',Winner_Points,' Point\n\n')


leaderboard1 = "{}:{}".format(Winner_Points,winner_User)
with open ("Leaderboard.txt", "a") as file:
file.write("\n")
file.write(leaderboard1)


f = open('Leaderboard.txt', 'r')
leaderboard = [line.replace('\n','') for line in f.readlines()]
f.close()

leaderboard.sort(reverse=True)

with open('Leaderboard.txt', 'w') as f:
for item in leaderboard:
f.write("%s\n" % item)

print("TOP 5 SCORES:")
with open("Leaderboard.txt", "r") as f:
counter = 0
N = 1
for line in f:
head,sep,tail = line.partition(":")
print("Place No.{}\nUsername: {}Score: {}\n".format(N,tail,head))
N = N + 1
counter += 1
if counter == 5: break


def choices(): # using a function so it is quicker and more efficient, its to output the options to the users and allow them to choose what to do
choices_users = input("Enter 1: to make an account, 2: to log in or 3: to display scores or 4:to play(after you login)")
if choices_users != "1" or "2" or "3" or "4":
print ( "pick a valid option please")

if choices_users == "1": # if they choose "1", the functions for logging in shown previousky are called
registration_p1()
registration_p2()
choices()#then it goes back to the option page
if choices_users == "2":
LoggingIn_1()#the function to sign up is called when "2" is choosen
LoggingIn_2()
choices()#then it goes back to the option page
if choices_users == "3": #this opens the leaderboard and outputs the highest player
scoreboard = open ("scores.txt", "r")
print ("\n")
print("highest player is: ")
scores.close
else:
roll()
choices()
Reply
#2
If you will use the "Insert python" tag [Image: python.png] when you upload your code it makes it very easy for someone to test the code and find the problem. As it is, it is almost impossible to figure out how you had it indented and therefor what might be causing the issue.
Reply
#3
The reason for the error is that player1 is not defined. You have a variable named "player_1" defined in the function LiggingIn_1() (line 64). You have another variable (looks like a module variable but hard to tell with the code not indented) that has the same name down in line 105. These are not the same variable, they just have the same name. When you try to use "player_1" down in line 105, nobody has created a variable of that name in that scope. If you don't understand what I am saying you need to read about python variables and scope.
Reply
#4
You should not have a variable named player_1 or Player2Points. If you have a game with 2 players you should have a variable named players, and it should be a list of length 2. You will realize significant reduction in code if you stop thinking of the game as having 2 players and instead think of it as a single player game with two players taking turns.

Players have 2 attributes, a name and a score. There are multiple things in Python that can store more than one value; lists, dictionaries, classes. In the example below a dictionary is used to store the player's name and score.
A list holds the two player dictionaries.
"""Plays a dice game"""
import random
from time import sleep

def get_players():
    """Get players names and initialize scores"""
    players = []
    for i in range(2):
        players.append({'name':input('Enter Player {i+1} Name: '), 'score':0})
    return players

def roll_dice(players):
    """Give each player a turn.  Players roll two dice.  Players are awarded
    the total of the two dice. If the total is even, the player is awarded
    a 10 point bonus.  If the total is odd, the player is penalized 5 points.
    If the player rolls doubles they roll an additional die and are awarded
    a bonus equal to the value of the die.
    """

def play_game(players):
    """Play the dice game.  Players get 4 rolls and the player with the highest
    score wins.  If players are tied after 4 rolls they continue to roll until
    the tie is broken.
    """
    for _ in range(4):
        roll_dice(players)

    while players[0]['score'] == players[1]['score']:
        print('The score is tied!  Tiebreaker roll!')
        roll_dice(players)

    if players[0]['score'] > players[1]['score']:
        winner, loser = players
    else:
        loser, winner = players
    print(f'\n{winner["name"]} wins with {winner["score"]} points!')
    print(f'{loser["name"]} finishes with {loser["score"]} points\n\n')

players = get_players()
play_game(players)
Notice how little code is devoted to there being two players. Instead of doing something for player 1 and hen doing almost exactly the same thing for player 2, I use a for loop and iterate through he players. It would be simple to change this game to allow 3, 4, 500 players.
Reply
#5
(Feb-11-2021, 05:15 AM)deanhystad Wrote: import randomfrom time import sleep def get_players():    """Get players names and initialize scores"""    players = []    for i in range(2):        players.append({'name':input('Enter Player {i+1} Name: '), 'score':0})    return players def roll_dice(players):    """Give each player a turn.  Players roll two dice.  Players are awarded    the total of the two dice. If the total is even, the player is awarded    a 10 point bonus.  If the total is odd, the player is penalized 5 points.    If the player rolls doubles they roll an additional die and are awarded    a bonus equal to the value of the die.    """ def play_game(players):    """Play the dice game.  Players get 4 rolls and the player with the highest    score wins.  If players are tied after 4 rolls they continue to roll until    the tie is broken.    """    for _ in range(4):        roll_dice(players)     while players[0]['score'] == players[1]['score']:        print('The score is tied!  Tiebreaker roll!')        roll_dice(players)     if players[0]['score'] > players[1]['score']:        winner, loser = players    else:        loser, winner = players    print(f'\n{winner["name"]} wins with {winner["score"]} points!')    print(f'{loser["name"]} finishes with {loser["score"]} points\n\n') players = get_players()play_game(players)
where would I put that ? do I replace the roll function with that
Reply
#6
(Feb-11-2021, 01:35 AM)BashBedlam Wrote: If you will use the "Insert python" tag [Image: python.png] when you upload your code it makes it very easy for someone to test the code and find the problem. As it is, it is almost impossible to figure out how you had it indented and therefor what might be causing the issue.

oh sorry I didn't know that
the code:
import random
import time
import re
i = 0
Player1Points = 0
Player2Points = 0
Player1Tiebreaker = 0
Player2Tiebreaker = 0
Winner_Points = 0

Users = open ("Usernames.txt.", "r+")
Passwords = open ("Passwords.txt.", "r+")
User_array = Users.read().splitlines()
Password_array = Passwords.read().splitlines()
User1 = False
User2 = False

def registration_p1(): # using a function to allow player 1 and 2 to create an account
    registration_p1 = True
    while registration_p1 == True:
        user_1 = input("Enter username for p1")#asks user to create username
        password_1 = input("Enter password for p1")#asks user to create password
        if user_1 in User_array: # if the details are already found in the text files, the program will inform them
            print("That account is already taken, sorry :(")
        else:
            Users.write(user_1) #saving username to usernames text file
            Users.write("\n")
            Passwords.write(password_1)#saving password to passwords text file
            Passwords.write("\n")
            print("Thanks")
            registration_1 = False
            break        
Users = open ("Usernames.txt.", "r+") #reopens the files
Passwords = open ("Passwords.txt.", "r+")           
def registration_p2():
    registration_p2 = True# this function does the exact same except this time its for player 2
    while registration_p2 == True:
        user_2= input("Enter username for p2")
        password_2 = input("Enter password for p2")
        if user_2 in User_array:
            print("That account is already taken, sorry :(")
        else:
            Users.write(user_2)
            Users.write("\n")
            Passwords.write(password_2)
            Passwords.write("\n")
            Users.close()
            Passwords.close()
            print("Great now you can log in :)")
            registration_2 = False
            break

            
def LoggingIn_1(): # function to authenticate player 1
    user_1guess = input("Player One, please enter your username:  ") 
    password_1guess = input("Player One, please enter your password:  ") 
    while (user_1guess not in User_array) or (password_1guess not in Password_array): 
        print("Wrong, closing program ") #if the array cannot find the users supposed log in details it informs them
        quit()
        user_1guess = input("Player One, please enter your username: ") 
        password_1guess = input("Player One, please enter your password:  ") 
    else: 
        player_1 = user_1guess
        print ("Hi Player One, I hope you enjoy the game!") #if it is found, the player can move on
        User_1 = True
        

def LoggingIn_2(): #this function does the same for player 2
    user_2guess = input("Player Two, please enter your username:  ") 
    password_2guess = input("Player Two, please enter your password:  ") 
    while (user_2guess not in User_array) or (password_2guess not in Password_array): 
        print("Wrong, closing program ")
        quit()
        user_2guess = input("Player Two, please enter your username: ") 
        password_2guess = input("Player Two, please enter your password:  ") 
    else: 
        player_2 = user_2guess
        print ("Hi Player Two, I hope you enjoy the game too!")
        User_2 = True


def roll():
    points = 0
    die1 = random.randint(1,6)
    die2 = random.randint(1,6)
    dietotal = die1 + die2
    points = points + dietotal
    
    if dietotal % 2 == 0:
        points = points + 10

    else:
        points = points - 5

    if die1 == die2:
        die3 = random.randint(1,6)
        points = points +die3

    return(points)

for i in range(1,5):
    Player1Points += roll()
    print('After this round ',player_1, 'you now have: ',Player1Points,' Points')
    time.sleep(1)
    Player2Points += roll()
    print('After this round ',player_2, 'you now have: ',Player2Points,' Points')
    time.sleep(1)

if Player1Points == Player2Points:
    while Player1Tiebreaker == Player2Tiebreaker:
        Player1Tiebreaker = random.randint(1,6)
        Player2Tiebreaker = random.randint(1,6)

    if Player1Tiebreaker > Player2Tiebreaker:
        Player2Points = 0
    elif Player2Tiebreaker > Player1Tiebreaker:
        Player1Points = 0



if Player1Points>Player2Points:
    Winner_Points = Player1Points
    winner_User = player_1
    winner = (Winner_Points, player_1)
elif Player2Points>Player1Points:
    Winner_Points = Player2Points
    winner = (Winner_Points, player_2)
    winner_User = player_2

print('\nWell done, ', winner_User,' you won with ',Winner_Points,' Point\n\n')


leaderboard1 = "{}:{}".format(Winner_Points,winner_User)
with open ("Leaderboard.txt", "a") as file:
    file.write("\n")
    file.write(leaderboard1)


f = open('Leaderboard.txt', 'r')
leaderboard = [line.replace('\n','') for line in f.readlines()]
f.close()

leaderboard.sort(reverse=True)

with open('Leaderboard.txt', 'w') as f:
    for item in leaderboard:
        f.write("%s\n" % item)

print("TOP 5 SCORES:")
with open("Leaderboard.txt", "r") as f:
    counter = 0
    N = 1
    for line in f:
        head,sep,tail = line.partition(":")
        print("Place No.{}\nUsername: {}Score: {}\n".format(N,tail,head))
        N = N + 1
        counter += 1
        if counter == 5: break

        
def choices(): # using a function so it is quicker and more efficient, its to output the options to the users and allow them to choose what to do
    choices_users = input("Enter 1: to make an account, 2: to log in or 3: to display scores or 4:to play(after you login)")
    if choices_users != "1" or "2" or "3" or "4":
        print ( "pick a valid option please")

    if choices_users == "1": # if they choose "1", the functions for logging in shown previousky are called
            registration_p1()
            registration_p2()
            choices()#then it goes back to the option page
    if choices_users == "2":
        LoggingIn_1()#the function to sign up is called when "2" is choosen
        LoggingIn_2()
        choices()#then it goes back to the option page
    if choices_users == "3": #this opens the leaderboard and outputs the highest player
        scoreboard = open ("scores.txt", "r")
        print ("\n")
        print("highest player is: ")
        scores.close
    else:
        roll()
choices()
Reply
#7
You don't seem to understand how Python works when loading a module. Code that does not appear inside a function is executed when you import a module or run a python program. All of this code runs immediately because it is not inside a function.
import random
import time
import re
i = 0
Player1Points = 0
Player2Points = 0
Player1Tiebreaker = 0
Player2Tiebreaker = 0
Winner_Points = 0
 
Users = open ("Usernames.txt.", "r+")
Passwords = open ("Passwords.txt.", "r+")
User_array = Users.read().splitlines()
Password_array = Passwords.read().splitlines()
User1 = False
User2 = False
So you immediately set Player1Points = 0 and immediately open the file "Usernames.txt". So far so good.

Slightly further down in the file you do this:
Users = open ("Usernames.txt.", "r+") #reopens the files
Passwords = open ("Passwords.txt.", "r+")           
def registration_p2():
    registration_p2 = True# this function does the exact same except this time its for player 2
    while registration_p2 == True:
        user_2= input("Enter username for p2")
        password_2 = input("Enter password for p2")
        if user_2 in User_array:
            print("That account is already taken, sorry :(")
        else:
            Users.write(user_2)
            Users.write("\n")
            Passwords.write(password_2)
            Passwords.write("\n")
            Users.close()
            Passwords.close()
            print("Great now you can log in :)")
            registration_2 = False
            break
Why are you opening "Usernames.txt" again? Do you think this code happens after registration_p1 but before retistration_p2? It doesn't. registration_p1 and registration_p2 aren't executed until called by choices(). So your code is doing this:
Users = open ("Usernames.txt.", "r+")
Passwords = open ("Passwords.txt.", "r+")
User_array = Users.read().splitlines()
Password_array = Passwords.read().splitlines()
User1 = False
User2 = False
Users = open ("Usernames.txt.", "r+") #reopens the files
Passwords = open ("Passwords.txt.", "r+")
You do this throughout your program, interspersing code that will execute as soon as the program is run with code that is only executed when the function is called.

In your program there should be almost no code that is outside a function. You should have the import statements at the top of the file. You may have a couple of global variables defined at the top of the file, though global variables are a bad idea. This should be followed by a bunch of functions, and then at the very bottom you have one command that calls choices(). Maybe 5 lines of code that are outside of a function (def).
Reply
#8
In an earlier post I mentioned that you can greatly reduce the amount of code if you stop thinking about there being two players. Your code has a function to register player 1 and another to register player 2. Why?

These two functions are nearly identical.
def registration_p1(): # using a function to allow player 1 and 2 to create an account
    registration_p1 = True
    while registration_p1 == True:
        user_1 = input("Enter username for p1")#asks user to create username
        password_1 = input("Enter password for p1")#asks user to create password
        if user_1 in User_array: # if the details are already found in the text files, the program will inform them
            print("That account is already taken, sorry :(")
        else:
            Users.write(user_1) #saving username to usernames text file
            Users.write("\n")
            Passwords.write(password_1)#saving password to passwords text file
            Passwords.write("\n")
            print("Thanks")
            registration_1 = False
            break        

def registration_p2():
    registration_p2 = True# this function does the exact same except this time its for player 2
    while registration_p2 == True:
        user_2= input("Enter username for p2")
        password_2 = input("Enter password for p2")
        if user_2 in User_array:
            print("That account is already taken, sorry :(")
        else:
            Users.write(user_2)
            Users.write("\n")
            Passwords.write(password_2)
            Passwords.write("\n")
            Users.close()
            Passwords.close()
            print("Great now you can log in :)")
            registration_2 = False
            break
Why isn't this one function? At this time there is no game being played, so there is no such thing as player_1 or player_2. You have people who are registering so that they can play your game.

If I was writing this code I would have 1 register function and a couple of support functions for loading the user accounts from a file and saving the user accounts to a file.
def load_accounts():
    """Load account inforation from a file.  Return accounts as
    a dictionary that maps usernames to passwords:
         {username1:password1, username2:password2}
    """
    #todo

def save_accounts(accounts):
    """Save account inforation to a file."""
    #todo

def register():
    """Create a player account"""
    accounts = load_accounts()
    while True:
        name = input("Enter username: ")
        if name in accounts:
            print(f'{name} is already taken")
            continue
        accounts[name] = input('Enter password: ')
        save_accounts()
        break
There is nothing in this code that mentions player 1 or player 2. Any player will use this same function go create an account so they can play your game. The support functions will be reused when users login to play and would also be used by any user account maintenance code.

You make this same mistake over and over in your code. You have LoggingIn_1 and LoggingIn_2. You should have 1 login function.
def login()
    """function to authenticate player.  Return player name
    if successful or None if player doesn't have an account
    or used an invalid password
    """
    accounts = load_accounts()
    for attempt in range(3): Give player 3 tries to log in
        name = input("Enter username: ") 
        if not name in accounts:
            print(f'{name} is not a valid username.')
            continue
        if accounts[name] != input('Enter password: '):
            print('Invalid password.')
            continue
        print('Login successful')
        return name
    
    print('Login unsuccessful')
    return None
Reply
#9
One last thing. This code does not work the way you expect.
    if choices_users != "1" or "2" or "3" or "4":
        print ( "pick a valid option please")
choices_users != "1" or "2" or "3" or "4" will evaluate to True unless user_choices == "1". To understand why read about the "or" operator.

https://realpython.com/python-or-operator/

A lot of people get this wrong.
Reply
#10
(Feb-11-2021, 05:12 PM)deanhystad Wrote: One last thing. This code does not work the way you expect.
    if choices_users != "1" or "2" or "3" or "4":
        print ( "pick a valid option please")
choices_users != "1" or "2" or "3" or "4" will evaluate to True unless user_choices == "1". To understand why read about the "or" operator.

https://realpython.com/python-or-operator/

A lot of people get this wrong.


thank you so much, we didn't get to learn a lot because of covid and I was struggling and tried to teach myself, I really appreciate the help you gave me and ill keep that advice in future.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  I need help with a python Rock Paper Scissors game urgently. Riff_Raff 3 5,921 Dec-05-2018, 09:13 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

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