Python random number generator not working properly - python

outcomeG = "0"
outcomeB = "0"
def roll(outcomeG, outcomeB):
outcomeG = random.randint(1, 6)
outcomeB = random.randint(1, 5)
return outcomeG, outcomeB
def goodDiceRoll():
goodDiceOptions.destroy()
global goodDiceRoll
goodDiceRoll = tkinter.Tk()
goodDiceRoll.title("Green Dice roll")
lbloutcome = tkinter.Label(goodDiceRoll, text="Press roll")
btnRollG = tkinter.Button(goodDiceRoll, text="Roll", command=roll(outcomeG, outcomeB))
if outcomeG == "1":
lbloutcome.config(text="Green 1")
goodDiceRoll.update()
f = open("Logs.txt", "a")
ts = time.time()
sttime = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d_%H:%M:%S - ')
f.write(sttime + "Green 1")
f.close()
elif outcomeG == "2":
lbloutcome.config(text="Green 2")
goodDiceRoll.update()
f = open("Logs.txt", "a")
ts = time.time()
sttime = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d_%H:%M:%S - ')
f.write(sttime + "Green 2")
f.close()
#rest of code
This is some of my code that is suppose to let you roll a green dice or red dice and then put it in a file. However when I press the roll button that i made, it is suppose to randomize a number from 1 to 6 and display it but what really happens is absolutely nothing. How can i fix this? Any help will be much appreciated.

If you do roll(outcomeG, outcomeB) then don't expect those two global variables to change. They will remain 0. This is because the (parameter) variables within roll are local to that function. Any assignment made to those variables will not affect the variables that were passed to the function.
If you then call goodDiceRoll() the if blocks will not be entered since the values of those variables are still 0, and by consequence nothing gets written to the file.
You can solve this by doing:
outcomeG, outcomeB = roll()
... and remove the parameters from the roll definition.
But, as you don't call roll that way, but pass a reference to it via:
btnRollG = tkinter.Button(goodDiceRoll, text="Roll", command=roll)
... you are forced into using global variables. So modify roll like this:
def roll():
global outcomeG, outcomeB
outcomeG = random.randint(1, 6)
outcomeB = random.randint(1, 5)
Make sure to also define them as such in goodDiceRoll.
Secondly, it is a really bad idea to assign to goodDiceRoll, which really destroys the previous value it had, i.e. the function you are in. This will make the function unreachable after the first invocation. Use a different variable name.

If what you have posted is the entirety of your code, then it is unlikely that anything will be written, since you only include cases for the green dice rolling a "1" or a "2". Instead of using if statements to deal with different cases of rolls, you should instead do something like this:
f = open("Logs.txt", "a")
ts = time.time()
sttime = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d_%H:%M:%S - ')
f.write(sttime + "Green " + outcomeG + ",\n")
f.write(sttime + "Blue " + outcomeB + "\n")
f.close()
Also you need to make sure when you call the 'roll' function, you can access that data.

Related

Updating an integer variable after it has been modified by a def

===EDIT SOLVED! COMPLETED CODE IN COMMENTS BELOW!===
Making a text based role play game. Developing HP system. I've managed to make the HP and damage definitions. I need to make it so it updates the HP variable after every instance of damage that is taken.
I have only been coding for a week and don't know the terminology I'm looking for so I've not been able to search for an answer successfully but I've been trying to find an answer for about two hours now.
import random
hit_points = 20
d4_damage = random.randint(1, 4)
d6_damage = random.randint(1, 6)
d8_damage = random.randint(1, 8)
def hp_loss_small():
for x in range(1):
return hit_points - d4_damage
print (hp_loss_small())
def hp_loss_medium():
for x in range(1):
return hit_points - d6_damage
print (hp_loss_medium())
def hp_loss_large():
for x in range(1):
return hit_points - d8_damage
print (hp_loss_large())
Correct result would be if you ran a damage def and lost 4 hit points, it displays 16. But it doesn't update the hp variable, so if you take another 2 damage you go to 18 hp. I need it so it'd update the variable and go to 14.
for x in range(1):
You can omit this completely, since this only runs the statement once.
When you return a value from a function, you can assign the result to a variable. In your case, you'd do hit_points = hp_loss_small(). Additionally, you should pass the current hit points as a parameter (def hp_loss_small(hit_points)), and call it as hp_loss_small(hit_points).
In case anyone else finds this while searching for a similar problem here is my finished code:
import random
hit_points = 20
d4_damage = random.randint(1, 4)
d6_damage = random.randint(1, 6)
d8_damage = random.randint(1, 8)
def dead():
if hit_points < 1:
return ('dead message ')
else:
return (' ')
def hp_loss_small(hit_points):
return hit_points - d4_damage
print (hp_loss_small(hit_points))
hit_points = hp_loss_small(hit_points)
print (dead())
def hp_loss_medium(hit_points):
return hit_points - d6_damage
print (hp_loss_medium(hit_points))
hit_points = hp_loss_medium(hit_points)
print (dead())
def hp_loss_large(hit_points):
return hit_points - d8_damage
print (hp_loss_large(hit_points))
hit_points = hp_loss_large(hit_points)
print (dead())

