For loop inside while loop in asking user input with conditions - python

I am writing a python game and it has following features to ask from user.
it can be up to 4 players (minimum 1 player, maximum 4 player)
It will ask players name. If the name is already exists, the program will prompt "name already in the list" and ask to enter the name again
if the player enters empty string in player name input, it will exits.
it will ask how many n number of random digits player want to play with (randint(start, stop) is used). only up to 3 digits are allowed
I know I have to user while loop for indefinitely ask the user input until the condition is satisfied. I also have to use for loop to ask users for a name based on the input at point 1.
Following is my attempt which has errors. Hence, need your help in review -
def attempt1():
playerList = []
numPlayers = input("How Many Players? ")
if int(numPlayers) < 5 and int(numPlayers) > 0:
while True:
if numPlayers != "":
for i in range(int(numPlayers)):
playerName = input("Player name or <Enter> to end ")
if playerName != "":
if playerName not in playerList:
playerList.append(playerName)
break
else:
print("Player Name Cannot be empty")
# numPlayers = input("How Many Players? ")
else:
print("There must be at least one player")
numPlayers = input("How Many Players? ")
else:
print("Invalid number of players. Please enter 1 - 4")
print(playerList)
def attempt2(numPlayers):
playerList = list()
# numPlayers = 1
i = 0
while i < 4:
for x in range(0,numPlayers):
playerName = input("Name ")
if playerName not in playerList:
playerList.append(playerName)
i += 1
else:
print("Name is already in the list")
print(playerList)
return playerList

This solves my issue. Please kindly suggest if you have better solutions. I am sure my code here is messy but it works for now.
def askPlayerName(numPlayers):
playerList = []
x = numPlayers
while True:
if x > 0:
for i in range(x):
print(x)
playerName = input("Enter name: ")
if playerName not in playerList:
x -= 1
playerList.append(playerName)
break
else:
print("ELSE")
x = numPlayers - len(playerList)
print(x)
print("name aldy in the list")
else:
return playerList
return playerList

Related

Python - How can I save the player's score as they keep increasing it? Any help is appreciated

to learn Python I'm working on a small terminal upgrade game. The user enters a number that is added to a random integer to get a score (called "Films Produced" in game). The problem I can't seem to fix is every time the player goes to the menu and back then back to entering more numbers the previous number is deleted instead of added on to the new one.
Here is the code:
print("TERMINAL FILM by Dominick")
print("---------------------")
# SCORE
def filmClicker():
global score
user_input = int(input(">> Enter a number: "))
score = user_input
if user_input > 5 or user_input < 0 or user_input == 0:
print(">> Not a valid number.")
filmClicker()
elif score > 0:
score = score + random.randint(1, 50)
print("")
print(">> You produced:", score, "films", "<<")
go_back_or_menu = input(">> Press ENTER to go again. Or type TAB to go back to the menu. ")
if go_back_or_menu == "":
filmClicker()
elif go_back_or_menu == "TAB" or "Tab" or "tab":
game()
def game():
print(">>>>>>>>>>>>> Menu >>>>>>>>>>>>>")
print(">> Type A to go make films. ")
print(">> Type B to see your current balance. ")
print(">> Type C to see the current box office. ")
print(">> Type D for your stats. ")
press_button_menu = input("")
if press_button_menu == "A":
filmClicker()
elif press_button_menu == "B":
print("Current Balance =", score)
press_enter()
game()
else:
filmClicker()
game()
So I want the player to be able to insert a number, the number gets added to another number by the computer, and then a final number is spit out. I got all that working. But it doesn't save when you do that multiple times. Which I don't want, I want it to stack each time you do it.
Sorry if I poorly explained it, I can answer more about it if needed. Any help is appreciated.
UPDATE:
I removed the score = "input" variable and declared it out of any function. But it's still not saving. Here is a better answer as to what I want it to do:
In the picture below I start at the game menu. I then decide to make films, I do it 5 times. But then when I go back to the menu and check my balance, the balance equals the last time I made films and not the TOTAL films. What I want it to do is add up all of the films. So in this case 48 + 49 + 9 + 38 + 25 instead of having just the last set (which is 25 in this case), to get a total balance which can be displayed by going to the menu and typing "B."
Here is the current code:
import random
score = 0
# SCORE
def filmClicker():
global score
user_input = int(input(">> Enter a number: "))
if user_input > 5 or user_input < 0 or user_input == 0:
print(">> Not a valid number.")
filmClicker()
elif score > 0:
score = score + random.randint(1, 50)
print("")
print(">> You produced:", score, "films", "<<")
go_back_or_menu = input(">> Press ENTER to go again. Or type TAB to go back to the menu. ")
print(go_back_or_menu)
if go_back_or_menu == "":
filmClicker()
elif go_back_or_menu == "TAB" or "Tab" or "tab":
game_menu()
# GAME MENU
def game_menu():
print(">>>>>>>>>>>>> Menu >>>>>>>>>>>>>")
print(">> Type A to go make films. ")
print(">> Type B to see your current balance. ")
print(">> Type C to see the current box office. ")
print(">> Type D for your stats. ")
press_button_menu = input("")
if press_button_menu == "A":
filmClicker()
elif press_button_menu == "B":
print("Current Balance =", score)
press_enter()
game_menu()
else:
filmClicker()
game_menu()
SECOND UPDATE:
Updated Code:
import random
score = 0
# PRINT BLANK LINE
def press_enter():
press_enter = print(input(""))
# SCORE
def filmClicker():
global score
user_input = int(input(">> Enter a number: "))
score += user_input
produced = random.randint(1, 50)
if user_input > 5 or user_input < 0 or user_input == 0:
print(">> Not a valid number.")
filmClicker()
elif score > 0:
score += produced
print("")
print(">> You produced:", produced, "films", "<<")
go_back_or_menu = input(">> Press ENTER to go again. Or type TAB to go back to the menu. ")
print(go_back_or_menu)
if go_back_or_menu == "":
filmClicker()
elif go_back_or_menu == "TAB" or "Tab" or "tab":
game_menu()
# GAME MENU
def game_menu():
print(">>>>>>>>>>>>> Menu >>>>>>>>>>>>>")
print(">> Type A to go make films. ")
print(">> Type B to see your current balance. ")
print(">> Type C to see the current box office. ")
print(">> Type D for your stats. ")
press_button_menu = input("")
if press_button_menu == "A":
filmClicker()
elif press_button_menu == "B":
print("Current Balance =", score)
press_enter()
game_menu()
else:
filmClicker()
game_menu()
In the picture below it's printing how much the player is producing from that turn but I also am testing the score (which is what the 6 and 49 stand for). It's scaling weird like that, where it adds a certain amount after every turn. Any way to fix this?
I think you are looking for the += operator.
Keep the score = 0 at the top of the file to initialize the variable, then use score += user_input to keep a running tally. This is the same as writing score = score + user_input.
In your filmClicker function, you should remove the following line:
score = user_input
By assigning to it, you've essentially erased its previous value which is why it doesn't accumulate between rounds.
For saving data, You can Use Files in python
For Saving:
f=open("data_game.txt","w")
f.write(<your score>)
f.close()
For Reading:
f=open("data_game.txt","r")
score=f.read()
print(score)
f.close()

