so i have been working on a input based dungeon game in python that is fairly rudimentary. I wanted to put a dice roll condition in the game and decide if a player will die or live on a path. However my if statement will not properly respond to the roll in the number generator i have in the program, it will print the number and then carry on whether or not the condition was met. How can i fix this, and why is this happening?
if direction == 1:
import random
from random import *
num = 6
def d6(num):
rolls = []
for x in range(num):
rolls.append(randint(1,6))
return rolls
rolls = d6(1)
print rolls
if rolls is 3:
print "you fall in a hole!\n"
print ' OH DEAR YOU ARE DEAD!'
raise SystemExit
elif rolls is not 3:
print "you are back at the start which way will you go?\n"
path3 =float(input("forward, or right?"))
is and is not are reserved for special comparisons in python. You need == and !=. Also you can change it to a simple if/else instead of if/elif with no else. Also, it looks like your d6 function returns a list instead of a single number. Try adjusting that to return a single number instead:
from random import randint
def d6():
return randint(1,6)
rolls = d6()
if rolls == 3:
print "you fall in a hole!\n"
print ' OH DEAR YOU ARE DEAD!'
raise SystemExit
else:
print "you are back at the start which way will you go?\n"
Related
Hello fellow programmers! I am a beginner to python and a couple months ago, I decided to start my own little project to help my understanding of the whole development process in Python. I briefly know all the basic syntax but I was wondering how I could make something inside a function call the end of the while loop.
I am creating a simple terminal number guessing game, and it works by the player having several tries of guessing a number between 1 and 10 (I currently made it to be just 1 to test some things in the code).
If a player gets the number correct, the level should end and the player will then progress to the next level of the game. I tried to make a variable and make a true false statement but I can't manipulate variables in function inside of a while loop.
I am wondering how I can make it so that the game just ends when the player gets the correct number, I will include my code down here so you guys will have more context:
import random
import numpy
import time
def get_name(time):
name = input("Before we start, what is your name? ")
time.sleep(2)
print("You said your name was: " + name)
# The Variable 'tries' is the indication of how many tries you have left
tries = 1
while tries < 6:
def try_again(get_number, random, time):
# This is to ask the player to try again
answer = (input(" Do you want to try again?"))
time.sleep(2)
if answer == "yes":
print("Alright!, well I am going to guess that you want to play again")
time.sleep(1)
print("You have used up: " + str(tries) + " Of your tries. Remember, when you use 5 tries without getting the correct number, the game ends")
else:
print("Thank you for playing the game, I hope you have better luck next time")
def find_rand_num(get_number, random, time):
num_list = [1,1]
number = random.choice(num_list)
# Asks the player for the number
ques = (input("guess your number, since this is the first level you need to choose a number between 1 and 10 "))
print(ques)
if ques == str(number):
time.sleep(2)
print("Congratulations! You got the number correct!")
try_again(get_number, random, time)
elif input != number:
time.sleep(2)
print("Oops, you got the number wrong")
try_again(get_number, random, time)
def get_number(random, try_again, find_rand_num, time):
# This chooses the number that the player will have to guess
time.sleep(3)
print("The computer is choosing a random number between 1 and 10... beep beep boop")
time.sleep(2)
find_rand_num(get_number, random, time)
if tries < 2:
get_name(time)
tries += 1
get_number(random, try_again, find_rand_num, time)
else:
tries += 1
get_number(random, try_again, find_rand_num, time)
if tries > 5:
break
I apologize for some of the formatting in the code, I tried my best to look as accurate as it is in my IDE. My dad would usually help me with those types of questions but it appears I know more python than my dad at this point since he works with front end web development. So, back to my original question, how do I make so that if this statement:
if ques == str(number):
time.sleep(2)
print("Congratulations! You got the number correct!")
try_again(get_number, random, time)
is true, the while loop ends? Also, how does my code look? I put some time into making it look neat and I am interested from an expert's point of view. I once read that in programming, less is more, so I am trying to accomplish more with less with my code.
Thank you for taking the time to read this, and I would be very grateful if some of you have any solutions to my problem. Have a great day!
There were too many bugs in your code. First of all, you never used the parameters you passed in your functions, so I don't see a reason for them to stay there. Then you need to return something out of your functions to use them for breaking conditions (for example True/False). Lastly, I guess calling functions separately is much more convenient in your case since you need to do some checking before proceeding (Not inside each other). So, this is the code I ended up with:
import random
import time
def get_name():
name = input("Before we start, what is your name? ")
time.sleep(2)
print("You said your name was: " + name)
def try_again():
answer = (input("Do you want to try again? "))
time.sleep(2)
# Added return True/False to check whether user wants to play again or not
if answer == "yes":
print("Alright!, well I am going to guess that you want to play again")
time.sleep(1)
print("You have used up: " + str(tries) + " Of your tries. Remember, when you use 5 tries without getting the correct number, the game ends")
return True
else:
print("Thank you for playing the game, I hope you have better luck next time")
return False
# Joined get_number and find_random_number since get_number was doing nothing than calling find_rand_num
def find_rand_num():
time.sleep(3)
print("The computer is choosing a random number between 1 and 10... beep beep boop")
time.sleep(2)
num_list = [1,1]
number = random.choice(num_list)
ques = (input("guess your number, since this is the first level you need to choose a number between 1 and 10 "))
print(ques)
if ques == str(number):
time.sleep(2)
print("Congratulations! You got the number correct!")
# Added return to check if correct answer is found or not
return "Found"
elif input != number:
time.sleep(2)
print("Oops, you got the number wrong")
tries = 1
while tries < 6:
if tries < 2:
get_name()
res = find_rand_num()
if res == "Found":
break
checker = try_again()
if checker is False:
break
# Removed redundant if/break since while will do it itself
tries += 1
I have a question:
When the program runs, it will randomly choose a number between 1 and 6. (Or whatever other integer you prefer — the number of sides on the die is up to you.) The program will print what that number is. It should then ask you if you’d like to roll again. For this project, you’ll need to set the min and max number that your dice can produce. For the average die, that means a minimum of 1 and a maximum of 6. You’ll also want a function that randomly grabs a number within that range and prints it.
This is what I have done so far:
import random
x = random.randint(1,6)
print("You roll a die ", x)
new_try = input("\n\n Do you want to roll a die again?")
if str(new_try) == 'yes':
print("You roll a die ", x)
else:
print("Cool game!")
I am still getting same numbers :(
You aren't changing x the second time, and merely printing it out again, giving the same result. Here is the code for a fixed version:
import random
x = random.randint(1, 6)
print("You roll a die", x)
new_try = input("\n\n Do you want to roll again? ")
if new_try == 'yes':
x = random.randint(1, 6)
print("You roll a die", x)
else:
print("Cool game!")
If you want to use a function for it, you can do it over multiple times:
import random
def roll_dice():
x = random.randint(1, 6)
print("Dice was rolled: " + str(x))
try_again = input("Do you want to try again? ")
if try_again == 'yes':
roll_dice()
roll_dice()
I reckon what you can do is set a different seed each time you run a new try.
x is not the diceroll, that is random.randint(1,6). So after x = random.randint(1,6), x stores the result of a single diceroll which happened earlier, and available to provide that single result any time in the future. So x stores a number, not the fact that it should be generated randomly.
If you want a function for rolling a dice, that would be def for first attempts:
def diceroll():
return random.randint(1,6)
having this function, any subsequent print(diceroll()) (note that it is a function call, diceroll()) would print the result of a different roll (and results could be equal only by coincidence). Or, you could again store the result of a single diceroll as x=diceroll(), so it could be re-used multiple times in the future (let's say you want to compare it to the user's guess and also print it)
Side note: technically you can store functions in variables too, x=diceroll would store the function, so x would not be a number, but the act of rolling the dice, and would have to be called as a function, like print(x()).
If you want to produce different numbers at different times, you have to use a seed value. Here is an example to explain:
import random
random.seed( 3 )
print "Random number with seed 3 :", random.random() #will generate a random number
#if you want to use the same random number once again in your program
random.seed( 3 )
random.random()
I will not make the program for you. I have explained you the concept. Now just implement it.
I'm trying to build a standalone application like the dice roller on Roll20.net, starting off simple and as I get better I can add more features, including a GUI, but returning to this project after giving up months ago, I still cannot get even the most basic form to even output.
import random
from random import randint
d20 = randint(1,20)
str1 = "You rolled a "
str2 = "Congrats Critical Hit"
str3 = "Uh Oh, Critical Fail"
def roll(d20):
roll(d20)
print (str1 + roll(d20))
if (d20 == 1):
print (str3)
elif (d20 == 20):
print (str3)
else:
print ("")
I either get a completely blank output, implying that the program technically runs, or I'll get a "function roll at 0x02A3B078" or I'll get a response that something isn't defined.
How to solve this?
You're defining a function, but not calling it? Add this line at the bottom of your program:
roll(d20)
Don't call your function inside itself. This leads to infinite recursion.
What you need is something like this:
...
def roll(d20):
print(str1, d20)
if d20 == 1:
print(str3)
elif d20 == 20:
print(str3)
roll(d20)
Do you want to make your program interactive? You could initialise a while loop and repeat while as long as the user is interested in playing.
while True:
d20 = randint(1, 20)
roll(d20)
if input('Keep playing? ') not in {'y', 'Y'}:
break
Try that
import random
from random import randint
str1 = "You rolled a "
str2 = "Congrats Critical Hit"
str3 = "Uh Oh, Critical Fail"
def roll(d20):
print (str1 + str(d20))
if (d20 == 1):
print (str3)
elif (d20 == 20):
print (str3)
num_of_rolls = 10
while num_of_rolls:
d20 = randint(1,20)
roll(d20)
num_of_rolls -= 1
Some things that you may take into account in the future. You didn't call the function. It sometimes prints no output, because it has 18:20 chance to print(""). You shouldn't start with (1,20) range. Test (1,2) and put print statement everywhere you can. That's the only way to be sure what's happening inside your function. You don't need to print("") if you don't need it.
I have made a text-based RPG that uses dice rolling for the combat system. If you get a 1, your attack is forfeited. You can keep rolling until you get a one, or type 'attack'. I made a dice roller, and I just want to know, how to make it detect if the roll is 2 through 6. Here is the code:
print ("Type roll to roll the dice")
rollKeeper = ("1")
while rollKeeper == ("1"):
rollOn = input ( )
if rollOn == ("roll"):
import random
def rollDice():
damage = random.randint(1,6)
damage = random.randint (1,6)
print (damage)
So I want to get it do detect numbers 2 through 6, and that's it. I know about
if damage == ("1"):
but that is already part of my game. I just need to be able to detect if it is any of the others (up to 6).
Roll it into a function, since it's reusable.
import random
def roll_die():
return random.randint(1,6)
then just test.
result = roll_die()
if result == 1:
# forfeit attack however you're doing that
else: # roll between 2-6
# do whatever your game logic has you doing.
Try adding:
if 2 <= damage <= 6:
#insert code here
I have created a program where the user can select a certain sided dice then it rolls and outputs the number generated, it then asks if the user wants to roll again and by using a while loop. i have wrote the program and for some reason it keeps on repeating the input dice side number prompt and i don't know why, here is the code
import random
roll_agn='yes'
while roll_agn=='yes':
dice=input ('Please choose a 4, 6 or 12 sided dice: ')
if dice ==4:
print(random.randint(1,4))
elif dice ==6:
print(random.randint(1,6))
elif dice ==12:
print(random.randint(1,12))
else:
roll_agn=input('that is not 4, 6 or 12, would you like to choose again, please answer yes or no')
if roll_agn !='yes':
print ('ok thanks for playing')
I suspect it is something to do with the while loop or the indentation, but I have been fiddling with it for like 3o mins and i cant get it to work properly, so if someone could help me out here it would be appreciated, Thanks !
The indentation on else: roll_agn=input is such that it only runs after you exit the while loop - but the while loop can never end until you run the else clause, therefore infinite loop.
Here is a cleaned-up, better-structured version:
# assumes Python 3.x
from random import randint
def get_int(prompt):
while True:
try:
return int(input(prompt)) # if Python 2.x use raw_input instead of input
except ValueError:
# not an int
pass
def get_yn(prompt):
while True:
value = input(prompt).strip().lower() # if Python 2.x use raw_input instead of input
if value in {'y', 'yes'}:
return True
elif value in {'n', 'no'}:
return False
def roll(sides):
return randint(1, sides)
def main():
while True:
sides = get_int("Number of sides on die (4, 6, or 12)? ")
if sides in {4, 6, 12}:
print("You rolled a {}".format(roll(sides)))
else:
print("U no reed gud?")
if not get_yn("Play again (y/n)? "):
print("Thanks for playing!")
break
if __name__=="__main__":
main()
It looks like you have indentation problems with the if statements. Try lining up elif with if.
if dice ==4:
print(random.randint(1,4))
elif dice ==6:
print(random.randint(1,6))
elif dice ==12:
print(random.randint(1,12))