How to give variable values from a function to another function?

Im making a "game" for practice. Its a basic guess game, but i wanted to make the game only with functions. This is my problem (for ex.):
function 1:
variablaA
#some other code
function 2:
variableB
variableC = varibleA + variableB
#some other code
I have tried too goole about objects and classes but im not sure i understand what im doing right now.
import random
import sys
min = 1
max = 99
guessed_number = random.randint(min, max)
class functions:
def __init__(game, difficulty, lifes):
game.difficulty = difficulty
game.lifes = lifes
def GameDiff(hardness):
#Setting game difficulty
print "Select difficulty : \n 1; Easy \n 2; Medium \n 3; Hard \n"
difficulty = raw_input()
if difficulty == "1":
print "Its just the beginning"
lifes = 15
elif difficulty == "2":
lifes = 10
elif difficulty == "3":
lifes = 5
else:
print "This isn't an option try again"
GameDiff(hardness)
def core(basic):
#The core of the game
print "I guessed a number..."
player_number = int(raw_input("Whats the number I thinking of?"))
constant = 1
GameTime = 1
while GameTime == constant:
if player_number < guessed_number:
print "Your number is smaller than my guessed number"
print "Try to duplicate your number (But maybe Im wrong)"
player_number = int(raw_input("Make your tip again\n"))
elif player_number > guessed_number:
print "Your number is bigger than my guessed number"
print "Try to half your number (But maybe Im wrong)"
player_number = int(raw_input("Make your tip again\n"))
else:
GameTime = 0
print "You guessed it! Congratulations"
def main(self):
#The whole game only with functions
functions.GameDiff()
functions.core()
Function = functions()
Function.main()
if you are defining function with parameters, you need to pass data(parameters) into a function when you call it
example:
def my_function(name):
print("my name is " + name)
my_function("Kevin")
in your case you define:
def GameDiff(hardness):
def core(basic):
which are expecting parameters
and when you are calling those funcitions, you are doing that on wrong way:
def main(self):
#The whole game only with functions
functions.GameDiff()
functions.core()
Function = functions()
you need to pass parameters
example:
functions.GameDiff(5)
functions.core(1)
Function = functions(1,5)
NOTE: good practice will be to use self instead of game
def __init__(self, difficulty, lifes):
self.difficulty = difficulty
self.lifes = lifes
they are just two different kinds of class elements:
Elements outside the init method are static elements; they belong
to the class. They're shared by all instances.
Elements inside the init method are elements of the
object (self); they don't belong to the class.Variables created inside init (and all other method functions) and prefaced with self. belong to the object instance.

Python: ' ' is not defined

Here is my code:
# This program makes the robot calculate the average amount of light in a simulated room
from myro import *
init("simulator")
from random import*
def pressC():
""" Wait for "c" to be entered from the keyboard in the Python shell """
entry = " "
while(entry != "c"):
entry = raw_input("Press c to continue. ")
print("Thank you. ")
print
def randomPosition():
""" This gets the robot to drive to a random position """
result = randint(1, 2)
if(result == 1):
forward(random(), random())
if(result == 2):
backward(random(), random())
def scan():
""" This allows the robot to rotate and print the numbers that each light sensors obtains """
leftLightSeries = [0,0,0,0,0,0]
centerLightSeries = [0,0,0,0,0,0]
rightLightSeries = [0,0,0,0,0,0]
for index in range(1,6):
leftLight = getLight("left")
leftLightSeries[index] = leftLightSeries[index] + leftLight
centerLight = getLight("center")
centerLightSeries[index] = centerLightSeries[index] + centerLight
rightLight = getLight("right")
rightLightSeries[index] = rightLightSeries[index] + rightLight
turnRight(.5,2.739)
return leftLightSeries
return centerLightSeries
return rightLightSeries
def printResults():
""" This function prints the results of the dice roll simulation."""
print " Average Light Levels "
print " L C R "
print "========================="
for index in range(1, 6):
print str(index) + " " + str(leftLightSeries[index]) + " " + str(centerLightSeries[index]) + " " + str(rightLightSeries[index])
def main():
senses()
pressC()
randomPosition()
scan()
printResults()
main()
So, I am getting this error when I run my program.
NameError: global name 'leftLightSeries' is not defined
I understand that I must be doing something wrong related to the return statement. I'm not sure if I can only return one variable at the end of a user-defined function. If that were to be true, then I should probably separate the scan(): function. Anyways, I would appreciate any help on how to fix this error. Also, this is the result that I am looking for when I successfully complete my program:
Click Here
I am looking to complete the average values like the picture shows, but I am not worried about them at this point, only the list of values from the light sensors. I do not need to reach those exact numbers, the numbers will vary in the simulator.
If you want to return multiple items from scan(), don't use three separate return statements. Instead, do this:
return leftLightSeries, centerLightSeries, rightLightSeries
Also, when you call the function, you have to assign variable(s) to the returned values; it won't automatically create new local variables with the same names. So in main, call scan() like this:
leftLightSeries, centerLightSeries, rightLightSeries = scan()

