Python 3.4 Dice Rolling Simulator Code Error - python

So I have my code here for a dice rolling simulator game that I am creating using PyDev in Eclipse Neon Python 3.4. Where you guess a number and a number from 1-6 will randomly generate and if you get the number right, you move on, etc.
guess1 = input("Enter your first guess as to which side the dice will roll on (1-6): ")
import random
dice_side = ['1','2','3','4','5','6']
game = print(random.choice(dice_side))
if guess1 == game:
print("Congrats that's the correct guess!")
else:
print("That's the wrong guess!")
I tested out the code and everytime I put in a number, the console always print "That's the wrong guess!". Even when the number I guess matched the generated number. I can't quite figure out what's wrong with this. I was thinking maybe I should use a while loop instead. However, I wanted to know if I can do it this way and what's wrong with this particular code. I am new to Python so any help is appreciated. Thanks in advance!

print() returns None. If you print game after that line you will see it's value. To fix:
game = random.choice(dice_side)

In order to understand why your game isn't working you should try to understand first what's wrong with this line game = print(random.choice(dice_side)). Here's a modified version of your game which will give you some clues, try to run it and understand it, then just review your script:
import random
dice_side = ['1', '2', '3', '4', '5', '6']
game = random.choice(dice_side)
print("Dice has been rolled... :D {0}".format(game))
guess = -1
number_attempts = 0
while True:
guess = raw_input("Which side the dice has rolled on (1-6): ")
number_attempts += 1
if guess == game:
print("Congrats that's the correct guess! You've tried {0} times".format(
number_attempts))
break
print("That's the wrong guess!")
One advice, once you've discovered why isn't working, just try to add more and more new features till your game becomes really addictive and interesting... but the most important, just have fun :)

Related

Betting system won't seem to process the user input correctly, how can this be improved?

I'm trying to code a game of craps in which the player has a virtual 'wallet' to gamble with. I've gotten to the user input part and it's not going as planned.
Here is what I have so far:
import random
import sys
money = "500"
# start the game
a = input("Hello travler, to start the game, please type 'yes'. If you are not ready to begin your journey, type 'no' ")
if a.lower() == "no":
sys.exit()
else:
print("Welcome")
print("Hold on... I'm missing something,")
name = input("What is your name, traveler?: ")
print("Welcome,", (name))
# those who need instructions can ask for it,
# others can start the game directly.
a = input("Welcome to a game that'll determine the rest of your life. Do you need instructions? (yes) or (no)? \n")
if a.lower() == "yes":
print('''1. the player will roll two six sided dice. the sum of the two dice is the player's number for the round.
2. rolling a 7 or an 11 as your first roll win you the game, but be weary, a 2, 3, or 12 automatically causes the player to lose. no more game for you. If a 4, 5, 6, 8, 9, or 10 are rolled on this first roll, that number becomes the 'point.'
3. the fated player continues to roll the two dice again until one of two things occur: either they roll the 'point' again, causing them to win the game; or they roll a 7, causing them to be doomed to the eternals.''')
elif a.lower() == "no":
print("may luck be with you on this fateful day,", name)
print("You will start off with 500 pieces of luck, if you leave this game with over 1000 pieces of luck, you will be fated for sucsess. On the other hand, should you drop below 0 peices of luck, you will find yourself in debt to the universe, a misfortune that few recover from.")
print("You currently have", money, "luck to spare")
# betting time
while True:
bet = input("How much luck do you wish to bet? ")
if bet.isdigit() is True:
if money > bet:
print("Bet accepted")
if bet.isdigit() is True:
if bet > money:
print("How unfortunate, you do not have the luck to make this bet.")
elif bet.isdigit() is False:
print ("Sorry, luck can only be quantitated in number values.")
# if you bet higher than your money, it wont allow you to bet within after that.
The code below the line # betting time is where I am hitting my head over.
I need the code to do the following:
check if the user input is in fact a number, if it's not a number, make them enter a new input
if the user input is a number, determine if it is within the amount they have in their 'wallet' (if not, make them input a new number)
if the number is within the amount in their 'wallet' and is a digit, give the user the option to "roll dice" triggering the game to start.
If they win, they need to be granted double what they bet, if they lose, they need to lose the amount they bet. The wallet will need to update after each play, giving the user the option to play again with their updated wallet (so if they bet 50 and win, their new balance will be 550. The process continues until the user either reaches 1000 or 0, causing the game to end either way.)
For checking if the user's bet is a number use the .isnumeric() function on your bet like:
bet.isnumeric()
to do the second thing you needed help with you could do:
if bet < wallet: blah blah blah elif
bet > wallet: print("You do not enough money")
around like that it with actual good syntax
to do dice you could use the random.randint() function like this:
random.randint(1,6)
I hope that helps!

