Fortune cookie game in Python - python

This is I'm sure a fairly rudimentary questions involving Python, but I've only recently started using the program. Here is the challenge:
"Write a program that simulates a fortune cookie. The program should display one of five unique fortunes, at random, each time it's run."
My approach was to assign five distinct variables their own individual fortunes:
fortune_1 = str("Good things come to those who wait.")
fortune_2 = str("Patience is a virtue.")
fortune_3 = str("The early bird gets the worm.")
fortune_4 = str("A wise man once said, everything in its own time and place.")
fortune_5 = str("Fortune cookies rarely share fortunes.")
What I am not clear on is how to generate the fortunes at random. Is there a way to utilize the random. module to pick one of the five predetermined fortunes uniquely each time? For example, could I set those five fortunes as numbers and then say something like:
user_fortune = random.randfortune(1,5)
? I hope this makes sense. As I am new to Python and posting in this forum it may take me some time to communicate more clearly.
Thanks!

My first instinct was to tell you to put your fortunes into a sequence of some kind (e.g., list, tuple). Then, you just need to pick a random element. I did the following at the Python prompt:
>>> import random
>>> help(random)
Help on module random:
NAME
random - Random variable generators.
FILE
/usr/lib/python2.7/random.py
MODULE DOCS
http://docs.python.org/library/random
DESCRIPTION
integers
--------
uniform within range
sequences
---------
**pick random element**
pick random sample
generate random permutation
distributions on the real line:
Aha! "pick random element" sounds good. So, I keep scrolling:
| **choice**(self, seq)
| Choose a random element from a non-empty sequence.
|
Aha again! I suppose I should have just known this, but it's good to know how to look this stuff up when you need it.
Possible solution (Python 2.7):
import random
fortunes = ["Good things come to those who wait.",
"Patience is a virtue.",
"The early bird gets the worm.",
"A wise man once said, everything in its own time and place.",
"Fortune cookies rarely share fortunes."]
print random.choice(fortunes)

You can add the fortunes to a list and select a random item from the list using choice:
import random
fortunes = [fortune_1, fortune_2, fortune_3, fortune_4, fortune_5]
print random.choice(fortunes)

Thank you very much!
I also noticed that I could try the following:
import random
fortune = random.randint(1,5)
if fortune == 1:
print("Good things come to those who wait.")
elif fortune == 2:
print("Patience is a virtue.")
elif fortune == 3:
print("The early bird gets the worm.")
elif fortune == 4:
print("A wise man once said, everything in its own time and place.")
elif fortune == 5:
print("Fortune cookies rarely share fortunes.")

imort random
fortune_cookie = random.choice([""Good things come to those who wait.",
"Patience is a virtue.",
"The early bird gets the worm.",
"A wise man once said, everything in its own time and place.",
"Fortune cookies rarely share fortunes."])
print(fortune_cookie)

Related

How to add random action to Python?

I've been coding an adventure game in Python myself and through YouTube and stuff I found online, but I want to add a part where You gotta get on this boat but a ticket costs $10 (Which you have an option to get earlier).
But say you didn't get the 10 earlier, you have another option to run past the guy who's asking you to pay for it (Which I guess you Could also do even if you have the 10 and just save money). But if you have $10, you just go through, and if you don't, you just restart and it runs sys.exit()
As of writing, the code looks like this:
print("A man offers you a trip to the eastern side of the village via boat")
print(
"as a bridge has not been constructed yet, but it will cost $10, do you give him it ($10 Required) or try run past him(Free)")
check_inv = input()
if "$10" not in inv:
print("He caught you making a run for it! restart game")
sys.exit()
else:
print("Let's see if you have enough...")
print(inv)
print("You have enough and cross the river")
removeFrominventory("$10")
I know how to write a random number generator as it was another beginner project I was advised to work on, but I want to to be that if you type 'Run' you will have a 50/50 chance to be able to outrun him.
Assuming you want it to be like the RNG in pokemon or want to create a coin flip event, you could either create a list of list = [0,1] and use random.choice(list) or you could use randrange() to get a number b/w 0 and 100. Let's say the chances to outrun are x%. If the value obtained from randrange is less than x, you outrun else you don't. You can create a function like:
def RNG(probability):
Generate Random num b/w 0 and 100
if num<probability:
return True
else:
return False
I would prefer the RNG function. Though it is time and memory consuming, it can be reused in the code again and again.

