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.
Related
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.
I wrote this code for my homework:
import random
score=[]
random.seed(1)
for i in range(0,100):
score.append(random.randrange(0,21))
for k in range(20, -1, -1):
print("Who get %2d score in test? : "%(k), end='')
while score.count(k)!=0:
j = score.index(k)
print("%3s" % (j), end=" ")
score.remove(k)
score.insert(j,25)
print("\n")
I ran it on my computer many times and the results were the same. Ironically, in other computers, the results are different from my computer, but also also getting repeated at each execution.
What's wrong with my code?
random.seed(n) starts the random number generator off from the same point each time the program is run.
That is you get the same sequence of random numbers. It is like taking a video of a dice being thrown and then playing it back each time - the numbers are random (pseudo random to be accurate) but you are playing back the sequence.
This is useful for testing, for example: you can run different versions of your program with the same random numbers, so you are sure differences in your results are only due to the program, not to chance.
Take random.seed out and you will get a sequence that starts at a random location. (On most computers, if you don't specify a seed, the clock time the program started is implicitely used as seed.)
When you write
random.seed(1)
You are saying to always use the same sequence of randomly generated numbers, therefore you always have the same results.
It happens when I run it on my computer too.
Simply remove the line and you should have different randomly generated numbers every time.
See this answer for an explanation of the seed.
And the python documentation for the random library
I've seen some similar questions, but they seemed to use some other programming language
So far I've got:
import turtle
turns=turtle.Turtle()
degree=input('enter a number: ')
for i in range(5):
turtle.left(degree)
turtle.forward(100);
Running this doesn't ask me to input a number and thus doesn't print anything
You should give commands to your turtle, which you named turns.
You invoked the methods on the class as a whole, which doesn't do anything useful for you. Try this:
for i in range(5):
turns.left(degree)
turns.forward(100)
For the input, just follow any input example for your Python version. For instance, for Python 3, try
degree = int(input("Enter the angle of the turn in degrees:"))
Also try inserting some debugging print statements to track the data and control flow.
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)
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