Exemple #1
0
    def start_game(self):
        # Create players
        self.players[0] = Player(name=input('Input your name: '))
        self.players[1] = NPC()

        # place ships for both players
        if input("[p]lace ships or [r]andomize positions?: ").lower() == 'p':
            self.place_ships(self.players[0])
        else:
            temp = NPC()
            self.place_ships(temp)
            self.players[0].board = temp.board
            self.players[0].ships = temp.ships

        # place NPCs ships
        self.place_ships(self.players[1])

        # determine who goes first
        turn = random.randint(0, 1)

        while True:
            if self.do_turn(self.players[turn], self.players[1 - turn]):
                turn = 1 - turn
            else:
                break

        print("{} is the winner!".format(self.players[turn].name))
Exemple #2
0
def input_initiative():
    initiative = Initiative()
    print("Enter initiative in form \"[Count] Name [Initiative]\".")
    while True:
        # Get input
        text = input("> ").strip()
        if text == "":
            break
        words = text.split()
        if words[0].isdigit():
            count_specified = True
            entity_count = int(words[0])
            name = words[1].lower()
        else:
            count_specified = False
            name = words[0].lower()
            entity_count = 1

        # If creature name is found in JSON, use it; otherwise, make an Entity object
        try:
            new_entity = NPC(loader.get_npc(name))
            print("Got " + new_entity.name + " stats from JSON.")
        except:
            new_entity = Entity(name.capitalize())

        # Get the initiative roll
        try:
            if count_specified:
                initiative_result = int(words[2])
            else:
                initiative_result = int(words[1])
        except:
            initiative_result = dice.random_int(20)
            try:
                initiative_result += new_entity.ability_modifiers["DEX"]
            except:
                pass
            print("Rolled " + str(initiative_result) + " for initiative.")

        # If count is nonzero
        if words[0].isdigit():
            for i in range(entity_count):
                try:
                    new_entity_instance = NPC(loader.get_npc(name))
                    for c in range(len(new_entity_instance.commands)):
                        new_entity_instance.commands[c] += str(i + 1)
                except:
                    new_entity_instance = Entity(name.capitalize())
                new_entity_instance.name += str(i + 1)
                initiative.add_entity(new_entity_instance, initiative_result)
        # Otherwise, just add it to the order
        else:
            initiative.add_entity(new_entity, initiative_result)
    return initiative
Exemple #3
0
    def create_home(self):

        person = NPC("Person", 100, -1)
        zombie = NPC("Zombie", random.randint(50, 100), random.randint(0, 10))
        vampire = NPC("Vampire", random.randint(100, 200),
                      random.randint(10, 20))
        ghoul = NPC("Ghoul", random.randint(40, 80), random.randint(15, 30))
        werewolf = NPC("Werewolf", 200, random.randint(0, 40))

        npc_index = [person, zombie, vampire, ghoul, werewolf]

        num_npcs = random.randint(0, 10)
        for i in range(num_npcs):
            #print(num_npcs)
            self.monsters.append(npc_index[random.randint(1, 4)])
Exemple #4
0
    def add(self, entitytype, x, y, **parameters):
        if entitytype == "knight":
            self.entities.append(NPC(x, y, self))
            self.npc = self.entities[-1]
        elif entitytype == "fireball" or entitytype == "fireball_2":

            ang = math.atan2(y - self.npc.y, x - self.npc.x)
            spd = 70.0

            if 'ang' in parameters:
                ang = parameters['ang']

            if 'spd' in parameters:
                spd = parameters['spd']

            if entitytype == "fireball":
                self.entities.append(
                    Entity(self, "projectile", x, y, angle=ang, speed=spd))
            if entitytype == "fireball_2":
                self.entities.append(
                    Entity(self, "eprojectile", x, y, angle=ang, speed=spd))
        elif entitytype == "geometry":
            self.entities.append(
                Entity(self,
                       "geometry",
                       x,
                       y,
                       dimensions=(parameters["w"], parameters["h"])))
        elif entitytype == "player":
            self.entities.append(Player(self, x, y, "spaceship"))
            self.player = self.entities[-1]
        elif entitytype == "potato":
            self.entities.append(Potato(self))
        elif entitytype == "smallexplosion":
            self.entities.append(Entity(self, "smallexplosion", x, y))
