Reputation:
I would like to start 4 independent threads which are basically methods of a class. What am I doing wrong in the code below:
from threading import Thread
import time
import random
class Creature:
def __init__(self, name):
self.name = name
def melee(self, level):
self.melee = level
def shielding(self, level):
self.shielding = level
def health(self, total):
self.health = total
def attack(self, attacker, opponent):
while 0 != 1:
power = random.randint(1, attacker.melee)
resistance = random.randint(1, opponent.shielding)
resultant = power - resistance
if resistance > 0:
opponent.health -= resistance
if opponent.health < 0:
print(opponent.name, " is dead")
print("Opponent's health ", opponent.health)
quit()
else:
print(attacker.name, " delivered an attack of ", resistance)
print("Opponent's health ", opponent.health)
def healing(self, healed):
while 0 != 1:
if healed.health <= 0:
if healed.health < 50:
life = random.randint(1, 50)
healed.health += life
if healed.health > 100:
healed.health = 100
print(healed.name, " has healed and now has a health of ", self.health)
Monster = Creature("Wasp")
Monster.health = 100
Monster.melee = 30
Monster.shielding = 15
Player = Creature("Knight")
Player.health = 100
Player.melee = 25
Player.shielding = 20
t1 = Thread(target=Player.attack(Monster, Player))
t1.start()
t2 = Thread(target=Monster.attack(Player, Monster),)
t2.start()
t3 = Thread(target=Player.healing(Player), args=())
t3.start()
t4 = Thread(target=Monster.healing(Monster), args=())
t4.start()
Somehow I am doing something wrong since only the t1 gets started. Why does the program start only t1? :-(
Thanks!
Upvotes: 0
Views: 74
Reputation: 47968
The problem(s) in your code are all demonstrable in this one line:
t1 = Thread(target=Player.attack(Monster, Player))
The trouble is that you're calling Player.attack
, not passing it to the Thread constructor. Your attack method never returns, so you never get past the attempt to create the first Thread. You'd want to do something like this:
t1 = Thread(target = Player.attack, args = (Monster, Player))
Upvotes: 1