Random word game python 3.5 - python-3.x

Hi i'm completely new to programming and have been trying to teach myself python, I have been trying to create a program that selects a word then shuffles the letters and prompts the user to input their guess within 3 tries. The problem I'm having is when a wrong answer is input it reshuffles the letters of the chosen word or returns a completely different word, here is my code:
import random
import sys
##Welcome message
print ("""\tWelcome to the scrambler,
select [E]asy, [M]edium or [H]ard
and you have to guess the word""")
##Select difficulty
difficulty = input("> ")
difficulty = difficulty.upper()
##For counting number of guesses it takes
tries = 0
while tries < 3:
tries += 1
##Starting the game on easy
if difficulty == 'E':
words = ['teeth', 'heart', 'police', 'select', 'monkey']
chosen = random.choice(words)
letters = list(chosen)
random.shuffle(letters)
scrambled = ''.join(letters)
print (scrambled)
guess = input("> ")
if guess == chosen:
print ("Congratulations!")
break
else:
print ("you suck")
else:
print("no good")
sys.exit(0)
As you can see I've only gotten as far as easy, I was trying to do it piece by piece and managed to overcome other problems but I can't seem to fix the one I'm having. Any help would be appreciated with the problem I'm having or any other issues you may spot in my code.

A few improvements and fixes for your game.
import random
import sys
# Game configuration
max_tries = 3
# Global vars
tries_left = max_tries
# Welcome message
print("""\tWelcome to the scrambler,
select [E]asy, [M]edium or [H]ard
and you have to guess the word""")
# Select difficulty
difficulty = input("> ")
difficulty = difficulty.upper()
if difficulty == 'E':
words = ['teeth', 'heart', 'police', 'select', 'monkey']
chosen = random.choice(words)
letters = list(chosen)
random.shuffle(letters)
scrambled = ''.join(letters)
else:
print("no good")
sys.exit(0)
# Now the scrambled word fixed until the end of the game
# Game loop
print("Try to guess the word: ", scrambled, " (", tries_left, " tries left)")
while tries_left > 0:
print(scrambled)
guess = input("> ")
if guess == chosen:
print("Congratulations!")
break
else:
print("You suck, try again?")
tries_left -= 1
Tell me if you don't understand something, I would be a pleasure to help you.

Related

How do i get out of this nested loop