Exemple #5
0
    def init_npc(self, map):

        all_npc_names = self.db.get_all_npc()

        for data in all_npc_names:
            npc = NPC(self.window, data)
            self.all_npc.append(npc)
    def __setupNPC(self):
        # This is to support the collisions for each node. See the paragraph comment
        # above where we modify the npc's collision node
        #        playerCollisionNP = self.__mainTarget.find("* collision node")

        modelStanding = "models/ralph"
        modelRunning = "models/ralph-run"
        modelWalking = "models/ralph-walk"
        self.__NPC = NPC(modelStanding, {
            "run": modelRunning,
            "walk": modelWalking
        },
                         turnRate=150,
                         speed=15,
                         agentList=self.__globalAgentList,
                         name="Ralph",
                         collisionMask=BitMask32.bit(3),
                         rangeFinderCount=13,
                         adjacencySensorThreshold=5,
                         radarSlices=5,
                         radarLength=0,
                         scale=1.0,
                         massKg=35.0,
                         collisionHandler=self.physicsCollisionHandler,
                         collisionTraverser=self.cTrav,
                         waypoints=self.roomWaypoints)
        self.__NPC.setFluidPos(render, 20, 10, 0)  #-190
        self.__NPC.setScale(render, 1)
        self.__NPC.setTarget(self.__mainTarget)

        self.__NPC.reparentTo(render)
        self.__NPC.start()
    def __init__(self, redis, features={}):
        Generator.__init__(self, redis, features)
        self.logger = logging.getLogger(__name__)

        for field in ['contact', 'npc']:
            if not hasattr(self, field):
                setattr(self, field, NPC(self.redis))
        if not hasattr(self, 'business'):
            setattr(self, 'business', Business(self.redis))

        if not hasattr(self, 'text'):

            for field in ['hook', 'request']:
                if hasattr(self, field):
                    self.template = getattr(self, field) + ' ' + self.template

            for field in ['requirement', 'disclaimer', 'payment']:
                if hasattr(self, field):
                    self.template = self.template + ' ' + getattr(self, field)

            self.template = self.template + ' Contact ' + self.contact.name.fullname
            self.template = self.template + ' at the ' + self.business.name.fullname
            if hasattr(self, 'detail'):
                self.template = self.template + ' ' + self.detail

            self.template += '.'

            self.text = self.render_template(self.template)
            self.text = self.render_template(self.text)
        self.text = self.text[0].capitalize() + self.text[1:]
