Confusion in looping a Python class - python

Sorry if I don't do this correctly, I am new here. I am trying to make it so that raw_input loops through saving the value of self.x every time so that it asks "r or l"? Whenever you click enter, then raise or lower self.x but I'm not sure how to. If someone could check my work, that would mean a lot. Thank you.
q = raw_input("r or l: ")
class game:
def __init__(self):
self.x = 0
def raise_n(self):
self.x += 1
return self.x
def lower_n(self):
self.x -= 1
return self.x
def main():
g = game()
while q == "r":
print g.raise_n()
break
while q == "l":
print g.lower_n()
break
main()
I also tried this, but it didn't save the value of self.x even if I tried to call main() again.
q = raw_input("r or l: ")
class game:
def __init__(self):
self.x = 0
def raise_n(self):
self.x += 1
return self.x
def lower_n(self):
self.x -= 1
return self.x
def main():
g = game()
while q == "r":
print g.raise_n()
break
while q == "l":
print g.lower_n()
break
main()
Any help would be very useful, thank you!

Your second approach was closer to a valid solution. There are several approaches, and below I show you one, without introducing too many changes. Basically:
The main() function is executed in an endless loop. Change the True condition if you want to change the stop condition.
The question is asked and evaluated every time it enters the main() function. Afterwards, it checks if it has to run the raise_n() or lower_n() methods.
The code:
class game():
def __init__(self):
self.x = 0
def raise_n(self):
self.x += 1
return self.x
def lower_n(self):
self.x -= 1
return self.x
def main():
q = raw_input("r or l: ")
if q == "r":
print g.raise_n()
if q == "l":
print g.lower_n()
g = game()
while True:
main()
EDIT: In order to put as condition for the while loop to iterate a determinated number of times, a constant can be succesively increased and check if it has reached the desired limit:
#... Copy previous code here
g = game()
iterations_limit = 10 #Substitute 10 by any positive integer
while k > iterations_limit:
k += 1 #Increase variable k
main()

Related

Python not saving variable values when they are changed inside a function

I saved my variables at the start of my program and allow the functions to access them I believe but when they run the value is not saved when the function repeats.
P1_score = 0
P2_score = 0
round_number = 0
def dice_rolling():
# P1D1 means player ones dice one value and so on with P1D2
import random
# player ones turn
print("player ones turn")
P1D1 = random.randint(1, 6)
print("your number is ", P1D1)
P1D2 = random.randint(1, 6)
print("your second number is", P1D2)
# player twos turn
print("player twos turn")
P2D1 = random.randint(1, 6)
print("your number is", P2D1)
P2D2 = random.randint(1, 6)
print("your second number is", P2D2)
score_calculation(P1D1, P1D2, P2D1, P2D2,P1_score,P2_score,round_number)
def score_calculation(P1D1, P1D2, P2D1, P2D2,P1_score,P2_score,round_number):
import random
round_number = round_number + 1
# player 1 score calculation
total_P1 = P1D1 + P1D2
P1_score = P1_score + total_P1
if total_P1 % 2 == 0:
P1_score = P1_score + 10
else:
P1_score = P1_score + 5
if P1D1 == P1D2:
P1D3 = random.randint(1, 6)
P1_score = P1_score + P1D3
# player 2 score calculation
total_P2 = P2D1 + P2D2
P2_score = P2_score + total_P2
if total_P2 % 2 == 0:
P2_score = P2_score + 10
else:
P2_score = P2_score + 5
if P2D1 == P2D2:
P2D3 = random.randint(1, 6)
P2_score = P2_score + P2D3
print("player ones score at the end of round", round_number, "is", P1_score)
print("player twos score at the end of round",round_number,"is",P2_score)
for x in range(0,5):
dice_rolling()
Any help would be appreciated and if someone could give a simple explanation as to what I'm doing wrong and what to fix would be great.
Python can read from global variables inside a function, but can't assign them without some extra work. In general, when you want to use a global variable, it's a good idea to make it explicit by using the global keyword in your function:
my_global_var = 0
def some_function():
global my_gobal_var
my_global_var = 10
print(my_global_var) # it prints 10
somefunction() # modifies the global var
print(my_global_var) # now it prints 10
Variables are defined and used locally. Consider this example.
x = 1 #initial value
def test(x):
print(x) #print what you got
x += 1
print(x) #print updated value
print(x) #Actual printouts here
test(x)
print(x)
This results in :
1
1 #value when entering the function
2 #Value changed by function
1 #value outside the function did not change
If you want the variables to be maintained in functions, consider using class variables or global variables. (I recommend avoiding globals as you get to more complex problems)
Global example:
global x
x = 1
def test():
global x
x+=1
print(x)
test()
print(x)
test()
print(x)
Results in :
1
2
3
Finally class variables:
class test_class():
def __init__(self):
self.x = 1 #variables defined like this are class variables
def test(self):
self.x += 1 #Advantages of class variables is that you can defined them in the __init__ function
def running(self):
print(self.x) # And you can access it from multiple functions without using globals and much more too.
self.test()
print(self.x)
if __name__ == '__main__':
tclass = test_class()
tclass.running()