I have been trying to get out of this nested loop I coded....please forgive me if the code is a bit too long but the actual important part has been commented at the last but one area of the code please help.
import random
import time
import math
# main
while True:
print('Only a maximum of three players are allowed in this game. A single player plays
with cpu')
print('1. Single Player\n2. Double Players\n3. Triple players')
print("Let's Start")
player_select = input('How many players will be playing ths game?: ')
single_score = [] # keep scores of player
cpu_score = [] # keep scores of CPU
while True:
lst = ['Rock', 'Paper', 'Scissors'] # holding the random three words
if player_select == '1' or player_select.lower() == 'single player':
randomize = random.choice(lst) # create a random choice out of the list
for i in last:
print(i) # display rock paper scissors
time.sleep(1)
print(randomize)
guess = input('guess rock, paper or scissors: ') # demanding for a guess
if guess.lower() == randomize.lower(): # what should happen if guess is right
single_score.append(1) # add 1 to the single_score list
print(f"Scores Player1 {single_score} \nScores Player CPU {cpu_score}")
elif guess.lower() != randomize.lower():
cpu_score.append(1)
print(f"Scores Player1 {single_score} \nScores Player CPU {cpu_score}")
print("Press 'Enter to continue'\n1. Change number of players(p)\n2. Exit(e) ")
question = input('Enter your choice: ')
if question == '':
continue
elif question.lower() in ['change number of players', 'p'] or question == '2':
print('Lets start all over')
#how do i get out of this to the intitial while loop?
elif question.lower() in ['exit', 'e'] or question == '3':
print('Total score of Player1', sum(single_score), '\n Total score of Player CPU',
sum(cpu_score))
The best way to do this is to use boolean check in your while loop :
check1 = True
check2 = True
while check1:
...
while check2:
if some_stop_condition_for_the_iner_loop:
check2 = False
if some_stop_condition_for_the_outer_loop:
check1 = False
check2 = False
In this way you can easily control your execution flow.
You can also use the keyword break that will allow you to stop the current loop you're in, but if there is neested loop, it will only break the deeper one, so boolean check are often the best solution.

I don't understand this rock paper scissors game

I found this code, and I'm having trouble understanding the lines 'user_hand = rps[int(user_input) - 1]' , 'com_hand = choice(rps)' , ' if rps_dict[user_hand]['strong'] == com_hand:' , 'print_result(**game_result)' , '
Why should I subtract 1 from user_input? Why put rps inside brackets next to choice? Why do you win 'if rps_dict[user_hand]['strong'] == com_hand ? Why if user_hand equal to com_hand? It doesnt make sense to me.. I know '**game_result' means it's a kwark, but I dont know why I need to declare it as a kwarg. I'm sorry if these questions seem stupid, but I'm frustrated.
from random import choice
rps = ('rock', 'paper', 'scissors')
rps_dict = {
'rock': {'strong': 'scissors', 'weak': 'paper'},
'paper': {'strong': 'rock', 'weak': 'scissors'},
'scissors': {'strong': 'paper', 'weak': 'rock'}
}
def print_result(user_score, com_score, win, lose, tie):
print('Result:', end=' ')
if user_score > com_score:
print('You win!')
elif user_score < com_score:
print('You lose...')
else:
print('Draw.')
print('--------------------')
# Print scores
print(f'Your score: {user_score}')
print(f'Computer score: {com_score}')
print('--------------------')
# Print statistics
print(f'Win: {win}')
print(f'Lose: {lose}')
print(f'Tie: {tie}')
def play(rounds):
game_result = {
'user_score': 0,
'com_score': 0,
'win': 0,
'lose': 0,
'tie': 0
}
while rounds > 0:
user_input = input(
'Enter your choice (1: Rock, 2: Paper, 3: Scissors, 0: Quit): ')
# Check whether the input is in the options
if user_input in ('1', '2', '3'):
rounds -= 1
user_hand = rps[int(user_input) - 1]
com_hand = choice(rps)
# user_hand is strong against com_hand
if rps_dict[user_hand]['strong'] == com_hand:
game_result['user_score'] += 1
game_result['win'] += 1
result = 'You win!'
# user_hand is weak against com_hand
elif rps_dict[user_hand]['weak'] == com_hand:
game_result['com_score'] += 1
game_result['lose'] += 1
result = 'You lose...'
# Tie
else:
game_result['tie'] += 1
result = 'Tie.'
print(
f'You -> {user_hand}. Computer -> {com_hand}. {result}')
elif user_input == '0':
break
else:
print('Invalid input!')
print()
print_result(**game_result)
if __name__ == "__main__":
print('Welcome to Rock-Paper-Scissors Game!')
try:
rounds = int(input('How many rounds you want to play? '))
play(rounds)
except ValueError:
print('Please input a valid number!')
This is an interesting question, and I'll do my best to discuss the lines that you said you have trouble with:
user_hand = rps[int(user_input) - 1]
The user_hand variable is used to store the choice the user inputs. user_input is the text the user directley entered. This will be saved as a string, so the code stransforms it into an integer with the int class. Next, it subtracts one from the user input (computers count from zero rather than 1). Then, it grabs the element from the list that has that index. For example, if I entered one, it would grab the list item at index 0 ("rock").
com_hand = choice(rps)
This line here is used to gather the computer's choice. As you can see from the first line, the choice function from the random module is imported directly. This allows you to use the function without specifying the module it came from. The choice function selects a random item from the specified list, which is the same rps list as before.
if rps_dict[user_hand]['strong'] == com_hand:
The if statement here gathers data from the rps_dict and compares it to the computer's hand. The rps_dict is a dictionary that contains data on which hand beats or loses to another. To translate the if statement into simpler english, it means if the hand the user's hand would beat (which can be found with rps_dict[user_hand]["strong"]), is the computer's hand, the user will win. In addition, to avoid confusion, the == operator check's for equality, and doesn't assign the variable to com_hand.
print_result(**game_result)
Here you said that you don't understand why the parameters are passed in this way. You don't really need to do it in this format, but the person who created the script decided to (possibly as it is simpler to read).
Thank you, and if you have any other questions, please comment and I'll do my best to answer them!

Python number guessing game not displaying feedback correctly. What's the problem?

So I tried to make a game where the computer chooses a random 4 digit number out of 10 given numbers. The computer then compares the guess of the user with the random chosen code, and will give feedback accordingly:
G = correct digit that is correctly placed
C = correct digit, but incorrectly placed
F = the digit isn't in the code chosen by the computer
However, the feedback doesn't always output correctly.
Fox example, when I guess 9090, the feedback I get is F C F, while the feedback should consist of 4 letters.... How can I fix this?
#chooses the random pincode that needs to be hacked
import random
pincode = [
'1231', '9997', '8829', '6765', '9114', '5673', '0103', '4370', '8301', '1022'
]
name = None
#Main code for the game
def main():
global code
global guess
#Chooses random pincode
code = random.choice(pincode)
#Sets guessestaken to 0
guessesTaken = 0
while guessesTaken < 10:
#Makes sure every turn, an extra guess is added
guessesTaken = guessesTaken + 1
#Asks for user input
print("This is turn " + str(guessesTaken) + ". Try a code!")
guess = input()
#Easteregg codes
e1 = "1955"
e2 = "1980"
#Checks if only numbers have been inputted
if guess.isdigit() == False:
print("You can only use numbers, remember?")
guessesTaken = guessesTaken - 1
continue
#Checks whether guess is 4 numbers long
if len(guess) != len(code):
print("The code is only 4 numbers long! Try again!")
guessesTaken = guessesTaken - 1
continue
#Checks the code
if guess == code:
#In case the user guesses the code in 1 turn
if (guessesTaken) == 1:
print("Well done, " + name + "! You've hacked the code in " +
str(guessesTaken) + " turn!")
#In cases the user guesses the code in more than 1 turn
else:
print("Well done, " + name + "! You've hacked the code in " +
str(guessesTaken) + " turns!")
return
#Sets empty list for the feedback on the user inputted code
feedback = []
nodouble = []
#Iterates from 0 to 4
for i in range(4):
#Compares the items in the list to eachother
if guess[i] == code[i]:
#A match means the letter G is added to feedback
feedback.append("G")
nodouble.append(guess[i])
#Checks if the guess number is contained in the code
elif guess[i] in code:
#Makes sure the position of the numbers isn't the same
if guess[i] != code[i]:
if guess[i] not in nodouble:
#The letter is added to feedback[] if there's a match
feedback.append("C")
nodouble.append(guess[i])
#If the statements above are false, this is executed
elif guess[i] not in code:
#No match at all means an F is added to feedback[]
feedback.append("F")
nodouble.append(guess[i])
#Easteregg
if guess != code and guess == e1 or guess == e2:
print("Yeah!")
guessesTaken = guessesTaken - 1
else:
print(*feedback, sep=' ')
main()
You can try the game here:
https://repl.it/#optimusrobertus/Hack-The-Pincode
EDIT 2:
Here, you can see an example of what I mean.
Here is what I came up with. Let me know if it works.
from random import randint
class PinCodeGame(object):
def __init__(self):
self._attempt = 10
self._code = ['1231', '9997', '8829', '6765', '9114', '5673', '0103', '4370', '8301',
'1022']
self._easterEggs = ['1955', '1980', '1807', '0609']
def introduction(self):
print("Hi there stranger! What do I call you? ")
player_name = input()
return player_name
def show_game_rules(self):
print("10 turns. 4 numbers. The goal? Hack the pincode.")
print(
"For every number in the pincode you've come up with, I'll tell you whether it is correct AND correctly placed (G), correct but placed incorrectly (C) or just plain wrong (F)."
)
def tutorial_needed(self):
# Asks for tutorial
print("Do you want a tutorial? (yes / no)")
tutorial = input().lower()
# While loop for giving the tutorial
while tutorial != "no" or tutorial != "yes":
# Gives tutorial
if tutorial == "yes":
return True
# Skips tutorial
elif tutorial == "no":
return False
# Checks if the correct input has been given
else:
print("Please answer with either yes or no.")
tutorial = input()
def generate_code(self):
return self._code[randint(0, len(self._code))]
def is_valid_guess(self, guess):
return len(guess) == 4 and guess.isdigit()
def play(self, name):
attempts = 0
code = self.generate_code()
digits = [code.count(str(i)) for i in range(10)]
while attempts < self._attempt:
attempts += 1
print("Attempt #", attempts)
guess = input()
hints = ['F'] * 4
count_digits = [i for i in digits]
if self.is_valid_guess(guess):
if guess == code or guess in self._easterEggs:
print("Well done, " + name + "! You've hacked the code in " +
str(attempts) + " turn!")
return True, code
else:
for i, digit in enumerate(guess):
index = int(digit)
if count_digits[index] > 0 and code[i] == digit:
count_digits[index] -= 1
hints[i] = 'G'
elif count_digits[index] > 0:
count_digits[index] -= 1
hints[i] = 'C'
print(*hints, sep=' ')
else:
print("Invalid input, guess should be 4 digits long.")
attempts -= 1
return False, code
def main():
# initialise game
game = PinCodeGame()
player_name = game.introduction()
print("Hi, " + player_name)
if game.tutorial_needed():
game.show_game_rules()
while True:
result, code = game.play(player_name)
if result:
print(
"Oof. You've beaten me.... Do you want to be play again (and be beaten this time)? (yes / no)")
else:
print("Hahahahaha! You've lost! The correct code was " + code +
". Do you want to try again, and win this time? (yes / no)")
play_again = input().lower()
if play_again == "no":
return
main()

Unable to record how many times my while loop runs- Python3

I am working on a number guessing game for python3 and the end goal of this is to show the user if they play more than one game that they'll receive an average number of guesses. However, I am unable to record how many times the game actually runs. Any help will do.
from random import randint
import sys
def guessinggame():
STOP = '='
a = '>'
b = '<'
guess_count = 0
lowest_number = 1
gamecount = 0
highest_number = 100
while True:
guess = (lowest_number+highest_number)//2
print("My guess is :", guess)
user_guess = input("Is your number greater than,less than, or equal to: ")
guess_count += 1
if user_guess == STOP:
break
if user_guess == a:
lowest_number = guess + 1
elif user_guess == b:
highest_number = guess - 1
print("Congrats on BEATING THE GAME! I did it in ", guess_count, "guesses")
PLAY_AGAIN = input("Would you like to play again? y or n: ")
yes = 'y'
gamecount = 0
no = 'n'
if PLAY_AGAIN == yes:
guessinggame()
gamecount = gamecount + 1
else:
gamecount += 1
print("thank you for playing!")
print("You played", gamecount , "games")
sys.exit(0)
return guess_count, gamecount
print('Hello! What is your name?')
myname = input()
print('Well', myname, ', I want you to think of number in your head and I will guess it.')
print("---------------------------------------------------------------------------------")
print("RULES: if the number is correct simply input '='")
print("---------------------------------------------------------------------------------")
print(" if YOUR number is GREATER then the output, input '>'")
print("---------------------------------------------------------------------------------")
print(" if YOUR number is LESS then the output, input '<'")
print("---------------------------------------------------------------------------------")
print(" ALRIGHT LETS PLAY")
print("---------------------------------------------------------------------------------")
guessinggame()
guess_count = guessinggame()
print(" it took me this many number of guesses: ", guess_count)
## each game the user plays is added one to it
## when the user wants to the game to stop they finish it and
## prints number of games they played as well as the average of guess it took
## it would need to take the number of games and add all the guesses together and divide it.
It is because you are either calling guessinggame() everytime user wants to play again or you are exiting the program. Also you are setting gamecount to 0 every time you call guessinggame(). You should move gamecount declaration and initialization out of your function. Also increment gamecount before you call guessinggame().

Keep getting "ValueError: invalid literal for int() with base 10: '' error, despite it working throughout the program

For my programming class, we have to make a trivia program that has an independent point value for each question. To do this, I added the point as a line in the text file and have this line in the code:
points = int(next_line(the_file))
I also have:
if answer == correct:
print("\nRight!")
score += points
in order to add the points to the total score.
This works all throughout the program, adding the points on after the player gets each question correct. However, at the end of the program, AFTER displaying the final score, the program says that there is a value error:
ValueError: invalid literal for int() with base 10:
I'm not sure what the error is, due to the fact that it works throughout the entire program, all the way up until the end.
Any help would be greatly appreciated, thank you.
Here is the entire code:
import sys
choice = None
while choice != "0":
choice = input("""
WELCOME TO THE TRIVIA CHALLENGE. PLEASE SELECT AN EPISODE
0: Exit Game
1: Trivia 1
2: Trivia 2
Choice: """)
if choice == "0":
print("You have chose to exit the program. Your loss.")
sys.exit()
elif choice == "1":
fileChoice = "trivia1.txt"
elif choice == "2":
fileChoice = "trivia2.txt"
else:
print("You have entered an invalid option. You are being kicked off.")
sys.exit()
def open_file(file_name, mode):
"""Open a file."""
try:
the_file = open(file_name, mode)
except IOError as e:
print("Unable to open the file", file_name, "Ending program.\n", e)
input("\n\nPress the enter key to exit.")
sys.exit()
else:
return the_file
def next_line(the_file):
"""Return next line from the trivia file, formatted."""
line = the_file.readline()
line = line.replace("/", "\n")
return line
def next_block(the_file):
"""Return the next block of data from the trivia file."""
category = next_line(the_file)
question = next_line(the_file)
answers = []
for i in range(4):
answers.append(next_line(the_file))
correct = next_line(the_file)
if correct:
correct = correct[0]
explanation = next_line(the_file)
points = int(next_line(the_file))
return category, question, answers, correct, explanation, points
def welcome(title):
"""Welcome the player and get his/her name."""
print("\t\tWelcome to Trivia Challenge!\n")
print("\t\t", title, "\n")
def main():
trivia_file = open_file(fileChoice, "r")
title = next_line(trivia_file)
welcome(title)
score = 0
# get first block
category, question, answers, correct, explanation, points = next_block(trivia_file)
while category:
# ask a question
print(category)
print(question)
for i in range(4):
print("\t", i + 1, "-", answers[i])
# get answer
answer = input("What's your answer?: ")
# check answer
if answer == correct:
print("\nRight!")
score += points
else:
print("\nWrong.")
print(explanation)
print("Score:", score, "\n\n")
# get next block
category, question, answers, correct, explanation, points = next_block(trivia_file)
trivia_file.close()
print("That was the last question!")
print("Your final score is", score)
main()
input("\n\nPress the enter key to exit.")
Another problem I have is with the way I did the sys.exit(), since it also doesn't work.
You'll get this error when you have a blank line. If you look at the error message, its telling you what the problem is (although it may not be obvious):
ValueError: invalid literal for int() with base 10:
The blank after 10: is the clue, its actually a blank line in the file.
So, just check if there is a blank line:
points_line = next_line(the_file).strip()
if points_line:
points = int(points_line)
else:
print('Got a blank line when expecting points!')

Resources