Exemple #8
0
 def move_to(self, i, j):
     move = self.game_map[i][j]
     if move == '#':
         print "You run into a wall and take 1 damage."
         self.hero.take_damage(1, False)
     else:
         self.i = i
         self.j = j
         self.encounter_odd += 0.05
         if move == 'E':
             print "Congratulations! You've reached the end of this floor!"
             exit(0)
         elif move == 'T':
             self.find_treasure()
             self.game_map[i][j] = ' ' #Removes the treasure chest from the game
         elif move == "S":
             print "Back to start! What now?"
         else:
             #Move into corridor, generate random fight here.
             dice_roll = random.random()
             if dice_roll < self.encounter_odd:
                 #BATTLE!
                 Combat(self.hero, [NPC("Goblin", 1, 10, 1, 2, 0, 20)])
                 self.encounter_odd = 0.0
             elif dice_roll > 0.95:
                 print "Surprise! You found something."
             else:
                 #Move normally
                 print "All is good, keep going!"
                 pass
     """
Exemple #9
0
 def __init__(self, NPCNumber):
     super().__init__()
     self.NPCNumber = NPCNumber
     self.NPCArray = []
     #### Adds the NPC's to each House ####
     for i in range(0, NPCNumber):
         self.NPCArray.append(NPC(randint(0, 4)))
         self.NPCArray[i].add_observer(self)
Exemple #10
0
def chat():
    npc = NPC()
    sentence = input('Say something to ' + npc.name + ': ')
    while sentence != 'quit':
        eliza_speech = npc.process_input(sentence)
        if eliza_speech:
            print(npc.name.upper() + ': ', end='')
            print_speech(eliza_speech)
        sentence = input('YOU: ')
Exemple #11
0
	def __init__(self, name, ship, printer, game):
		"""Stores the information regarding the fire planet."""
		super(Fireplanet, self).__init__(name, "Bracing yourself against the heat, you squint out at the blackened landscape, dotted with pools of lava.", ship, game)
		
		self.crater = Location("10", "there is a path that leads back to where you left your spaceship. You hope it's still there and the crater hasn't eaten it.", "Your spaceship sits behind you, hanging on the edge of a large crater, which glows mysteriously due to the magma inside.", printer, [Event(EventName.on_arrival, 'self.game.printer.pprint("You had to be careful as you landed on Paxak, as the surface is mostly covered in seething lava. Even the ground you can walk on is inhospitible and dangerous. You are glad that you weren\'t born here.")', "10"), Event(EventName.on_sign_read, 'self.game.printer.pprint("The words on the sign are written in a language that speaks of crackling embers and barely controlled aggression. Though the language is not your own, you can read it, albeit with some difficutly. You wish you understood why.")', "1-")])
		ship_item = Item(False, True, False, ["ship", "spaceship", "craft"], "Your spaceship is still there, thank goodness.", "The plating on the bottom looks a little blackened after the descent through the hot atmosphere.", printer)
		crater = Item(False, True, False, ["crater"], "The crater behind the spaceship glows ominously.", "It looks pretty deep. The bottom, far below you, has what looks like a lava spring filling it. You wish you'd spotted a better patch of ground to land on, but this was the closest place to the signs of life you spotted from the air. It'll do for now.", printer)
		sign1 = Sign(self.get_sign_list()[1]["first_sign"], "A metal board attached to a section of small girder protrudes from the ground. You guess that this is the Paxak version of signs.", printer)
		npc1 = NPC(["man1"], "Man1 stands before you.", "As you look at man1, you see man1.", False, False, self.get_npc_speeches(1,0), printer, [], game)
		self.crater.objects = [ship_item, crater, sign1, npc1]
		
		self.base_of_volcano = Location("11", "you see a constant stream of smoke and a hazy glow from the top of a large mountain.", "You look up at the peak of the smoking volcano. You decide not to risk your life venturing up.", printer, []) 
		volcano = Item(False, True, False, ["mountain", "volcano"], "The volcano stands in front of you like a lightly sleeping giant.", "You reason that going to the top would be a pretty quick way to end your life.", printer)
		sign2 = Sign(self.get_sign_list()[1]["second_sign"], "Facing away from the volcano is a second sign, almost red hot from the heated ground.", printer)
		self.npc2 = NPC(["man2"], "Man2 stands before you.", "Perhaps she could get into the volcano?", True, False, self.get_npc_speeches(1,1), printer, [Event(EventName.on_talking, 'self.game.fireplanet.npc2.state = NPCState.task_complete', "11", NPCState.during_task), Event(EventName.on_talking, 'self.game.fireplanet.npc5.state = NPCState.task_complete; self.game.player.get("The deepest heat", "the volcano"); self.game.printer.pprint("You got the deepest heat from the volcano!")', "11", NPCState.after_task)], game)
		self.base_of_volcano.objects = [volcano, sign2, self.npc2]
		
		self.village = Location("12", "you can just see what could be the remains of a settlement.", "You are surrounded by tumbledown houses, broken and split. Debris is strewn from the doorways, as if they were hurriedly deserted.", printer, [Event(EventName.on_arrival, 'self.game.fireplanet.set_path(self.game.fireplanet.village, ("forwards", "forward"), self.game.fireplanet.crater)', "12")])		
		buildings = Item(False, True, False, ["buildings", "houses"], "You realise the houses are glittering slightly in the light of the everpresent lava.", "The houses appear to have been made from a glass like substance, now shattered. It's terrible, but it's also beautiful.", printer)
		sign3 = Sign(self.get_sign_list()[1]["third_sign"], "Just outside the village is another sign, telling more of the story.", printer)
		npc3 = NPC(["man3"], "Man3 stands before you.", "Man3 is a house husband.", False, False, self.get_npc_speeches(1,2), printer, [], game)
		self.village.objects = [buildings, sign3, npc3]
		
		self.lava_pool_edge = Location("13", "you can see a large expanse of lava.", "You go as close to the lava pool as you dare. It is hot.", printer, [])
		pool = Item(False, True, False, ["pool", "lava"], "The pool of lava is constantly in motion, as if being stirred from within.", "The heat of the molten rock is making bubbles in the liquid, and whenever they burst you have to be careful not to get burned.", printer)
		sign4 = Sign(self.get_sign_list()[1]["fourth_sign"], "In danger of being consumed by the spitting lava is a sign.", printer)
		npc4 = NPC(["man4"], "Man4 stands before you.", "Man4 will in fact be a child.", False, False, self.get_npc_speeches(1,3), printer, [], game)
		self.lava_pool_edge.objects = [pool, sign4, npc4]
		
		self.workshop = Location("14", "you spot a small building all on its own.", "The building is the least damaged of all the ones you have seen here, but then it's not made of the same material as the others.", printer, [Event(EventName.on_arrival, 'self.game.fireplanet.set_path(self.game.fireplanet.workshop, ("left",), self.game.fireplanet.crater)', "14"), Event(EventName.on_arrival, 'EventName.planets_visited_before_npcs += "A"', "14")])
		building = Item(False, True, False, ["building", "workshop"], "The small building looks solid and heavily fireproofed, and as if it has had to be rebuilt multiple times.", "The substance the building is made of reminds you of the hardened black rocks you have seen floating within the lava. Inside the building you see a furnace, an anvil, and an iron bucket filled with tools of a blacksmith. This must be the workshop of Paxak.", printer)
		sign5 = Sign(self.get_sign_list()[1]["fifth_sign"], "Stuck on the door is the sign that completes the story.", printer)
		self.npc5 = NPC(["man5"], "Man5 stands before you.", "Man5 owns the forge.", True, True, self.get_npc_speeches(1,4), printer, [Event(EventName.on_talking, 'self.game.fireplanet.npc2.state = NPCState.during_task; self.game.player.karma += 1', "14", NPCState.during_task), Event(EventName.on_talking, 'self.game.player.get("Explosive power", "Paxak"); self.game.player.gun_pieces += 1; self.game.printer.pprint("You got the Explosive Power part of the Ultimate Weapon!"); del(self.game.player.inventory["The deepest heat"]); self.game.printer.pprint("The deepest heat of the volcano was taken away.")', "14", NPCState.after_task)], game)
		self.workshop.objects = [building, sign5, self.npc5]
		
		self.landing_location = self.crater
		self.current_location = self.ship
		for loc in [self.crater, self.base_of_volcano, self.village, self.lava_pool_edge, self.workshop, self.ship]:
			self.add_location(loc)
			
		self.set_path(self.crater, ("left",), self.base_of_volcano)
		self.set_path(self.base_of_volcano, ("left",), self.village)
		self.set_path(self.village, ("left",), self.lava_pool_edge)
		self.set_path(self.lava_pool_edge, ("left",), self.workshop)
Exemple #12
0
    def init_npc(self, map_name):

        map_data = self.db.get_map_npc(map_name)
        map_npc = []

        for data in map_data:
            map_npc.append(data["npc"])

        for npc in map_npc:
            self.all_npc.append(NPC(self.renderer, self.factory, npc))
Exemple #13
0
 def update(self, npc):
     tempNum = self.NPCArray.index(npc)
     print(self.NPCArray[tempNum].get_name(), "has been slain!")
     self.NPCArray.remove(npc)
     self.NPCArray.insert(tempNum, NPC(0))
     self.NPCArray[tempNum].add_observer(self)
     if all(x.get_npcT() is 0 for x in self.NPCArray):
         print("THE MONSTERS ARE DEAD!!!")
         print("Leave and head to another house!")
         super().update(self)
Exemple #14
0
def npcGenerator(aliveNPCDict, maxPopulation, location, race = "human"):
    # Create seed population with 18 year old couples
    for pop in range(int(maxPopulation / 2)):
        if race == "human":
            coupleRace = MiscTables["BasicRaces"].rollTable()[0].lower()
        else:
            pass #TODO
        # Create male and add him to the alive population dictionary
        maleNPC = NPC(race=coupleRace, gender="male", isAlive=True, bornIn=location,
                      age=randrange(conf.ageGroupLimits[coupleRace][1], conf.ageGroupLimits[coupleRace][2]))
        aliveNPCDict[maleNPC.firstName + " " + maleNPC.lastName] = maleNPC

        # Create female and add her to the alive population dictionary
        femaleNPC = NPC(race=coupleRace, gender="female", isAlive=True, bornIn=location,  lastName=maleNPC.lastName,
                        age = randrange(conf.ageGroupLimits[coupleRace][1], conf.ageGroupLimits[coupleRace][2]))
        aliveNPCDict[femaleNPC.firstName + " " + femaleNPC.lastName] = femaleNPC

        # Marry the NPCs
        marryNPCs(maleNPC, femaleNPC)
Exemple #15
0
    def __init__(self, redis, features={}):

        Generator.__init__(self, redis, features)
        self.logger = logging.getLogger(__name__)

        for person in ['npc', 'victim']:
            if not hasattr(self, person):
                setattr(self, person, NPC(self.redis))

        self.headline = self.render_template(self.headline)
        self.lastseen = self.render_template(self.lastseen)
    def start_game(self):
        self.players[0] = NPC()
        self.players[1] = NPC()

        self.place_ships()

        tempPlaya = Player(name="Me")
        tempPlaya.board = self.players[0].board
        tempPlaya.ships = self.players[0].ships
        self.players[0] = tempPlaya

        turn = random.randint(0, 1)

        while True:
            if self.do_turn(self.players[turn], self.players[1 - turn]):
                turn = 1 - turn
            else:
                break

        print("{} is the winner!".format(self.players[turn].name))
Exemple #17
0
    def create_npc(self):
        self.maxCharacterId += 1
        pos_x = random.randint(100, 1024)
        arg = {
            'health': 100,
            'speed': 0.9,
            'position': Coordinate(pos_x, 450),
            'facingDirection': Direction.RIGHT
        }

        npc = NPC(self.maxCharacterId, arg)
        self.actors[self.maxCharacterId] = npc
Exemple #18
0
    def __init__(self, redis, features={}):

        Generator.__init__(self, redis, features)
        self.logger = logging.getLogger(__name__)

        for person in ['npc', 'villain']:
            if not hasattr(self, person):
                setattr(self, person, NPC(self.redis))

        if not hasattr(self, 'text'):
            self.text = self.render_template(self.template)
            self.text = self.render_template(self.text)
        self.text = self.text[0].capitalize() + self.text[1:]
 def selectMode(self):
     value = input("Please enter 1 for vs npc, or 2 for player vs player\n")
     while value != "1" and value != "2":
         os.system('cls')
         value = input(
             "Invalid input. Please enter 1 for vs npc, or 2 for player vs player\n"
         )
     self.vsNPC = value == "1"
     self.player1 = HumanPlayer(1)
     if self.vsNPC:
         self.player2 = NPC(2)
     else:
         self.player2 = HumanPlayer(2)
Exemple #20
0
    def __init__(self, redis, features={}):

        Generator.__init__(self, redis, features)
        self.logger = logging.getLogger(__name__)

        for person in ['victim', 'culprit', 'source', 'believer']:
            if not hasattr(self, person):
                setattr(self, person, NPC(self.redis).name.fullname)

        if not hasattr(self, 'text'):
            self.text = self.render_template(self.template)
            self.text = self.render_template(self.text)
        self.text = self.text[0].capitalize() + self.text[1:]
Exemple #21
0
 def __init__(self):
     self.gui = None  # set at Logic.start()
     self.game_over = False
     self.i_say_queue = []
     self.last_npc_tick = None
     self.tick = 0
     # create rooms
     self.rooms = {}
     self.rooms['execs'] = Room(self, 'execs')
     # create NPCs
     self.npcs = {}  # indexed by title
     for title, name in NAMES.items():
         is_human = title == MY_TITLE
         self.npcs[title] = NPC(self, title, name, is_human)
Exemple #22
0
    def __init__(self, redis, features={}):

        Generator.__init__(self, redis, features)
        self.logger = logging.getLogger(__name__)
        self.generate_features(self.kind)

        self.npc = NPC(redis)

        self.curse_chance_roll = random.randint(1, 100);
        if self.curse_chance_roll < self.curse_chance :
            self.curse = Curse(redis)
        else:
            del self.curse

        self.build_creator()

        text = self.render_template(self.name_template)
        self.name = self.render_template(text)
Exemple #23
0
    def __init__(self, redis, features={}):
        Generator.__init__(self, redis, features)
        self.logger = logging.getLogger(__name__)
        self.generate_features(self.kind)
        self.senses = []

        # originally I was going to move these to a for loop, but the verb
        # doesn't match the variable name, so it would require refactoring
        # of the dataset and every other damn thing. Meh.

        if hasattr(self, 'smell'):
            self.smell = 'you smell ' + self.smell
            self.senses.append(self.smell)
        if hasattr(self, 'sound'):
            self.sound = 'you hear ' + self.sound
            self.senses.append(self.sound)
        if hasattr(self, 'sight'):
            self.sight = 'you see ' + self.sight
            self.senses.append(self.sight)

        if not hasattr(self, 'owner'):
            self.owner = NPC(redis)

        # TODO patrons should be better calculated

        if not hasattr(self, 'patroncount'):
            self.patroncount = random.randint(1, 10)

        # Business is one of the few classes where trailer doesn't start as part of the name
        # So we have to add it here.

        self.name = Name(self.redis, 'business', {'trailer': self.trailer})

        # If maxfloors isn'd designated, set it to 1

        if not hasattr(self, 'maxfloors'):
            self.maxfloors = 1

        # don't set floors if it already exists

        if not hasattr(self, 'floor'):
            self.floor = random.randint(1, int(self.maxfloors))
 def __setupTarget(self):
     modelStanding = "models/ralph"
     modelRunning = "models/ralph-run"
     modelWalking = "models/ralph-walk"
     self.__mainTarget = NPC(modelStanding, {
         "run": modelRunning,
         "walk": modelWalking
     },
                             turnRate=150,
                             speed=0,
                             agentList=self.__globalAgentList,
                             collisionMask=BitMask32.bit(1),
                             name="target",
                             massKg=35.0,
                             collisionHandler=self.physicsCollisionHandler,
                             collisionTraverser=self.cTrav)
     # Make it visible
     self.__mainTarget.reparentTo(render)
     self.__mainTarget.setPos(-20, -10, 0)  #-210
     self.gate.find("**/Cube;+h").setCollideMask(
         ~self.__mainTarget.collisionMask)
Exemple #25
0
    def update(self, dt):
        if self.musicplayer.source == self.musicres[
                self.level][1] and not self.musicplayer.eos_action == 'loop':
            self.musicplayer.eos_action = 'loop'

        for e in self.entities:
            if self.controllable:
                e.update(dt)
            else:
                if not e.entitytype == "NPC":
                    e.update(dt)

        for e in [todel for todel in self.entities if todel.active == False]:
            self.entities.remove(e)

        if self.npc.dead:
            # explosions
            self.entities.remove(self.npc)

            self.entities.append(NPC(random.randint(0, 600), -10, self))
            self.npc = self.entities[-1]
Exemple #26
0
    def __init__(self, redis, features={}):
        Generator.__init__(self, redis, features)
        self.logger = logging.getLogger(__name__)
        if not hasattr(self, 'region'):
            print "noregion!!!"
            self.region = region.Region(self.redis)

        self.gatheringplace = Business(self.redis,
                                       {'kind': 'bus_' + self.gatheringplace})
        if not hasattr(self, 'leader'):
            self.leader = leader.Leader(self.redis, {"location": self})
            #self.leader = Leader(self.redis)

        if not hasattr(self, 'name'):
            self.name = Name(self.redis, 'city')

        self.citizen = NPC(self.redis)

        self.calculate_population()
        self.calculate_racial_breakdown()
        self.select_subraces()
Exemple #27
0
    def __init__(self, redis, features={}):
        Generator.__init__(self, redis, features)
        self.logger = logging.getLogger(__name__)

        if not hasattr(self, 'npc'):
            setattr(self, 'npc', NPC(self.redis))

        if not hasattr(self, 'npcname'):
            setattr(self, 'npcname', self.npc.name.shortname)
        if not hasattr(self, 'npcprofession'):
            setattr(self, 'npcprofession', self.npc.profession)

        if not hasattr(self, 'text'):
            if hasattr(self, 'signature'):
                self.template = self.template + ' The message is signed ' + getattr(
                    self, 'signature')
            if hasattr(self, 'age'):
                self.template = self.template + " You'd guess the message is " + getattr(
                    self, 'age')

            self.text = self.render_template(self.template)
            self.text = self.render_template(self.text)
        self.text = self.text[0].capitalize() + self.text[1:]
Exemple #28
0
 def testNpc(self):
     B = Board(7, 7)
     B.Set(1, 1, 1)
     C = NPC(B)
     for i in range(1, 500):
         C.FirstMove()
         x, y, v = B.Moves[1][0], B.Moves[1][1], B.Moves[1][2]
         self.assertTrue([x, y] != [1, 1])
         self.assertTrue(x >= 0)
         self.assertTrue(x < 7)
         self.assertTrue(y >= 0)
         self.assertTrue(y < 7)
         B.Set(x, y, 0, True)
     self.assertEqual(C.hScore(1, 1, 1), 1)
     B.Set(1, 2, 1)
     self.assertEqual(C.hScore(1, 1, 1), 2)
     B.Set(1, 3, 1)
     self.assertEqual(C.hScore(1, 1, 1), 3)
     B.Set(1, 4, 1)
     self.assertEqual(C.hScore(1, 1, 1), 4)
     B.Set(1, 5, 1)
     self.assertEqual(C.hScore(1, 1, 1), 5)
     # Same idea applies for vScore, d1Score, d2Score, therefore we assume that if this works then those work as well
     # Checking the defense
     B.Set(1, 5, 0, True)
     B.Set(1, 4, 0, True)
     x, y = C.FindBlockMove()
     self.assertEqual(x, 1)
     self.assertEqual(y, 0)
     # Checking the offensive
     B.Set(2, 1, -1)
     B.Set(2, 2, -1)
     B.Set(2, 3, -1)
     x, y, v = C.FindBestMove()
     self.assertEqual(x, 2)
     self.assertEqual(y, 0)
     self.assertEqual(v, 4)
Exemple #29
0
 def create_shop_keeper(self):
     print('Enter the Shopkeepers name: ')
     npc_name = input()
     self.shop_keeper = NPC(npc_name, "Shop Keeper")
Exemple #30
0
import time
import ntpath
import pygame
from spriteanimation import SpriteAnimation
from npc import NPC
from player import Player

pygame.init()
pygame.joystick.init()
for x in range(pygame.joystick.get_count()):
    joystick = pygame.joystick.Joystick(x)
    joystick.init()

player1 = Player(initial_action="down", player_id=1)
player2 = Player(initial_action="down", player_id=2)
player_pc = NPC(initial_action="down", player_id=0)
power1 = SpriteAnimation(initial_action="void")
power2 = SpriteAnimation(initial_action="void")
power3 = SpriteAnimation(initial_action="void")
power_dispute = SpriteAnimation(initial_action="void")
power_dispute2 = SpriteAnimation(initial_action="void")
effects = SpriteAnimation(initial_action="void")
effects2 = SpriteAnimation(initial_action="void")
clock = pygame.time.Clock()

WHITE = (255, 255, 255)
YELLOW = (255, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)