Class' Function, When called, does nothing

So I've been working on this game (I'm a big noob at python and I've only worked on this for like 3 days) and I've been trying to move the Location (Add or Subtract one from Location's x and y values) but the fuction doesn't work. I know because I put a print in the function and the print didn't work at all. What is wrong? (I have created a folder for this project and there is a folder called Decisions containing 2 files.)
Locations.py:
class Location:
def __init__(self, x, y):
self.x = x
self.y = y
def move_forward(self):
self.y = self.y + 1
return self.y
def move_back(self):
self.y = self.y - 1
return self.y
def move_left(self):
self.x = self.x - 1
return self.x
def move_right(self):
self.x = self.x + 1
return self.x
main.py (Main Function):
import Decisions
import Characters
import Locations
def main():
Player = Characters.Character([], 100)
Loc = Locations.Location(0, 0)
answer = Decisions.choice_yes_no.choice_yes_no("You woke up, discovering
that somehow you were in the middle of a dark dungeon. A sword lies to the
left of you, pick it up? (Yes/No) ")
if answer == True:
print("You picked up the sword.")
Player.add_item("Sword")
elif answer == False:
print("You chose not to pick up the sword.")
answer_2 = Decisions.choice_direction.choice_direction("You stood up,
patting the dust off your clothes, you looked around. The room was dark and
you view was limited to a few meters. Where do you go?
\n(Left/Right/Forward/Back) ")
if answer == "forward":
Loc.y = Loc.y + 1
elif answer == "back":
Loc.move_back()
elif answer == "left":
Loc.move_left()
elif answer == "right":
Loc.move_right()
print(Loc.x)
print(Loc.y)
main() #REMOVE BEFORE USING#
The function add_item works just fine, what is wrong? There aren't any errors, it's just when I print the x and y values at the end they stay 0.

Preventing a step back in python for rhino

Im trying to make a stepping function in python for rhino,
The function is supposed to make a step in a random direction, without going backwards.
How do i prevent a step back?
import rhinoscriptsyntax as rs
import random as r
r.seed(seed)
class Walker:
def __init__(self):
self.x = 0
self.y = 0
def point(self):
shape = rs.AddPoint(self.x, self.y, 0)
return shape
def step(self):
choice = r.randint(0,3)
choice = r.randint(1,3)
if (choice == 0):
self.x = self.x + r.choice(uList)
elif (choice == 1):
self.x = self.x - r.choice(uList)
elif (choice == 2):
self.y = self.y + r.choice(uList)
else:
self.y = self.y - r.choice(uList)
uList = [8,11,14]
w = Walker()
pList = []
for t in range(time):
w.step()
pList.append(w.point())
for t-1 in range(time):
a = pList
This line:
choice = r.randint(0,3)
chooses one of 4 directions randomly. But if you don't want to go backwards, then you only want forward, left and right. So change the parameters to randint() so that it only chooses from 3 possible numbers, avoiding the one that corresponds to the direction you are calling backwards, whichever that is.

Why is my count variable not incrementing for each new instance of my class?

My code:
class Lobby(Definition):
Lcount = 0
def __init__(self):
if Lobby.Lcount == 0:
self.description = "test1"
elif Lobby.Lcount > 0:
self.description = "test2"
else:
print("\nHmmm something went wrong...\n")
self.contents = ["Briefcase"]
self.doors = {"n": "terminal", "w": "hallway"}
Lobby.Lcount += 1
I want it to be where after an instance of the room has been created (i.e. you have visited it before), it will display a different description than it the original one. However, it keeps printing the same description. So what precisely am I doing wrong here?
edit: Here is what is in my definition class:
class Definition:
def __init__(self):
self.description = ""
self.contents = []
self.doors = {}
def get_desc(self):
print("{}".format(self.description))
def get_direction(self):
direction = input("Enter a direction or search the room: ").lower()
search = True
if direction == "q":
return direction
elif direction in self.doors:
location = self.doors[direction]
return location
elif direction == "s":
while search:
action = input("\nYou search for some items... Press 1 to continue or 2 to quit.\n")
if action == "1":
if len(location.contents) == 0:
print("\nYou find nothing of value in the room.\n")
else:
find = random.randrange(1, 3)
if find == 1:
found = random.randrange(len(location.contents))
item = location.contents.pop(found)
print("\nYou found a {}\n".format(item))
self.items.append(item)
self.check_items()
else:
print("\nNothing found yet\n")
elif action == "2":
search = False
break
else:
print("\nLocation reminder: ")
location.get_description()
else:
return "\nNot a valid entry\n"
Something in Definition is preventing this from working appropriately.
class FooClass(object):
foo = 0
def __init__(self):
print("Foo {} before".format(self.__class__.foo))
self.__class__.foo += 1
print("Foo {} after".format(self.__class__.foo))
# Works appropriately
>>> x = Foo()
Foo 0 before
Foo 1 after
>>> x = Foo()
Foo 1 before
Foo 2 after
However I'd recommend a different way to track this if it's just a binary "seen" variable. Restricting your ability to create multiple Lobby objects may mess you up in the future. Strongly consider creating a dictionary that houses all your objects, with a visit method that runs the logic your __init__ is doing now, and sets a flag that makes a following visit do something different.
class SomeRoom(Room):
# where Room is some superclass like Definition is now
def __init__(self, *args):
super().__init__(args) # or however
self.__visited = False
#property
def visited(self):
return self.__visited
def visit(self):
if self.visited:
print("Welcome back")
else:
print("Welcome!")
self.__visited = True

Passing Objects Between functions?

I am new to programming in python and, I started writing a simple text based adventure game. I came across a problem when passing an object from one function to another. Here is my code:
import random
import time
num = random.randint(0,2)
xp1 = random.randint(1,2)
class player:
def __init__ (self, name, health, strength, defense, potion, xp, level):
self.__health = health
self.__strength = strength
self.__defense = defense
self.__name = name
self.__potion = potion
self.__xp = xp
self.__level = level
def getName(self):
return self.__name
def getHealth(self):
return self.__health
def getStrength(self):
return self.__strength
def getDefense(self):
return self.__defense
def getPotion(self):
return self.__potion
def getXP(self):
return self.__xp
def getLevel(self):
return self.__level
def setHealth(self):
self.__health = 10
def setLevel(self):
self.__level = 1
def subHealth(self, num):
self.__health -= num
def subPotion(self):
self.__potion -= 1
return self.__health
def addPotion(self, num1):
self.__potion += num1
def addHealth(self):
self.__health +=2
def addStrength(self):
self.__strength += 1
def addDefense(self):
self.__defense += 1
def addXP(self):
self.__xp += xp1
def addLevel(self):
self.__level += 1
self.__addHealth += 1
self.__defense += 1
self.__strength += 1
def battle(enemy, player1, name1):
player1 = player(name1, player1.getHealth(), player1.getStrength(), player1.getDefense(), player1.getPotion(), player1.getXP(), player1.getLevel())
enemy = player('Dongus', enemy.getHealth(), enemy.getStrength(), enemy.getDefense(), enemy.getPotion(), enemy.getXP(), enemy.getLevel())
s = 0
while s == 0:
time.sleep(1)
attack =int(input("Type 1 to attack, type 2 to use a potion."))
if attack == 1:
time.sleep(1)
print("Dongus's health is", enemy.subHealth(num))
print("Dongus hit you and your health is now at", player1.subHealth(num-player1.getDefense()))
elif attack == 2:
time.sleep(1)
print("You used a potion.")
player1.addHealth(), player1.subPotion()
if player1.getHealth() > 10:
player1.setHealth()
print("Dongus hit you and your health is now at", player1.subHealth(num-player1.getDefense()))
if enemy.getHealth()<=0:
print("Congratulations, you won! You recieved", xp1, "xp!")
player.addXP()
s = 2
def main():
name1 = input("What would you like your name to be?")
time.sleep(1)
print("Hello,", name1, "you are on a quest to save otis from the evil Dongus. You must slay him, or Otis will poop.")
time.sleep(2)
player1 = player(name1, 10, 2, 1, 0, 0, 1)
enemy = player('Dongus', 8, 4, 0, 0, 0, 0)
print("Your stats are, health:", player1.getHealth(), "strength:", player1.getStrength(), "and defense:", player1.getDefense())
time.sleep(2)
print("Fight!")
pick = input("You found a health potion! Press 'p' to pick it up.")
p = 0
while p == 0:
if pick == "p":
print("You added a potion to your inventory.")
player1.addPotion(1)
p = 2
else:
print("You have no potions, you should probably pick this one up.")
player1.addPotion(1)
p = 2
battle(enemy, player1, name1)
if self.__getXP() == 1:
print("You leveled up. You are now level 2.")
player1.addLevel()
print("Your stats are, health:", player1.getHealth(), "strength:", player1.getStrength(), "and defense:", player.getDefense())
loot1 = int(input("Type ''1'' to loot the enemy chest."))
if loot1 == 1:
print("You recieved two potions!")
player1.__addPotion(2)
enemy.setHealth(10)
battle(enemy, player1, name1)
main()
Now the problem is when I run the game, I get to a point where I type "1" to attack the enemy, but it says, for some reason, that after attacking the enemy, the enemies health is at "None". This is the same case when the enemy attacks player1, it says player1's health is at "None". I assume that "None" is the default value in python 3.4.1, so my thinking is that the player1's object from def main() are not being transferred over to def battle() and I cannot see the reason why this is happening. I most likely am missing something here, or it is something I do not already know about Python that is causing the issue. Does anybody know what I can do to fix this, and why it is doing this?
BTW some of the terms I am using may be wrong, so please correct me if they are... I have only been coding for 2 weeks :p.
Thanks!!!
First, received not recieved
2nd yes, If you have a Python function that does not return a value, the result is None
# dummy will return "Positive" or None
def dummy(x):
if X > 0:
return "Positive"
So, you probably want to change
def subHealth(self, num):
self.__health -= num
to
def subHealth(self, num):
self.__health -= num
return self.__health
Your question re: the "player" classes from def main() are not being transferred over to def battle() does not really make sense to me.
But, I see that in the first 2 lines of battle, you are replacing the formal parameters player1 and enemy with local variables, this seems like odd usage in your program.

Categories

Resources