How could i know the random number generated in python?

Here is my code. I am just starting to learn Python.
I am trying to generate a random number and guess it. If the answer is 7, then my program will print "lucky". If not, then "unlucky". I try to run my simple code many times. Every time I get "unlucky". Is there anybody who knows whether the problem is in my algorithm or somewhere else. BTW, I really want to know how could I know specifically know what is the number randomly generated in python? I just wonder if the same number, that is being generated every time, is the same one or not.
from random import randint
z = input("What's the max number you want me to guess?")
choice = f"randint(1,{z})"
if choice == 7:
print("lucky")
else:
print("unlucky")
The reason you're getting unlucky every time has nothing to do with randomness.
Try running your code in the debugger, or adding a print(choice), to what what you're getting.
If you enter, say, 10, then choice is the string "randint(1,'10')". That string is never going to be equal to the number 7.
To make this work, you need to change two things:
Actually call randint, instead of making a string that looks like the source code to call it.
Call it on a number, like 10, not a string, like '10'.
So:
choice = randint(1, int(z))
Once you fix this, the random numbers will be random. Technically, they're created by a PRNG (pseudo random number generator), a fancy algorithm that takes a bunch of state information and spits out a sequence of numbers that look random, but are actually predictable from that state. But, as explained under seed, by default, Python seeds that generator with os.urrandom (which, on most platforms, is another PRNG, but is itself seeded by whatever actual random data is available).
If you want the sequence to be repeatable, for testing, you can call the seed function manually. For example, this program:
from random import randint, seed
seed(42)
z = input("What's the max number you want me to guess?")
choice = randint(1, int(z))
print(choice)
… will give you 2 every time you ask for a random number between 1 and 10.
If you want to check whether the same number is being guessed by random, just use print, to check it. Here:
from random import *
z = int(input("What's the max number you want me to guess?"))
choice = randint(1,z)
print("The number that I guessed:",choice)
if choice == z:
print("I gussed it! I got lucky.")
else:
print("I couldn't guess it, I got unlucky.")

How to use the output of randint in an if statement (Python)

I'm learning Python (3.6.3) and making a silly (and very linear) chatbot to get started. At one point the chatbot asks you to guess its age, I used randint to generate a number between 1-1000 and want to use the outputted random integer in an if statement (so the chat bot is either happy or upset by your answer, depending on whether you thought it was older than it really is).
The user's input is a var called guess and I assumed (as I cannot find a similar example online) that I could just reference guess and the randint in an if statement to print the desired output, but I get an error advising radint is not defined when I run the prog -
print('guess how old I am')
guess = input()
import random
for x in range(1):
time.sleep(0.4)
print ('nope, I\'m ' + (str(random.randint(1,1000))) + ' actually')
time.sleep(0.88)
if randint <= guess
print('(so rude...)')
else:
print('aw thanks')
Apologies if my StackExchange syntax is broken too, any help appreciated, thanks
- you need to define your randint variable
- import time
- fix: you left out colon after "if randint <= guess"
- you need to make your input guess an integer in order to perform comparison
print('guess how old I am')
guess = int(input())
import random
import time
randint = random.randint(1,1000)
for x in range(1):
time.sleep(0.4)
print ('nope, I\'m %s actually' % randint)
time.sleep(0.88)
if randint <= guess:
print('(so rude...)')
else:
print('aw thanks')
here is a corrected version of your chatbot:
import time
import random
guess = input('guess how old I am: ')
random_guess = random.randint(1,1000)
time.sleep(0.4)
print ('nope, I\'m {} actually'.format(random_guess))
time.sleep(0.88)
if random_guess <= guess:
print('(so rude...)')
else:
print('aw thanks')
I'm just going to note down the things that were wrong and some good practices so that you can follow it since you are learning python (I just learnt it as well):
In the if statement you were comparing randint <= guess which is not possible because randint is not saved as variable anywhere. The 1st time you used random.randint(1, 1000) it was statically added only to be used in the print statement. So what I did here is save the random.randint(1,1000) (as you can see randint is a method inside the random module of python) into a variable called random_guess for comparison. It returns a random integer as stated in random.randint.
Coming to the print statement since your random_guess will be of
type int, using formatted string will be a nice and pretty option.
Always use import statement at the top of the file so that it'll be
a one stop place for altering imports.
Take a look at this input() method as well, I have passed in a
string which automatically prints out the string passed instead of a
separate print statement
I also removed the for loop since it was looping once anyways (I
know you need to call it many times, anywho..)
Edit: Oh, and you missed a colon in the if statement!
I hope this cleared your doubts.