How to make random.randit get new number, every time the game starts again

i have to make this GUESS THE NUMBER Gamme from 1-100 that will restart if user wants to play again,
the user can try to find the number 10 times.
But i have a problem..
every time the user says "yes" to play again,the program will not change the random number,i try to find some solution but i didnt
here is the code
import random
guesses = 0 # μετραει ποσες προσπαθειεςς εγιναν απο τον χρηστη
print("Hello,lets play a game...and try to find the number i have guess!!")
number = random.randint(1, 100)
**while guesses < 11:
print('Please Guess a number from (1-100):')
enter = input()
enter = int(enter)
guesses = guesses + 1
if enter < number:
print('This number you enter is lower,please try again')
if enter > number:
print('This number you enter is higher,please try again')
if enter == number:
score = 10 - guesses
score = str(score)
guesses = str(guesses)
print('Well Done, You found it! \nYor Score is' + score + '!')
print('DO you want to play again; yes/no:')
out = input()
if out == "no":
break
elif out == "yes":
guesses = 0
if guesses > 10:
number = str(number)
print("i'm sorry you lost, the number is " + number)
print("Have a great time")**
In addition to reset the guesses inside the elif out == "yes" block, reset also the number. Try:
elif out == "yes":
guesses = 0
number = random.randint(1, 100)

how to congratulate player with using hint and without using it differently

i would like to know how to tell the computer to print different input for player using hint
and for someone who doesn't used it to congratulate them
import random
words = dict(
python = "type of snake",
honda = "type of car",
spanish = "type of language",)
word = list(words)
var = random.choice(word)
score = 0
chance = 5
x = list(var)
random.shuffle(x)
jumble = "".join(x)
print("the jumble word is :", jumble,)
while True:
guess = input(" this is my guess :")
if guess == "hint":
print(words[var])
if guess == var:
print("well done you only used ", score,"to guessed it ")
break
else:
print("try again")
score +=1
if score == chance:
print("better luck next time")
break
What about adding a boolean, say hintUsed, that keeps track of whether or not the user used a hint:
hintUsed = False
while True:
guess = input(" this is my guess :")
if guess == "hint":
hintUsed = True # change hintUsed to True !!
print(words[var])
And then, to congratulate:
if guess == var:
if hintUsed:
#print a message
else:
#print another message
break

