Why is 'module' object not callable? [duplicate] - python

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
TypeError: ‘module’ object is not callable
This is my very first Python attempt, just trying to regain basic programming knowledge after a 10 year silence in a, for me, new language, Python. The basic idea is a tiny battly engine which decides the better hit. The bugging code is next.
self.__power = self.__att*random(2,4)/dier.__defn
As my python knowledge is extremely basic, I'm rather scared of saying the right things so Im gonna put my code down below (47 lines), you..ll notice it is really transparant so I dont suspect this will give any problem. The errorline is 16. I tried renaming the att variable to atta as well as some repositionings though new bugs come, I solve them and in the end its always the same error on the same line.
class Character:
def __init__(self,name="", att=0,defn=0,lvl=0,leven=0,exp=0, power=0):
self.__att = att
self.__defn = defn
self.__lvl = lvl
self.__leven = leven
self.__name = name
self.__xp = exp
self.__power = power
def batl(self):
import random
while self.__lvl <= 3:
dier = Character("Anaconda",1,1,50,1,0,0)
print "You encountered an " + dier.__name + " and fight it."
**self.__power = self.__att*random(2,4)/dier.__defn**
dier.__power = (dier.__att*random(1,4))/self.__defn
if self.power > dier.power:
growth = dier.__lvl*dier.__atta
groei()
else:
dmg = dier.lvl*dier.att
leven = leven-dmg
if leven < 0:
print "Alas, you're done for."
exit()
else:
print "You took " + dmg + "damage and have " + leven + "life left."
def groei(self):
if (growth+exp) > 100:
lvl += 1
exp = growth-100
print "You won and gained " + str(growth) + " and grew from level " + str(lvl-1) + " to level " + str(lvl) + "."
else:
exp = growth + exp
print "You won and gained " + str(growth) + "."
def main():
hero = Character("Nevery",2,1,2,100,0,0)
hero.batl()
if name == 'main':
main()
As you can see ive got my character class, in which i have defined the battle() method and the groei() method, very basic. Can anyone point me what I'm missing out on, been looking at it for hours. Thanks in Advance

random is the module, not the function. You need to call random.random. You could also from random import random, but I'd go with the first option in this case.

Use random.random() instead of random?

Related

KeyError Codes from User Input

Good Evening All,
I have been working on my first self directed project and have run into a bit of a snag. The program calculates what a character would have to roll to hit another based on their THAC0 and AC. The two scores in question are kept in a pair of dictionaries. If something is entered that is not in the dictionary I want the program to let whoever is operating it know. I've managed to get it to produce an error code, but I still get a KeyError. How do I get it to stop doing that?
defender = input("Who are they attacking?")
dict_thaco = {"Serena" : 19, "Morris" : 19}
if aggressor in dict_thaco:
pass
else:
print("I don't know that attacker")
dict_ac = {"Serena" : 6, "Morris" : -1}
if defender in dict_ac:
pass
else:
print("I don't know that defender")
def thaco_calc(thaco, ac):
to_hit = thaco - ac
return to_hit
aggressor_thaco = dict_thaco[aggressor]
defender_ac = dict_ac[defender]
hit = thaco_calc(aggressor_thaco, defender_ac)
print(aggressor + " would need to roll a " + str(hit) + " to hit " + defender + ".")
Perhaps you need something like
...
try:
aggressor_thaco = dict_thaco[aggressor]
defender_ac = dict_ac[defender]
hit = thaco_calc(aggressor_thaco, defender_ac)
print(aggressor + " would need to roll a " + str(hit) + " to hit " + defender + ".")
except KeyError as e:
print(e)

Creating a simple experience points gaining and leveling up system in a text based RPG in Python