How do I randomly select a variable from a list, and then re assign it to another variable?

I want to make a mastermind game im sure you all know what it is, some kind of GCSE style python number guessing game. it should ask you for a number, select a number and then tell you if you guessed any correctly but im having trouble assigning that randomly selected number to "x" perhaps.
I am pretty new to python as you can see.
numberseasy = ['1244', '1354', '2355', '2366', '2609', '0010', '1234', '8873', '7775', '2512', '0293', '9463', '9901',
'6272', '0629']
numbershard = ['25356', '86025', '67390', '96873', '01255', '77654', '96756', '88742', '09564', '12345', '19455',
'35656', '20967', '32570']
print("welcome to mastermind!")
gamemode = input("please select gamemode: easy, hard")
if gamemode == "easy":
(random.choice(numberseasy)) = x
print("easy was selected")
print("im thinking of a number, try to guess a one digit integer each time to work out the number im thinking of i")
print("will tell you if you have one correct")
first = input("please enter a number")
Variable assignments go from left to right. You just need x = random.choice(numberseasy).
You should be using a .lower() to the input string for text. This would allow the text to be entered in any capital letters.
As mentioned with blorgon's answer, you must have the variables on the left-hand side and the input on the right. In python, it is right to left such as cake = True or food = "cake".
numberseasy = ['1244', '1354', '2355', '2366', '2609', '0010', '1234', '8873', '7775', '2512', '0293', '9463', '9901',
'6272', '0629']
numbershard = ['25356', '86025', '67390', '96873', '01255', '77654', '96756', '88742', '09564', '12345', '19455',
'35656', '20967', '32570']
print("welcome to mastermind!")
gamemode = input("please select gamemode: easy, hard")
if gamemode.lower() == "easy":
x = random.choice(numberseasy)
print("easy was selected")
print("im thinking of a number, try to guess a one digit integer each time to work out the number im thinking of i")
print("will tell you if you have one correct")
first = input("please enter a number")

Program Win/Loss statistics in Number Guessing Game for Python

I've written a program for a Number guessing game in Python which i have almost completed. However, there is one small problem i can't figure out. After the game finishes I want the statistics to be printed out for each player to a .txt with the following information:
Username | Win or Loss | Number of Guesses.
I can't figure out how to generate the Win/Loss statistic in the following line for each player:
f.write(str(playerName)+ '|' +str(numberOfGuesses)+'\n').
If anyone could please provide some advice it would be greatly appreciated. I have displayed part of the code as follows:
won = False
while numberOfGuesses < maxGuesses:
guess = int(input('What is your guess?: '))
numberOfGuesses += 1
if guess < number:
print('Too low')
if guess > number:
print('Too high')
if guess == number:
won = True
break
print('You have', str(maxGuesses - numberOfGuesses) + ' guesses remaining\n')
if won:
print('Congratulations!!! You guessed the number in ' + str(numberOfGuesses) + ' tries!')
else:
print('Game Over!!! You did not guess the correct number, the number was ' + str(number))
f = open('Statistics.txt', 'a')
f.write(str(playerName)+ '|' +str(numberOfGuesses)+'\n')
f.close()
f = open('Statistics.txt', 'r')
print(f.read())
It's pretty, simple.
To clarify, if won == True, you want to write "Won" to the line and if won == False, you want to write "Loss" to the line right?
win_or_loss = 'Loss'
if won:
win_or_loss = 'Win'
Then you just use this variable when you write to the file
f.write(str(playerName)+ '|' + win_or_loss + '|' +str(numberOfGuesses)+'\n')
Also, you don't need to wrap playerName in str() since it is already a string.
Since you have playerName in the mix, I assume you're trying to keep score stats per player. In that case, I suggest you create a dictionary keyed on player names. The values can be lists of [numCorrect, totalGuesses] per player. You would update numCorrect and totalGuesses during each player's turn as appropriate. In the end, you would walk through that dictionary and process the results.
Here's the logic to implement so you can get the Win/Loss stats.
For each game, you will have the following
Player Name, Win or Loss flag, Total Guesses.
Read statistics file to see if player exists. If player exists, then retrieve the following information:
Player Name, Win Count, Loss Count, Win-Loss Stats, Lowest Number of Guesses
* Win Count will be # of times player has won in the past
* Loss Count will be # of times player has lost in the past
* Win-Loss stat will be Win / (Win + Loss). If you want % then x by 100
* Lowest Number of Guesses for the first entry will be numberOfGuesses
For all subsequent entries, you need to update the record in the file based on new calculations as shown below.
If current game is win, win_count += 1
If current game is loss, loss_count += 1
win_loss stat will remain win_count / (win_count + loss_count)
if numberOfGuesses < lowest_number_of_guesses: lowest_number_of_guesses = numberOfGuesses.
#you can modify this with walrus option if you use 3.8+
Write back this stats to the file. This will keep track of the status for the player and you can use this to keep the stats updated every time the player plays
Since you are going to have a lot of I/O with the above logic, you may want to read the file into memory and calculate this in memory, then write to file as part of normal program exit. One challenge is that the data will be lost if the program abruptly crashes.
Hope this helps you implement a good logic.
I wanted to write this in comments but the max chars exceeded. So put this in the answer comments. I would prefer you write the code as it will help you with the implementation of the logic.

