How would I clean this code/shorten it (most of it is login)
What the program does:
Only authorized players are allowed to play.
Input from user should be validated where possible.
5 rounds.
Score cannot go below 0.
2 players roll 2 6-sided dice.
Points rolled on each player's dice are added to their score.
If total is even number, add 10 points to score.
If total is odd number, subtract 5 points from score.
If they roll a double they get to roll one extra die and the points rolled added to their score.
Person with highest score wins.
If have same score at end, they roll 1 die and whoever gets the highest score wins.
#Importing modules
import random
import time
import re
##################################################################################################################################
#Defining global variables
i = 0
Player1Points = 0
Player2Points = 0
Player1Tiebreaker = 0
Player2Tiebreaker = 0
Winner_Points = 0
##################################################################################################################################
#Authorisation/Registration
#Login
def login():
#Defining function variables
x = 0
UserNumber = 1
login = False
found = False
placeholder = True
NoLowercase = True
NoUppercase = True
NoNumber = True
NoSymbol = True
NoSymbolPlaceHolder = False
#Function starts
while login == False:
while found != True:
player = input("Has User{} got an account? Y/N: ".format(UserNumber))
if player == "Y" or player == "y":
user = input("Input User{}'s username: ".format(UserNumber))
password = input("\nInput your password: ")
user = user.lower()
user = user.replace(" ","")
password = password.replace(" ","")
with open('Usernames.TXT') as file:
for line in file:
uu, pp = line.strip().split(':')
if user == uu and password == pp:
print("\nUser found\n")
if x == 0:
global user1
user1 = user
found = True
x = 1
UserNumber = 2
elif x == 1:
global user2
user2 = user
found = True
login = True
x = 2
break
if not found:
print("\nUser{} not found\n".format(UserNumber))
if x == 1:
found = False
#Register username
elif player == "N" or player == "n":
UsernameModule = False
while UsernameModule != True:
RegisterUsername = input("\nInput your desired username: ")
RegisterUsername = RegisterUsername.lower()
RegisterUsername = RegisterUsername.replace(" ","")
if len(RegisterUsername) <= 16 and len(RegisterUsername) >= 4:
RegisterUsernameValidation = input("\nInput your desired username again: ")
RegisterUsernameValidation = RegisterUsernameValidation.lower()
RegisterUsernameValidation = RegisterUsernameValidation.replace(" ","")
if RegisterUsername != RegisterUsernameValidation:
print("\nThe username you have inputted is not the same, please try again.")
elif RegisterUsername == RegisterUsernameValidation:
print("\nThe username you have inputted match.")
print("\nYour username is:",RegisterUsernameValidation)
UsernameModule = True
elif len(RegisterUsername) > 16 or len(RegisterUsername) < 4:
print("\nSorry, your username is either shorter than 4 characters or longer than 16 characters.")
#Register password
PasswordModule = False
while PasswordModule != True:
RegisterPassword = input("\nInput your desired password: ")
#Checking if password has symbols, numbers, upper and lower case
N = 0
N2 = 1
while N2 < 17:
if N == 0:
RegisterPassword = RegisterPassword.replace(" ","")
else:
placeholder1 = True
RegisterPassword1 = RegisterPassword[N:N2]
if RegisterPassword1.islower() == True: # there is lowercase
NoLowercase = False
else:
placeholder1 = True
if RegisterPassword1.isupper() == True:
NoUppercase = False
else:
placeholder1 = True
if RegisterPassword1.isdigit() == True:
NoNumber = False
else:
placeholder1 = True
if RegisterPassword1 == "[" or RegisterPassword1 == "@" or RegisterPassword1 == "_" or RegisterPassword1 == "!" or RegisterPassword1 == "#" or RegisterPassword1 == "$" or RegisterPassword1 == "%" or RegisterPassword1 == "^" or RegisterPassword1 == "&" or RegisterPassword1 == "*" or RegisterPassword1 == "(" or RegisterPassword1 == ")" or RegisterPassword1 == "<" or RegisterPassword1 == ">" or RegisterPassword1 == "?" or RegisterPassword1 == "/" or RegisterPassword1 == "\\" or RegisterPassword1 == "|" or RegisterPassword1 == "}" or RegisterPassword1 == "{" or RegisterPassword1 == "~" or RegisterPassword1 == ":" or RegisterPassword1 == "]":
NoSymbolPlaceHolder = True
else:
placeholder1 = True
if NoSymbolPlaceHolder == True:
NoSymbol = False
else:
placeholder1 = True
N = N + 1
N2 = N2 + 1
if len(RegisterPassword) > 7 and len(RegisterPassword) < 17 and NoLowercase == False and NoUppercase == False and NoNumber == False and NoSymbol == False:
RegisterPasswordValidation = input("\nInput your desired password again:")
RegisterPasswordValidation = RegisterPasswordValidation.replace(" ","")
if RegisterPassword != RegisterPasswordValidation:
print("\nThe password you have inputted is not the same, please try again.")
elif RegisterPassword == RegisterPasswordValidation:
print("\nThe password you have inputted match.")
print("\nYour password is:",RegisterPasswordValidation)
PasswordModule = True
RegisteredUsernameAndPassword = RegisterUsername+":"+RegisterPassword
with open("Usernames.txt", "a") as file:
file.write("\n")
file.write(RegisteredUsernameAndPassword)
print("\nYou have successfully registered!")
elif len(RegisterPassword) <= 7 or len(RegisterPassword) > 16:
print("\nYour password needs a total of 8 to 16 characters.")
if NoLowercase == True:
print("\nYour password does not have lowercase letters.")
if NoUppercase == True:
print("\nYour password does not have uppercase letters.")
if NoNumber == True:
print("\nYour password does not have numbers.")
if NoSymbol == True:
print("\nYour password does not have symbols, please try again.")
N = 0
N2 = 1
elif placeholder == True:
placeholder1 = True
N = 0
N2 = 1
elif NoSymbol == True:
print("\nYour password does not have symbols, please try again.")
N = 0
N2 = 1
elif NoNumber == True:
print("\nYour password does not have numbers.")
if NoSymbol == True:
print("\nYour password does not have symbols, please try again.")
N = 0
N2 = 1
elif placeholder == True:
placeholder1 = True
N = 0
N2 = 1
elif NoSymbol == True:
print("\nYour password does not have symbols, please try again.")
N = 0
N2 = 1
elif NoUppercase == True:
print("\nYour password does not have uppercase letters.")
if NoNumber == True:
print("\nYour password does not have numbers.")
if NoSymbol == True:
print("\nYour password does not have symbols, please try again.")
N = 0
N2 = 1
elif placeholder == True:
placeholder1 = True
N = 0
N2 = 1
elif NoSymbol == True:
print("\nYour password does not have symbols, please try again.")
N = 0
N2 = 1
elif NoNumber == True:
print("\nYour password does not have numbers.")
if NoSymbol == True:
print("\nYour password does not have symbols, please try again.")
N = 0
N2 = 1
elif placeholder == True:
placeholder1 = True
N = 0
N2 = 1
elif NoSymbol == True:
print("\nYour password does not have symbols, please try again.")
N = 0
N2 = 1
elif NoLowercase == True:
print("\nYour password does not have lowercase letters.")
if NoUppercase == True:
print("\nYour password does not have uppercase letters.")
if NoNumber == True:
print("\nYour password does not have numbers.")
if NoSymbol == True:
print("\nYour password does not have symbols, please try again.")
N = 0
N2 = 1
elif placeholder == True:
placeholder1 = True
N = 0
N2 = 1
elif NoSymbol == True:
print("\nYour password does not have symbols, please try again.")
N = 0
N2 = 1
elif NoNumber == True:
print("\nYour password does not have numbers.")
if NoSymbol == True:
print("\nYour password does not have symbols, please try again.")
N = 0
N2 = 1
elif placeholder == True:
placeholder1 = True
N = 0
N2 = 1
elif NoSymbol == True:
print("\nYour password does not have symbols, please try again.")
N = 0
N2 = 1
elif NoUppercase == True:
print("\nYour password does not have uppercase letters.")
if NoNumber == True:
print("\nYour password does not have numbers.")
if NoSymbol == True:
print("\nYour password does not have symbols, please try again.")
N = 0
N2 = 1
elif placeholder == True:
placeholder1 = True
N = 0
N2 = 1
elif NoSymbol == True:
print("\nYour password does not have symbols, please try again.")
N = 0
N2 = 1
elif NoNumber == True:
print("\nYour password does not have numbers.")
if NoSymbol == True:
print("\nYour password does not have symbols, please try again.")
N = 0
N2 = 1
elif placeholder == True:
placeholder1 = True
N = 0
N2 = 1
elif NoSymbol == True:
print("\nYour password does not have symbols, please try again.")
N = 0
N2 = 1
elif player != "y" or player != "n" or player != "Y" or player != "N":
print("\nTry again.\n")
return()
login()
###### DEFINING ROLL ######
### Makes the dice roll for the player and works out the total for that roll ###
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)
###### DICE ROLL ######
### This rolls the dice 5 times for the players, and then adds up the total. If the scores are equal, it starts a tie breaker and determines the winner off that ###
for i in range(1,5):
Player1Points += roll()
print('After this round ',user1, 'you now have: ',Player1Points,' Points')
time.sleep(1)
Player2Points += roll()
print('After this round ',user2, '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
###### WORKING OUT THE WINNER ######
### This checks which score is bigger, then creates a tuple for my leaderboard code ###
if Player1Points>Player2Points:
Winner_Points = Player1Points
winner_User = user1
winner = (Winner_Points, user1)
elif Player2Points>Player1Points:
Winner_Points = Player2Points
winner = (Winner_Points, user2)
winner_User = user2
print('\nWell done, ', winner_User,' you won with ',Winner_Points,' Point\n\n')
###### CODE TO UPLOAD ALL SCORES TO A FILE ######
### This will store the winners username and score in a text file ###
leaderboard1 = "{}:{}".format(Winner_Points,winner_User)
with open ("Leaderboard.txt", "a") as file:
file.write("\n")
file.write(leaderboard1)
###### CODE TO LOAD, UPDATE AND SORT LEADERBOARD ######
### This loads the leaderboard into an array, then compares the scores just gotton and replaces it ###
f = open('Leaderboard.txt', 'r')
leaderboard = [line.replace('\n','') for line in f.readlines()]
f.close()
### This sorts the leaderboard in reverse, and then rewrites it ###
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
-
\$\begingroup\$ It would be very helpful if the title indicated what the entire project is. \$\endgroup\$pacmaninbw– pacmaninbw ♦2019年11月24日 17:02:59 +00:00Commented Nov 24, 2019 at 17:02
1 Answer 1
For simplicity I have just used variables to assign a user name and password. You should never hard code this, instead use a dictionary file with open
that compares the key username to the value password for simple storage. If you want a more creative way to store and gather the information you can use an encrypted database such as SQlCipher. You do not need to account for every instance of what an input is, you can just use an else
clause if the credentials are not correct.
user_name = 'admin'
pwd = 'password'
def login():
while True:
try:
i = input('Enter username:> ')
if i == user_name:
p = input('Enter password:> ')
if p == pwd:
print('FUNCTION TO GAME HERE')
break # whatever your game function is
else:
print('Wrong password')
else:
print('User does not exist')
except ValueError:
print('Invalid')
login()
Your code gives hints to what the password or user name is. This defeats the object of keeping the information safe with as little possibility that it is going to be guessed.
Output:
Enter username:> a
User does not exist
Enter username:> 1
User does not exist
Enter username:> admin
Enter password:> p
Wrong password
Enter username:> admin
Enter password:> password
FUNCTION TO GAME HERE