Feel free to edit this post if it requires it.
Hi, I have been learning python for two months now, and I just finished learning about functions and blue bean logic. I decided to try my hand at making a text adventure on the side while I am not in class, and seeing how it turns out at the end of the semester. My tutor is not available this week, or the next, so I take my questions here. I feel like my problem has to do with me not fully understanding how the global variables work yet, as I just started using them, or if I should even use them to store data for this purpose. The idea I have with this game is essentially to run on calling a bunch of functions that I will make when I need them to, because I feel like it is pretty efficient for what I know. Running this code gives the error "positional argument is missing" if you are to run it. What could I do better here? I tried to integrate a function to test it out too, so that it would be easier to give me assistance.
tldr;
how can I make the experience points system I am trying to envision work so that it saves the number of experience points that are gained, then adds that number to the new higher requirement of experience for the next level as in most RPG games? For example, upon adding five experience, the program errors out. Thanks in advance for reading this! I hope I adequately explained my issue.
here is the code that I have come up with so far
global playername
playername = "Name Jeff 21 Bruh"
global playerlvl
playerlvl = 0
global xpcurrent
xpcurrent = 0
global xpnext
xpnext = int(((playerlvl * 4) / 3) + 4)
global xpgained
xpgained = 0
def show_stats():
print("*" * 20, "\n")
print(playername, "the Adventurer")
print("Lvl", playerlvl)
print("EXP =", xpcurrent, '/', xpnext)
print("-_" * 16 + '\n')
def lvlup(xpgained):
global xpcurrent
xpgainedhere = xpgained
xpcurrent += xpgained
xpgained = 0
if xpcurrent >= xpnext:
playerlvl + 1
xpcurrent -= xpnext
print("~ ~", playername, "is Lvl", playerlvl, "! ~ ~")
if xpcurrent >= xpnext:
lvlup()
else:
show_stats()
else:
print("~ ~", playername, "gained", xpgainedhere, "Exp! ~ ~")
show_stats()
def game_main():
print("*" * 50)
print("This is where the game begins.")
# ------just before this \n (the '.' )is the character limit
# ---------------------------------------------------------V
print("The player after lines of text can enter commands.\n"
"use this to enter commands to test them.")
print("*" * 50, "\n")
def testexp():
addexp = int(input("type the integer for how much exp "
"that you would like to add\n"))
lvlup(addexp)
testexp()
testexp()
testexp()
testexp()
testexp()
testexp()
testexp()
testexp()
game_main()
Global variables are generally a bad idea. Try to convert your functions to use parameters instead of global variables.
this part
def show_stats():
print("*" * 20, "\n")
print(playername, "the Adventurer")
print("Lvl", playerlvl)
print("EXP =", xpcurrent, '/', xpnext)
print("-_" * 16 + '\n')
would become
def show_stats(playername, playerlvl, xpcurrent, xpnext):
print("*" * 20, "\n")
print(playername, "the Adventurer")
print("Lvl", playerlvl)
print("EXP =", xpcurrent, '/', xpnext)
print("-_" * 16 + '\n')
to use this new function instead of making all the variables global do
playername = "Name Jeff 21 Bruh"
playerlvl = 0
xpcurrent = 0
xpnext = int(((playerlvl * 4) / 3) + 4)
show_stats(playername, playerlvl, xpcurrent, xpnext)

Have I implented Prim's Algorithm correctly? - Maze generation

I am fairly new to Python, and recently started creating a game, that I hope would entirely take place in the terminal. One of the aspects of the game was creating a random maze, so I decided to use a randomized form of Prim's Algorithm, as described here - https://en.wikipedia.org/wiki/Maze_generation_algorithm
The code works, but the maze feels to "easy", as though there are too many connections between the passageways. I don't know whether this is because I did it wrong, or it's just a feature of the algorithm. Either way, I would appreciate someone explaining how to fix this; keep in mind I'm still a beginner.
import random
def printout(*args):
for arg in args:
print(*arg, sep='')
Map = [["░" for k in range(40)] for l in range(20)]
def Prim(Map):
Wall_List = []
position = [0,20]
Map[0][20]= " "
for i in range(420):
if Map[(position[0]+2)%20][position[1]] == "░":
Wall_List.append([(position[0]+2)%20,position[1]])
if Map[(position[0]-2)%20][position[1]] == "░":
Wall_List.append([(position[0]-2)%20,position[1]])
if Map[position[0]][(position[1]+2)%40] == "░":
Wall_List.append([position[0],(position[1]+2)%40])
if Map[position[0]][(position[1]-2)%40] == "░":
Wall_List.append([position[0],(position[1]-2)%40])
cellposition = random.choice(Wall_List)
joiningwalls = []
if Map[(cellposition[0]+2)%20][cellposition[1]] == " ":
joiningwalls.append([(cellposition[0]+1)%20,cellposition[1]])
if Map[(cellposition[0]-2)%20][cellposition[1]] == " ":
joiningwalls.append([(cellposition[0]-1)%20,cellposition[1]])
if Map[cellposition[0]][(cellposition[1]+2)%40] == " ":
joiningwalls.append([cellposition[0],(cellposition[1]+1)%40])
if Map[cellposition[0]][(cellposition[1]-2)%40] == " ":
joiningwalls.append([cellposition[0],(cellposition[1]-1)%40])
joiningcell = random.choice(joiningwalls)
Map[joiningcell[0]][joiningcell[1]] = " "
Map[cellposition[0]][cellposition[1]] = " "
position = cellposition
Wall_List.remove(cellposition)
return Map
Map = Prim(Map)
printout(*Map)

How do I get a python program to rerun itself [duplicate]