I dont know how to do error handling with incorrect inputs

im trying to make it so in a part of my code where a user enters their name that they cant enter a number, without the program crashing. I am also trying to do the same with some other parts of my code aswell
I havent tried anything as of now
enter code here
myName = str(input('Hello! What is your name?')) #Asks the user to input their name
myName = str(myName.capitalize()) #Capitalises the first letter of their name if not already
level = int(input('Please select a level between 1 and 3. 1 being the easiest and 3 being the hardest'))
guessNumber()
print('')
print('It is recommended to pick a harder level if you chose to progress')
print('')
again = int(input("Would you like to play again? Input 1 for yes or 2 for no?" ))
# Is asking the user if they want to play again.
if again == 1:
guessNumber()
if again == 2:
print('Thanks for playing Guessing Game :)')
sys.exit(0)
You should post the code of guessNumber().
kinda difficult to understand question anyway I'd do this.
To accept a string and if the value entered is int it'd give the message but you can't differentiate as int cant be str but str can be a number.
try:
myName=str(input("Enter name\n"))
except ValueError as okok:
print("Please Enter proper value")
else:
printvalue=f"{myName}"
print(printvalue)

Python not responding in loop

Here is my code:
from random import randint
doorNum = randint(1, 3)
doorInp = input("Please Enter A Door Number Between 1 and 3: ")
x = 1
while (x == 1) :
if(doorNum == doorInp) :
print("You opened the wrong door and died.")
exit()
now, that works fine, if I happen to get the unlucky number.
else :
print("You entered a room.")
doorNum = randint(1, 3)
This is the part where it stops responding entirely. I am running it in a bash interactive shell (Terminal, on osx). It just ends up blank.
I am new to programming in Python, I spent most of my time as a web developer.
UPDATE:
Thanks #rawing, I can not yet upvote (newbie), so will put it here.
If you are using python3, then input returns a string and comparing a string to an int is always false, thus your exit() function can never run.
Your doorInp variable is a string type, which is causing the issue because you are comparing it to an integer in the if statement. You can easily check by adding something like print(type(doorInp)) after your input line.
To fix it, just enclose the input statement inside int() like:doorInp = int(input("...."))
In python3, the input function returns a string. You're comparing this string value to a random int value. This will always evaluate to False. Since you only ask for user input once, before the loop, the user never gets a chance to choose a new number and the loop keeps comparing a random number to a string forever.
I'm not sure what exactly your code is supposed to do, but you probably wanted to do something like this:
from random import randint
while True:
doorNum = randint(1, 3)
doorInp = int(input("Please Enter A Door Number Between 1 and 3: "))
if(doorNum == doorInp) :
print("You opened the wrong door and died.")
break
print("You entered a room.")
See also: Asking the user for input until they give a valid response

Categories