0

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!

1
  • 2
    Please use while True instead of while 0 != 1. It's ... easier on the eyes, to say the least. Commented Oct 31, 2014 at 18:11

1 Answer 1

1

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.