This question already has answers here:
How do I re-run code in Python?
(9 answers)
Closed 6 years ago.
I want the code below to automatically rerun itself any ideas hwo to do this? Btw I am new to stack overflow and python itself so If I am doing anything wrong on either please let me know, Thanks
import sys
import os
import random
answer_correct_message = random.choice(['Well done', 'Correct answer','Nice one','Thats correct!'])
answer_wrong_message = random.choice(['Unlucky','Thats wrong','Nope'])
random_num_1 = random.randint(1,10)
random_num_2 = random.randint(1,10)
def question_asker_and_answerer():
q2 = input("What is " + str(random_num_1) + " + " + str(random_num_2) + "?")
if q2 == random_num_1 + random_num_2:
the_questions = True
if the_questions == True:
return (answer_correct_message)
else:
return (answer_wrong_message)
else:
the_questions = False
if the_questions == True:
return (answer_correct_message)
else:
print(answer_wrong_message)
print question_asker_and_answerer()
This is not a situation where you are need a program to rerun itself. That sort of requirement is when you want a script to run as a daemon. This is simply a matter of creating a loop
while True:
print question_asker_and_answerer()
There are two problems here:
how to iterate;
how to make sure that the various randomly-chosen variables are different each pass through.
Just looping over the existing function, or getting it to recurse (as in a couple of other answers) solves the first of these problems (actually, recursing really doesn't, since Python doesn't have tail-call elimination, so it will run out of stack eventually).
To solve both of them you need to make the randomly-chosen variables local to the function, and then loop. I have also modified it so it returns the string to print rather than printing it, in the case of a wrong answer (last line of function).
import sys
import os
import random
def question_asker_and_answerer():
answer_correct_message = random.choice(['Well done', 'Correct answer',
'Nice one','Thats correct!'])
answer_wrong_message = random.choice(['Unlucky','Thats wrong','Nope'])
random_num_1 = random.randint(1,10)
random_num_2 = random.randint(1,10)
q2 = input("What is " + str(random_num_1) + " + " + str(random_num_2) + "?")
if q2 == random_num_1 + random_num_2:
the_questions = True
if the_questions == True:
return (answer_correct_message)
else:
return (answer_wrong_message)
else:
the_questions = False
if the_questions == True:
return (answer_correct_message)
else:
return (answer_wrong_message)
while True:
print question_asker_and_answerer()

Simple 1 vs 1 Fight Simulation [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I'm trying to write a simple program that defines two imaginary fighters with only a name and amount of health.
Right now this is what I have written:
import random
def main():
pass
if __name__ == '__main__':
main()
hpRed = 20
hpBlu = 20
def attack():
damage = random.randrange(1,3)
return hpRed - damage
return hpBlue - damage
def fighterRed(name, hpRed):
print(str(name) + " has " + str(hpRed) + " health left.")
def fighterBlue(name, hpBlu):
print(str(name) + " has " + str(hpBlu) + " health left.")
def battle():
fighterRed("Branden",hpRed)
fighterBlue("Alex",hpBlu)
while ((hpRed > 0) and (hpBlu > 0) is True):
attack()
else:
print("The battle is over!")
if (hpRed > 0):
return "Red Player is victorious!"
else:
return "Blue Player is victorious!"
battle()
So far I constantly receive the error "hpRed referenced before assignment". What can I change to get it to properly pass on the value of hpRed and hpBlu?
There were a couple of errors:
You were using two different names: hpBlue and hpBlu
You were returning two values instead of changing the values of the variables you defined.
Your printing functions were just executing 1 time. (Added inside the while so it prints each iteration)
Code:
import random
hpRed = 20
hpBlu = 20
def attack():
global hpRed, hpBlu
damage = random.randrange(1,3)
hpRed = hpRed - damage
hpBlu = hpBlu - damage
def fighterRed(name, hpRed):
print(str(name) + " has " + str(hpRed) + " health left.")
def fighterBlue(name, hpBlu):
print(str(name) + " has " + str(hpBlu) + " health left.")
def battle():
while (((hpRed > 0) and (hpBlu > 0)) is True):
fighterRed("Branden",hpRed)
fighterBlue("Alex",hpBlu)
attack()
else:
print("The battle is over!")
if (hpRed > 0):
return "Red Player is victorious!"
else:
return "Blue Player is victorious!"
battle()
You're not actually making any changes to either player's hp; look at your attack() function and start checking your variables.
The hpRed and hpBlue (which is misspelled in at least one place by the way) variables are defined at the module ("global") level. The names inside the functions are function-local names, which cannot see global variables unless they are explicitly assigned to globals. That would look like this:
def attack():
global hpRed, hpBlue
# rest of your function
While you could do this simply with globals, it's not very good practice. I recommend passing the value into any functions that need it, or putting it in a class so that methods of the class can operate on it.
def attack(hpr, hpb):
# calculate damage, then...
return (hpr - damage, hpb - damage)
You may notice that I changed your return statement. What you'd written wouldn't work the way you wanted it to: once you return, you can't return again from the same method call (that behavior would be more like a generator). If you want to return both the new red HP and the new blue HP, return a tuple containing them both.
This code has some other problems as well-- you're never actually changing the global variables, for instance, and you'll save yourself some headache if you put a print call inside the while loop so you can see how the hp changes.

Categories