Generating Random Numbers for a Combat Simulator

I am attempting to create a very basic Combat Simulator. Here is my code:
import random
#from random import * I had, at one time, created a D20 generator that used the * function. I have since removed it in favor of using randint()
sword = 0
D20 = 0
class Hero:
def swing_and_hit(sword, D20):
sword = D20
print(D20)
if sword >= 10:
print("You have defeated the Villian!")
elif sword < 10:
print("You have died!")
D20 = randint(1,20)
Adventurer = Hero
#Adventurer.D20_Func() Ignore this...aborted effort to try something
Adventurer.swing_and_hit(sword, D20)
Every time I run this at http://pythontutor.com/visualize.html#mode=edit, the random number generator outputs 13. I cannot figure out why it does this...any thoughts? I have tried nesting the random number generation inside the function swing_and_hit, and it still generates the same number every time I run the program.
This seems to be a "feature" in Pythontutor to ensure different people will see the same results running the same code. (I am getting always 17)
Whether or not they define it as a feature, it is broken as it could be - random numbers should be random.
Just install Python in your own computer, and get going - it is a smaller than 20MB download from http://python.org if you are using Windows (and if you are not, you have Python installed already). There are interactive interpreters and even a simple development environment that is installed along with the language - there is no motive for you to hurt yourself with a web implementation that might be good for group study of some code, or introspecting what goes in each variable step by step. Python interactive environments are much more dynamic than the "click to run" you get on this site.
I think the random number generator producing the same number every time is a quirk of pythontutor.com. I get 17 every time with just this code:
import random
print(random.randint(1, 20))
If you must use a website to run your code, try repl.it.

Rolling statistics for a game

I am very new to programming. I have only touched the surface of one language, Python, which is what I am working with at the moment. I am trying to write a program that can display random rolling numbers between a range like 1-100. For lack of being able to explain it, I would rather show a video of what I am looking to do.
http://www.youtube.com/watch?v=88SENZe6Z3I
At about 33 seconds in you can see rolling numbers that the player must stop in order to assign it to a character trait. Less all the pretty graphics and everything, What I want to know is if it is possible to write a program that serves this same type of function in Python? If not Python, the only other 2 languages I am becoming a little familiar with are C# and Java. Would it be possible to write it with one or a combination of those?
If it is possible, can you point me in the direction for resources to this effort. I did do a search before posting this but I found myself coming up empty for lack of knowing what to search for.
Thanks!
The “problem” is that this is not directly possible using the command line interface. If you are looking into game development you are probably going to have some graphical interface anyway, so you should look if you find a library that gives you more options in animating things.
Nevertheless, a possible solution for the command line would involve multi-threading. The reason for that is that you cannot both print (continuously changing) numbers and also wait for keyboard input. The normal command line is actually quite limited in that way.
Below you can find a possible solution with a threading approach. But again, if you are going for some game development, you should rather check out actual graphic libraries, or even game libraries that can help you.
from random import randint
from time import sleep
from threading import Thread
import sys
class RollAnimation ( Thread ):
activated = True
number = None
def run ( self ):
while self.activated:
self.number = randint( 1, 100 )
sys.stdout.write( '\r{: >3}'.format( self.number ) )
sys.stdout.flush()
sleep( 0.05 )
t = RollAnimation()
t.start()
# Waiting for enter
input() # use raw_input() for Python 2.x
t.activated = False
print( 'Final roll result:', t.number )
You haven't formulated your question correctly if people has to watch a Youtube video to understand what you want to do. Without watching the video, I can only assume you want to know how random integers work.
import random
x = random.randint(1, 100)
If you want it rolling, you can simply either make three variables or display three random integers inside a for loop and place that in a while or a for loop.
Here's an example.
import random
import sys
try:
rolls = int(sys.argv[1])
except IndexError:
print "Usage: "+sys.argv[0]+" [rolls]"
sys.exit(1)
for i in range(1, rolls+1):
print "Roll "+str(i)
for i in range(0, 3):
print random.randint(1, 100)
For the graphical part of your application, you should look at pygame: http://pygame.org

Categories