How to have python recognize correct value in my code? Dictionaries

for i in range(n):
while len(dictionary)>0:
choice = random.choice(list(dictionary.keys()))
correctAnswer = dictionary[choice]
print("English: ",choice)
guess = input("Spanish: ")
dictionary.pop(choice)
if guess == correctAnswer:
print("\nCorrect!\n")
else:
print("Incorrect\n")
wrongAnswers.append(choice)
break
print("\nYou missed", len(wrongAnswers), "words\n")
Hi, I am trying to create a vocabulary test on python. My code works up until this chunk. After the program prompts the user for their guess, the program will say it is incorrect even if it is the right answer. Is there an error in this code? How can I get around this?
This is what it looks like:
English: white
Spanish: blanco
Incorrect
English: purple
Spanish: morado
Incorrect
Thanks!
Full Code:
def main():
import random
wrongAnswers = []
print("Hello, Welcome to the Spanish-English vocabulary test.")
print(" ")
print("\nAfter the test, this program will create a file of the incorrect answers for you to view")
print("\nTo start, please select from the following options: \nverbs.txt \nadjectives.txt \ncolors.txt \nschool.txt \nplaces.txt") #sk
while True: #SK
selection = input("Insert your selection: ").lower() #user inputs selection #sk
if selection == "verbs.txt" or selection == "adjectives.txt" or selection == 'colors.txt' or selection == 'school.txt' or selection == 'places.txt':
print("You have chosen", selection, "to be tested on.")
break
if False:
print("try again.")
selection = input("Insert your selection: ").lower()
break
file = open(selection, 'r')
dictionary = {}
with file as f:
for line in f:
items = line.rstrip("\n").split(",")
key, values = items[0], items[1:]
dictionary[key] = values
length = len(dictionary)
print(length,'entries found')
n= int(input("How many words would you like to be tested on: "))
while n > length:
print("Invalid. There are only" ,length, "entries")
n= int(input("How many words would you like to be tested on: "))
print("You have chosen to be tested on",n, "words.\n")
for i in range(n):
while len(dictionary)>0:
choice = random.choice(list(dictionary.keys()))
correctAnswer = dictionary[choice]
print("English: ",choice)
guess = input("Spanish: ")
dictionary.pop(choice)
if guess == correctAnswer:
print("\nCorrect!\n")
else:
print("Incorrect\n")
wrongAnswers.append(choice)
break
print("\nYou missed", len(wrongAnswers), "words\n")
if len(wrongAnswers) > 0:
wrong = str(wrongAnswers)
output = input("Please name the file you would like you wrong answers to be saved in: ")
outf = open(output, 'w')
outf.write(wrong)
outf.close()
else:
print("You got all of the problems correct!")
main()

Computer guessing game

import random
def start():
print "\t\t***-- Please enter Y for Yes and N for No --***"
answer = raw_input("\t\t Would you like to play a Guessing Game?: ")
if answer == "Y"
or answer == "y":
game()
elif answer == "N"
or answer == "n":
end()
def end():
print("\t\t\t **Goodbye** ")
raw_input("\t\t\t**Press ENTER to Exit**")
def game():
print "\t\t\t Welcome to Williams Guessing Game"
user_name = raw_input("\n\t\t Please enter your name: ")
print "\n", user_name, "I am thinking of a number between 1 and 20"
print "You have 5 attempts at getting it right"
attempt = 0
number = random.randint(1, 20)
while attempt < 5:
guess = input("\t\nPlease enter a number: ")
attempt = attempt + 1
answer = attempt
if guess < number:
print "\nSorry", user_name, "your guess was too low"
print "You have ", 5 - attempt, " attempts left\n"
elif guess > number:
print "\nSorry ", user_name, " your guess was too high"
print "You have ", 5 - attempt, " attempts left\n"
elif guess == number:
print "\n\t\t Yay, you selected my lucky number. Congratulations"
print "\t\t\tYou guessed it in", attempt, "number of attempts!\n"
answer = raw_input("\n\t\t\t\tTry again? Y/N?: ")
if answer == "Y"
or answer == "y":
game()
elif answer == "N"
or answer == "n":
end()
start()
If you want the computer to guess your number, you could use a function like this:
import random
my_number = int(raw_input("Please enter a number between 1 and 20: "))
guesses = []
def make_guess():
guess = random.randint(1, 20)
while guess in guesses:
guess = random.randint(1, 20)
guesses.append(guess)
return guess
while True:
guess = make_guess()
print(guess)
if guess == my_number:
print("The computer wins!")
break
else:
print(guesses)
It's just a quick-and-dirty example, but I hope it gives you the idea. This way, the computer gets unlimited guesses, but you could easily change the while loop to limit its number of guesses.

Categories

Resources