Save File Function

So for my intro programming class we have to create a game with a save/load function and I'm trying to test out some code to make sure it works.
For some reason I cannot get the following function to work properly. I've tried going through it line by line in the Idle and it works just fine there but once I try to use the same system in a function it just will not work. Help please?
def save(name,inventory,mapGrid,x,y,enemy):`
choice = 0
file = shelve.open("save_files")
save = {'save1':file['save1'],'save2':file['save2'],'save3':file['save3']}
print("Where would you like to save?")
print("Save 1 -", save['save1']['name'])
print("Save 2 -", save['save2']['name'])
print("Save 3 -", save['save3']['name'])
choice = input("Enter Number:\t")
if choice == 1:
save['save1']['name'] = name
save['save1']['inventory'] = inventory
save['save1']['mapGrid'] = mapGrid
save['save1']['x'] = x
save['save1']['y'] = y
save['save1']['enemy'] = enemy
file['save1'] = save['save1']
file.sync()
if choice == 2:
save['save2']['name'] = name
save['save2']['inventory'] = inventory
save['save2']['mapGrid'] = mapGrid
save['save2']['x'] = x
save['save2']['y'] = y
save['save2']['enemy'] = enemy
file['save2'] = save['save2']
file.sync()
if choice == 3:
save['save3']['name'] = name
save['save3']['inventory'] = inventory
save['save3']['mapGrid'] = mapGrid
save['save3']['x'] = x
save['save3']['y'] = y
save['save3']['enemy'] = enemy
file['save3'] = save['save3']
file.sync()
file.close()
print("Game Saved")
EDIT: After running the function it should save the dictionary to file['save#'] and allow me to access the data later on, but the data doesn't save to the shelve file and when I try to access it again there's nothing there. ((Sorry should have put this in right off the bat))
For example if I run the save() function again it should display the name associated with the save file, but it just shows 'EMPTY'.
The basic thing I have the save_files set to is
file['save#'] = {'name':'EMPTY'}
Since your if statements are comparing int, make sure that choice is also an integer. It's possible that choice is actually a string, in which case none of the comparisons will be True. Basically:
choice = int(input("Enter Number:\t"))
Alternatively you could change all comparisons to strings, but the important thing is to assure type consistency in the comparisons

Python 2 game coordinates class

I wanted to create a x-y coordinate system even though this is supposed to be a text RPG as to keep track of where everything is. So, I was experimenting on making a function and test for that function that would let the character move on a x-y grid, however, no matter what I try, I cannot make it work. Here is the code:
class Player:
def movement(charactor_movement):
proceed = 0
if charactor_movement == "left":
character.position_x = character.position_x - 1
proceed = 1
elif charactor_movement == "right":
character.position_x = character.position_x + 1
proceed = 1
elif charactor_movement == "forward":
character.position_y = character.position_y + 1
proceed = 1
elif charactor_movement == "backward" or charactor_movement == "back":
character.position_y = character.position_y - 1
proceed = 1
charactor = Player()
charactor.position_x = 0
charactor.position_y = 0
proceed = 0
while proceed == 0:
print "You are at",
print charactor.position_x,
print"x and",
print charactor.position_y,
print"y."
global charactor_movement
charactor_movement = raw_input("Where are you going?")
charactor.movement()
At this point, it does what it is supposed to do up to changing the coordinates, as it prints "You are at 0 x and 0 y" and "Where are you going?" no matter what I type. I have tried adding an else to the function which it defaulted to no matter what I typed and gave me "Sorry, I cannot understand you." Any comments on fixing or generally improving the code would be appreciated.(Note: For the testing I purposely did not add a way to exit. The class is what i need fixed.)
You are getting the same coordinates with each iteration because your values within your while loop are not changing. Incrementing character.position_x within movement will never change the value of character.position_x within your while loop, as it is outside your function's scope. You have to use the global keyword within your movement function for each variable you are changing should you want your current logic to remain the same. Additionally, why not just pass charactor_movement as a parameter to your movement function, as opposed to using global as you currently are doing.
A minimal example:
Consider the following:
def somefunct(x):
mycode = x
mycode = 'no codez'
while True:
print mycode
codez = raw_input('gimme teh codez: ')
somefunct(codez)
which outputs
>>>[evaluate untitled-1.py]
no codez
gimme teh codez: codez!
no codez
Declaring mycode as global in the function places it in the scope of the while loop when assigned, thus
def somefunct(x):
global mycode #make variable global here
mycode = x
mycode = 'no codez'
while True:
print mycode
codez = raw_input('gimme teh codez: ')
somefunct(codez)
results in the output
>>>[evaluate untitled-1.py]
no codez
gimme teh codez: codez!
codez!

Categories

Resources