def enemy_encounter(self, event, button):
        self.enter_room(button, "battle")

        battle_window = Toplevel(self.board)
        app = Battle(self.party, self.cheat_mode,
                     self.text_log, self.party_text_log,
                     self.random_event_gen.get_enemy(), battle_window, self)
Example #2
0
    def check_new_tile(self, tile_grid):
        battle = None
        # Checks new location of hero to see if it is a combat area
        boolean = tile_grid.check_combat_area((self.x_loc, self.y_loc),
                                              self.width, self.height)
        if boolean is True:
            number = random.randint(0, 99)
            if number < self.combat_chance:
                battle = Battle.Battle(self,
                                       Enemy.Wolf(100, 100, 100, 1, 1, 1))
                self.combat_chance = 0
            else:
                self.combat_chance += 1

        # Checks new location of hero to see if it is a load point
        boolean, tile = tile_grid.check_load_points((self.x_loc, self.y_loc),
                                                    self.width, self.height)
        # Returns hero sprite, hero_loc, and map_name / None
        if boolean is True:
            self.x_loc = tile.new_loc_x * tile_grid.tile_size
            self.y_loc = (tile.new_loc_y * tile_grid.tile_size) - (
                self.height - self.width)  # Extra hero height
            return tile.new_map, battle
        else:
            return None, battle
Example #3
0
    def runBattle(self, enemyNames, background, canFlee=True):

        combatants = list(self.partyManager.team)

        enemyElements = self.enemiesFile.getElementsByTagName("enemy")
        for name in enemyNames:
            found = filter(lambda e: str(e.getAttribute("name")) == name,
                           enemyElements)
            if len(found):
                combatants += [Enemy.Enemy(found[0])]
            else:
                self.logManager.error("No enemy called " + name +
                                      " found in " + self.enemiesLocation +
                                      ".")

        # Choose a nice battle music.
        playingMusic = self.audioManager.getPlayingMusic()
        self.audioManager.playMusic("music/battle" +
                                    str(self.mathManager.randInt(1, 4)) +
                                    ".ogg")

        battle = Battle.Battle(combatants, background, canFlee)

        self.battleIntro()
        battle.run()

        self.audioManager.playMusic(playingMusic)

        return battle.won
 def checkEnemyCollisions(self):
     for enemy in self.active_enemies.sprites():
         if pygame.sprite.collide_rect(self.player, enemy) == True:
             self.battle = True
             self.battleEvent = Battle(self, self.player, enemy, 0, 150)
             self.battleEvent.add(self.active_battle)
             ANIMATE_KEYSTROKES = pygame.USEREVENT + 1
             pygame.time.set_timer(ANIMATE_KEYSTROKES, 125)
             ANIMATE_ENEMY = pygame.USEREVENT + 3
             pygame.time.set_timer(ANIMATE_ENEMY, 125)
    def doBattle(self, teamOne, teamTwo):
        # create instance of battle, pick a random pokemon from each team,
        # and have them fight
        battle = Battle.Battle(teamOne, teamTwo)
        battle.setFighterOne(battle.getTeamOne().chooseRandomFighter())
        battle.setFighterTwo(battle.getTeamTwo().chooseRandomFighter())

        # perform battle, print results.
        battle.startBattle()
        self.addBattle(battle)
Example #6
0
	def create_game(self) :
		client, team = self.ask_to_play.pop(0)
		game_id = free_game_ids.pop(0)
		new_battle = Battle.Battle(game_id, client, team) # To MODIFY
		self.games[game_id] = new_battle
		new_battle.step = "new_game"

		msg = {"gid" : game_id,
			"step" : "new_game",
			"grid" : new_battle.grid.get_serializable_grid(),
			"state" : new_battle.get_state()}
		client.send(msg)
Example #7
0
def initiatebattle(enemy):
    variables.settings.state = "battle"
    classvar.player.change_of_state()
    enemy.sethealth()
    enemy.enterbattle()
    classvar.player.heal()
    classvar.battle = Battle.Battle(enemy)

    variables.dirtyrects = [Rect(0,0,variables.width,variables.height)]
    play_effect("engagebattle")
    stop_music()

    if variables.settings.autosavep:
        save(False);
        variables.saved = True
Example #8
0
import random
from Battle import *


class RandTrainer(Trainer):
    def Act(self):
        return random.randint(0, 3)


if __name__ == "__main__":
    print("Let's get ready to Battle!")
    bulba = AllPokemon.MakeNewPokemon(1, 50)
    bulba.SetMoves(["Vine Whip", "Tackle"])
    pika = AllPokemon.MakeNewPokemon(25, 50)
    pika.SetMoves(["Thunder Shock", "Tackle"])

    gary = RandTrainer("Gary", bulba)
    ash = RandTrainer("Ash", pika)

    randBattle = Battle(gary, ash)
    randBattle.Battle(20)
Example #9
0
    def load(scenarioFilename):
        scenarioFile = file(scenarioFilename, "rU")
        scenarioText = scenarioFile.read()
        scenarioFile.close()

        globalVars = {}
        localVars = {}

        module = compile("from engine.Unit import MALE, FEMALE, NEUTER",
                         "Unit.py", "exec")
        eval(module, globalVars)
        module = compile("from engine.Faction import Faction",
                         "Faction.py", "exec")
        eval(module, globalVars)
        
        for m in ["Light", "Battle"]:
            module = compile("import engine.%s as %s" % (m, m), m, "exec")
            eval(module, globalVars)       
        compiled = compile(scenarioText, scenarioFilename, 'exec')

        eval(compiled, globalVars, localVars)
        scenarioData = localVars
        
        if scenarioData['VERSION'] != 1:
            raise Exception("Scenario version %d not supported" %
                            scenarioData["VERSION"])

        # Required fields: map 
        m = Resources.map(scenarioData['MAP'])

        # Load ending conditions
        endingConditions = [Battle.NEVER_ENDING]
        if scenarioData.has_key('ENDING_CONDITIONS'):
            endingConditions = scenarioData['ENDING_CONDITIONS']

        # Load lights
        if scenarioData.has_key('LIGHTING'):
            lightEnv = scenarioData['LIGHTING']
        else:
            lightEnv = Light.defaultEnvironment()

        # Load units
        units = []
        if scenarioData.has_key('FACTIONS'):
            for f in scenarioData['FACTIONS']:
                faction = f.faction()
                for u in f.units():
                    (unitFile, (x, y)) = u
                    u = Resources.unit(unitFile)
                    m.squares[x][y].setUnit(u)
                    u.setFaction(faction)
                    units.append(u)

        # Music
        music = 'barbieri-battle'
        if scenarioData.has_key('MUSIC'):
            music = scenarioData['MUSIC']

        # Create battle
        battle = Battle.Battle(endingConditions, units, m)
   
        return Scenario(m, units, lightEnv, battle, None, music)
Example #10
0
from characters import Human_Character
import Battle
import Item
import Shopping
from constants.Game_States import GAME_OVER, CHOOSING_PATH, IN_BATTLE, SHOPPING
from display_utilities.GraveStone import displayGrave
from Bestiary import returnEnemyByTier
import pickle

shopping_station = Shopping.Shopping()
battle_station = Battle.Battle()
smol_sword = Item.Item('smol sword', 3, [], 9)
medium_sword = Item.Item('medium sword', 5, [], 9)
htb_sword = Item.Item("'Honestly too big' sword", 9, [], 9)

player_name = input('Enter Character Name: ')

player_character = Human_Character.HumanCharacter(player_name, 7, 10, 7, 2, 11,
                                                  0, [medium_sword])

game_status = CHOOSING_PATH

while (game_status != GAME_OVER):
    print('Current Gold: ' + str(player_character.gold))
    print('Current Exp: ' + str(player_character.exp))
    choice = input(
        'Enter Battle (b), Shopping (s), Save (sg), Load (lg) or Inventory (i): '
    ).lower()
    if choice == 'b':
        # Battle
        game_status = IN_BATTLE
Example #11
0
    def update(self):
        toRemove = []

        # Processes messages received on the server
        self.networkManager.connectionLock.acquire()
        for client in self.networkManager.clients:
            client.aliveTimer += client.aliveClock.tick()
            if client.aliveTimer > 10000:  # If more than 10 seconds have passed since the last update, remove the client
                print(client.aliveTimer)
                toRemove.append(client)

            client.messageLock.acquire()
            while len(client.messageQueue) > 0:
                data = client.messageQueue.popleft()
                command = data[0]

                if command == "Alive":
                    client.aliveTimer = 0

                elif command == "Disconnect":
                    toRemove.append(client)

                elif command == "Login":
                    client.name = data[1]
                    '''
                    Generate 3 Pokemon to send to the client
                    For now, I'm just using placeholder ints 0, 1, and 2
                    client.draft = draftPokemans()
                    '''

                    client.draft = []  # clear draft
                    for i in range(3):  #new draft
                        r = random.randint(0, 4)  #random class
                        g = random.randint(0, 1)  #random gender
                        client.draft.append(pokeman(r, g))

                    content = ["Draft", client.draft]
                    client.sendPacket(content)

                elif command == "Draft":
                    index = data[1]
                    '''
                    Keep track that the client has chosen a particular pokeman
                    '''
                    client.pokemans.append(client.draft[int(index)])

                    # If the client does not have 3, then send another draft
                    # Remember that we need to reset the pokemans list to []
                    # to eliminate length problems!
                    if len(client.pokemans) < 3:
                        client.draft = []  # clear draft
                        for i in range(3):  #new draft
                            r = random.randint(0, 4)  #random class
                            g = random.randint(0, 1)  #random gender
                            client.draft.append(pokeman(r, g))
                        content = ["Draft", client.draft]
                        client.sendPacket(content)

                    # Else put the client into the queue
                    else:
                        client.draft = []  # Resets draft
                        self.waitingQueue.append(client)
                elif command == "Battle":
                    client.ready = True
                    client.waitingCommand = [data[1], data[2]]
                    content = ["BattleWait"]
                    client.sendPacket(content)

            client.messageLock.release()

        for client in toRemove:
            print('Removed:', client.addr)
            client.disconnect()
            try:
                self.waitingQueue.remove(client)
            except:
                pass

            try:
                self.networkManager.clients.remove(client)
            except:
                pass

            battleToRemove = None
            winner = None
            for battle in self.battles:
                if client == battle.client1:
                    winner = battle.client2
                    battleToRemove = battle
                    break
                elif client == battle.client2:
                    winner = battle.client1
                    battleToRemove = battle
                    break

            if battleToRemove:
                # Also send the other player a packet that the game has been disconnected
                self.battles.remove(battleToRemove)

                winner.waitingCommand = []
                winner.ready = False
                winner.win = False
                winner.lose = False
                winner.sendPacket(["Result", "Win"])
                self.waitingQueue.append(winner)

        self.networkManager.connectionLock.release()

        while len(self.waitingQueue) >= 2:
            client1 = self.waitingQueue.popleft()
            client2 = self.waitingQueue.popleft()
            self.battles.append(Battle(client1, client2))
            content = ["BattleStart", client2.pokemans[0], client2.name]
            client1.sendPacket(content)
            content = ["BattleStart", client1.pokemans[0], client1.name]
            client2.sendPacket(content)
        for battle in self.battles:
            '''
            Battle will contain the GameState that will be updated
            '''
            battle.update()
            if battle.over == True:
                battle.over = False
                if battle.client1.lose == True:
                    client = battle.client1
                    winner = battle.client2
                else:
                    client = battle.client2
                    winner = battle.client1
                client.waitingCommand = []
                client.ready = False
                client.lose = False
                client.win = False
                winner.waitingCommand = []
                winner.ready = False
                winner.win = False
                winner.lose = False
                winner.sendPacket(["Result", "Win"])
                for p in winner.pokemans:
                    p.current = p.stats[5]
                client.sendPacket(["Result", "Loss"])
                client.draft = []  # clear draft
                client.pokemans = []  #clears pokeman
                for i in range(3):  #new draft
                    r = random.randint(0, 4)  #random class
                    g = random.randint(0, 1)  #random gender
                    client.draft.append(pokeman(r, g))
                content = ["Draft", client.draft]
                client.sendPacket(content)
                self.waitingQueue.append(winner)
                self.battles.remove(battle)
Example #12
0
subreddit = reddit.subreddit('CenturyofBlood')
for comment in subreddit.stream.comments(skip_existing=False):
    comment.refresh()
    if (re.search('/u/maesterbot', comment.body, re.IGNORECASE)
            and comment.id not in comments_replied_to
        ):  #Make sure we're tagged in order to run. Non caps-sensitive.
        comments_replied_to.append(comment.id)

        if (re.search("Naval Battle", comment.body, re.IGNORECASE)):
            Globals.battleType = "Naval"
            battleInfo = re.match(
                "(.*) ([\+\-]\d)\n+(.*) (\d\d\d\d) ([\+\-]\d\d)\n+(.*) ([\+\-]\d)\n+(.*) (\d\d\d\d) ([\+\-]\d\d)",
                comment.body)
            if (battleInfo):
                print("Running Naval battle")
                battle = Battle.Battle()
                if (re.search("Dramatic Mode", comment.body, re.IGNORECASE)):
                    print("Dramatic")
                    lastcomment = comment
                    comments_replied_to.append(lastcomment.id)
                    for roundCount in battle.run(battleInfo).split("---"):
                        try:
                            lastcomment = lastcomment.reply(roundCount)
                            comments_replied_to.append(lastcomment.id)
                            with open("comments_replied_to.txt", "w") as f:
                                for comment_id in comments_replied_to:
                                    f.write(comment_id + "\n")
                        except:  #Shouldn't happen too much, but in case we get rate limited.
                            print("Rate limited. Sleeping for 6 minutes.")
                            time.sleep(360)
                            lastcomment = lastcomment.reply(roundCount)
Example #13
0
pkm1 = Pokemon("Treecko", Grass, NONE, pkm2_stats, 5, 65, "Parabolic")
pkm2 = Pokemon("Torchic", Fire, NONE, pkm1_stats, 5, 65, "Parabolic")

#ATTACKS
pkm1.setAttacks([
    Attack("Destructor", Normal, PHYSICAL, 35, 40, 100),
    Attack("Malicioso", Normal, STATE, 30, 0, 100)
])
pkm2.setAttacks([
    Attack("Arañazo", Normal, PHYSICAL, 35, 40, 100),
    Attack("Gruñido", Normal, STATE, 40, 0, 100)
])

jugador.addPokemon(pkm1)

#BATTLE

batalla = Battle(jugador, pkm2, "s")

while not batalla.Huir() and not batalla.is_finished():
    batalla.Comando()
    ##batalla.combat(batalla.pokemon1, batalla.pokemon2)

print("El combate a finalizado")

if batalla.Huir() == False:
    batalla.Calculation_EXP()
else:
    print("Has huido")
    batalla.ResetHuida()
        def get_more_information_with_intimidation(self, condition):

            if "Persuasion" not in self.skill_performed:
                prompt()
                print("> You head to their table"), sec(2)
                prompt()
                print("* I hear you lads got into a bit of pickle *"), sec(2)
                print("\n* Now for reasons I can't be bothered to explain *"
                      ), sec(2)
                print("\n* I need to know what happened and where *"), sec(2)
                print("\n* Don't waste my time *"), sec(2)

            if condition is True:
                prompt()
                print("|Human 3| ~ Of course, . ~"), sec(2)
                print("\n|Human 3| ~ We were coming down Lapque ~"), sec(2)
                print(
                    "\n|Human 3| ~ The Resistance took our trailer and all our stuff ~"
                ), sec(2)
                print("\n|Human 3| ~ They jumped out on us near Lillies River"
                      ), sec(2)
                print("\n|Human 2| ~ We're lucky to be alive ~"), sec(2)
                prompt()
                print("* I'd say *"), sec(2)
                prompt()
                print("\n> You head back to your table")
                self.get_rest()
            else:

                prompt()
                print("|Ork| ~ Your brave little sod ~"), sec(2)
                print("\n|Human 1| ~ Go f**k yourself ~"), sec(2)
                prompt()
                print(
                    "> You've tried to intimidate the group not the best idea given thier numbers"
                ), sec(3)
                print(
                    "\n> The ork has become defensive and get's up from his seat."
                ), sec(2)
                print("\n> With a weapon in hand")

                prompt()
                outcome = Battle("Jurafa").encounter()
                sec(3)
                prompt()
                if outcome == "Fight Difused":
                    print("* I'm not looking to cause any trouble *"), sec(2)
                    print(
                        "\n* Just needed to be pointed in the right direction"
                    ), sec(2)
                    print("\n* But I'll figure it out. *"), sec(2)
                    prompt()
                    print("> You've avoided having a fight"), sec(2)
                    prntt("\n> You move towrds your table"), sec(2)
                    self.information_gathered = False

                elif outcome == "PC Dead":
                    print("> You suffer a slow and painfull death"), sec(2)
                    self.information_gathered = None

                    #Call Check Point

                elif outcome == "NPC Dead":
                    print(
                        "> The death of their comrad has made them very talkative"
                    ), sec(2)
                    prompt()

                    print("|Human 3| ~ We were coming down Lapque ~"), sec(2)
                    print(
                        "\n|Human 3| ~ The Resistance took our trailer and all our stuff ~"
                    ), sec(2)
                    print(
                        "\n|Human 3| ~ They jumped out on us near Lillies River"
                    ), sec(2)
                    print("\n|Human 2| ~ We're lucky to be alive ~"), sec(2)
                    prompt()
                    print("* Right you are *"), sec(2)
                    print(
                        "\n* Sorry about your friend he was a little full of himself *"
                    ), sec(2)
                    self.information_gathered = True

                elif outcome == "NPC Unconsious":
                    print("> Thier unconious guard is lying next to them"
                          ), sec(2)
                    print("\n> They seem ready to start talking"), sec(2)
                    prompt()
                    print("* So where were we? *"), sec(2)
                    prompt()
                    print("|Human 3| ~ We were coming down Lapque ~"), sec(2)
                    print(
                        "\n|Human 3| ~ They jumped out on us near Lillies River"
                    ), sec(2)
                    print(
                        "\n|Human 3| ~ The Resistance they took our trailer and all our stuff ~"
                    ), sec(2)
                    print("\n|Human 2| ~ We're lucky to be alive ~"), sec(2)
                    prompt()
                    print("* Right you are"), sec(2)
                    print("\n* I'd higher a few extra guards next time *"
                          ), sec(2)
                    print("\n* This ones definetly no good *"), sec(2)
                    self.information_gathered = True

                elif outcome == "PC Revived":
                    print(
                        "> You took alot of damage to continue fight would be risky"
                    ), sec(2)
                    print("\n> You return back to your table."), sec(2)
                    self.information_gathered = False

                self.get_rest()
Example #15
0
pkm1 = Pokemon("Treecko", Grass, NONE, pkm2_stats, 5, 65)
pkm2 = Pokemon("Torchic", Fire, NONE, pkm1_stats, 5,
               65)  ##nombre, tipo1, tipo2, nivel

#ATTACKS
pkm1.attacks = [
    Attack("Destructor", Normal, PHYSICAL, 35, 40, 100),
    Attack("Malicioso", Normal, STATE, 30, 0, 100)
]
pkm2.attacks = [
    Attack("Arañazo", Normal, PHYSICAL, 35, 40, 100),
    Attack("Gruñido", Normal, STATE, 40, 0, 100)
]

#BATTLE

batalla = Battle(pkm1, pkm2, "s")

while not batalla.Huir and not batalla.is_finished():

    batalla.Comando()
    ##batalla.combat(batalla.pokemon1, batalla.pokemon2)

print("El combate a finalizado")

if batalla.Huir == False:
    batalla.Calculation_EXP()
else:
    print("Has huido")
    batalla.huir = False
Example #16
0
player.inventory.addItem(magicBow)
player.inventory.addItem(fireSword)

player.equip(
    utils.getChoice("Choose weapon to equip:", player.inventory.items()))

bronzeHead = Armor("Bronze Helmet", Stats(Con=1), 1, armorType.Head)
bronzeGloves = Armor("Bronze Gloves", Stats(Con=1), 1, armorType.Gloves)
bronzeChest = Armor("Bronze Chest", Stats(Con=1), 1, armorType.Chest)
bronzeLeggings = Armor("Bronze Leggings", Stats(Con=1), 1, armorType.Leggings)
bronzeBoots = Armor("Bronze Boots", Stats(Con=1), 1, armorType.Boots)

player.equip(bronzeHead)
player.equip(bronzeGloves)
player.equip(bronzeChest)
player.equip(bronzeLeggings)
player.equip(bronzeBoots)
print(player.equipment)

player.potionsPocket.addPotion(Potion(0.25))
player.potionsPocket.addPotion(Potion(0.33))
#print(player.potionsPocket)

Battle(player, [dragonMonster, puppyMonster])

# TODO Что нужно сделать
# Quest / QuestJournal
# SpellBook
# City
Example #17
0
#-*- coding: utf-8 -*-

from Player import *
from Battle import *
from Enemys import *

player = Player("wei", 10, 10, 10, 10, 10, 10, 0, 10, 1)

enemy = Enemy2("enemy2", 200)

enemy.action(0, player)
print "some sentence of gmae. blbl......"

print "That is too bad. Your meet a monster......"

print player._hp, enemy._hp
a = Battle(player, enemy).call()

if a:
    print "Congratulation! You Win!"
else:
    print "...."
Example #18
0
from Battle import *
batlle = Battle("Ali", "Abue")
Example #19
0
import LCDDrawer
import DrawableObject
import UI
import Battle
import Enemies
import Title
import Controller
import Player
import sys

p1 = Player.Player(50, 20, 10, 10, 10, 10, 10, portrait_num=1)
battle = Battle.Battle(player=p1,
                       enemy1=Enemies.Enemy('Medusa Head', 15, 5, 10, 10,
                                            'medusa'),
                       enemy2=Enemies.Enemy('Skeleton', 15, 5, 5, 10,
                                            'skeleton'),
                       enemy3=Enemies.Enemy('Skeleton', 15, 5, 5, 10,
                                            'skeleton'))
#title = Title.Title()
p1.battle = battle

RUNNING = True

LCDDrawer.draw_objects()
LCDDrawer.refresh_screen()

while RUNNING:
    LCDDrawer.draw_objects()
    LCDDrawer.refresh_screen()
    battle.battle_input()
Example #20
0
class Map:
    ch = Character()
    b = Battle()

    def __init__(self):
        #instance variable grid
        #world initialized with saved playerdata
        self.grid = [
            ["#", "~", "~", "#", "~"],
            ["#", "~", "~", "~", "~"],
            ["~", "~", "#", "~", "~"],
            ["~", "#", "~", "~", "#"],
        ]
        if self.ch.isInTable() == True:
            self.drawPlayer(self.ch.getCurrent()['row'],
                            self.ch.getCurrent()['col'])
        else:
            self.drawPlayer(1, 2)

    def drawGrid(self):
        print("    0 1 2 3 4")
        rowNum = -1
        for r in self.grid:
            rowNum += 1
            print(rowNum, "|", r[0], r[1], r[2], r[3], r[4])

    def getPlayerPos(self):
        #Returns tuple which contains player position
        #Should return 1,2
        r = -1
        c = -1
        for row in self.grid:
            r += 1
            for col in row:
                c += 1
                if c == 5:
                    c -= 5
                if col == "p":
                    return r, c

    def isPlayerInWorld(self):
        r = -1
        c = -1
        for row in self.grid:
            r += 1
            for col in row:
                c += 1
                if c == 5:
                    c -= 5
                if col == "p":
                    return True
            return False

    def shouldSpawnEnemy(self):
        if self.isDangerous(self.getPlayerPos()[0],
                            self.getPlayerPos()[1]) == False:
            self.b.startBattle()

    def isDangerous(self, inRow, inCol):
        if self.grid[inRow][inCol] == "#":
            return True
        else:
            return False

    def drawPlayer(self, r, c):
        self.grid[r][c] = "p"

    def movePlayer(self, byRow, byCol):
        row = self.getPlayerPos()[0]
        col = self.getPlayerPos()[1]
        self.grid[row][col] = "."  # tiles already travelled notated with a .
        if row > 3 or col > 3:
            print("Can't move there.")
        else:
            self.grid[row + byRow][col + byCol] = "p"

    def movePlayerUp(self):
        self.movePlayer(-1, 0)

    def movePlayerDown(self):
        self.movePlayer(1, 0)

    def movePlayerRight(self):
        self.movePlayer(0, 1)

    def movePlayerLeft(self):
        self.movePlayer(0, -1)
Example #21
0
def blankMap(map):
    return Scenario(map, [], Light.defaultEnvironment(),
                    Battle.Battle([Battle.NEVER_ENDING], [], map),
                    None,
                    '')
Example #22
0
def ExploreRegion(player, region):
    os.system("cls")
    Exp = "You are currently in " + region["Name"] + " with " + str(
        region["Unexplored Regions"]) + " explored out of " + str(
            region["Total Regions"])
    while 0 < region["Unexplored Regions"] <= region["Total Regions"]:
        print("1>  ")
        itp = input(
            "(a)ssess,(e)xplore,(i)nspect,(h)eal,(m)ana,(p)ass,(q)uit>  ")
        Act = 0
        while itp not in list("aAeEhHiImMqQ"):
            player = act.ModifyPlayer(player)
            itp = input(
                "(a)ssess,(e)xplore,(i)nspect,(h)eal,(m)ana,(p)ass,(q)uit>  ")
        if itp in ["q", "Q"]:
            quit()
        elif itp in ["p", "P"]:
            pass
        elif itp in ["a", "A"]:
            act.SelfAssessment(player)
        elif itp in ["m", "M"]:
            player = btl.RestoreMana(player)
        elif itp in ["h", "H"]:
            player = btl.Heal(player)
        elif itp in ["i", "I"]:
            os.system("cls")
            print(Exp)
            act.DisplayInventory(player)
            Inv = player["Inventory"]
            itp = input(
                "now what? (s)ocket gems, (u)nsocket gems, (e)quip, u(n)quip, (b)ack>   "
            )
            if itp in ["b", "B"]:
                pass
            elif itp in ["e", "E", "n", "N"]:
                player = act.EquipItem(player)
                itp = 0
            elif itp in ["s", "S"]:
                print("Socket what? (E)quips, (I)nventory")
                itp = input(">   ")
                if itp in ["e", "E"]:
                    ky = ""
                    types = "(w/W)eapon 1, (w/W)eapon 2, (h/H)elm, (wr/Wr)ists,(f/F)eet, (ar/Ar)ms, (l/L)egs, (c/C)hest, (r/R)ing #(1-4) = (r/R)#, (i)nventory"
                    thing = clts.OrderedDict()
                    itp = input(types + ">   ")
                    if itp in ["w1", "W1"]:
                        ky = "Weapon 1"
                        thing = player[ky]
                    elif itp in ["w2", "W2"]:
                        ky = "Weapon 2"
                        thing = player[ky]
                    elif itp in ["h", "H"]:
                        ky = "Helm"
                        thing = player["Helm"]
                    elif itp in ["wr", "Wr", "WR"]:
                        ky = "Wrists"
                        thing = player["Wrists"]
                    elif itp in ["c", "C"]:
                        ky = "Chest"
                        thing = player["Chest"]
                    elif itp in ["ar", "Ar", "AR"]:
                        ky = "Arms"
                        thing = player["Arms"]
                    elif itp in ["l", "L", "lg", "Lg", "LG"]:
                        ky = "Legs"
                        thing = player["Legs"]
                    elif itp in ["f", "F"]:
                        ky = "Feet"
                        thing = player["Feet"]
                    elif itp in ["r1", "R1"]:
                        ky = "Ring 1"
                        thing = player["Ring 1"]
                    elif itp in ["r2", "R2"]:
                        ky = "Ring 2"
                        thing = player["Ring 2"]
                    elif itp in ["r3", "r3"]:
                        ky = "Ring 3"
                        thing = player["Ring 3"]
                    elif itp in ["r4", "R4"]:
                        ky = "Ring 4"
                        thing = player["Ring 4"]
                    print("what gem?")
                    InvGem = thing["Gems"]
                    itp = input("0-" + str(len(InvGem)) + ">   ")
                    while not 0 <= int(itp) < len(InvGem):
                        itp = input("0-" + str(len(InvGem)) + ">   ")
                    gem = thing["Gems"][int(itp)]
                    print("Proceed? (y/n)")
                    itp = input(">   ")
                    while itp not in ["y", "Y"]:
                        itp = input(">   ")
                    player[ky] = act.SocketGem(thing, gem)
                    del gem, ky
                elif itp in ["i", "I"]:
                    itp = input("0-" + str(len(Inv)) + ">   ")
                    while not 0 <= int(itp) < len(Inv):
                        itp = input("0-" + str(len(Inv)) + ">   ")
                    thing = Inv[int(itp)]
                    print("what gem?")
                    InvGem = list(filter(lambda x: x["Type"] == "Gem", Inv))
                    itp = input("0-" + str(len(InvGem)) + ">   ")
                    while not 0 <= int(itp) < len(InvGem):
                        itp = input("0-" + str(len(InvGem)) + ">   ")
                    gem = InvGem[int(itp)]
                    print("Proceed? (y/n)")
                    itp = input(">   ")
                    if itp in ["y", "Y"]:
                        Thing = act.SocketGem(thing, gem)
                        Inv[Inv.index(thing)] = Thing
                    del InvGem
            elif itp in ["u", "U"]:
                print("Unsocket from what? (e)quips, (i)nventory")
                itp = input(">   ")
                if itp in ["e", "E"]:
                    ky = ""
                    thing = clts.OrderedDict()
                    itp = input(">   ")
                    if itp in ["w1", "W1"]:
                        ky = "Weapon 1"
                        thing = player[ky]
                    elif itp in ["w2", "W2"]:
                        ky = "Weapon 2"
                        thing = player[k]
                    elif itp in ["h", "H"]:
                        ky = "Helm"
                        thing = player["Helm"]
                    elif itp in ["wr", "Wr", "WR"]:
                        ky = "Wrists"
                        thing = player["Wrists"]
                    elif itp in ["c", "C"]:
                        ky = "Chest"
                        thing = player["Chest"]
                    elif itp in ["ar", "Ar", "AR"]:
                        ky = "Arms"
                        thing = player["Arms"]
                    elif itp in ["lg", "Lg", "LG"]:
                        ky = "Legs"
                        thing = player["Legs"]
                    elif itp in ["f", "F"]:
                        ky = "Feet"
                        thing = player["Feet"]
                    elif itp in ["r1", "R1"]:
                        ky = "Ring 1"
                        thing = player["Ring 1"]
                    elif itp in ["r2", "R2"]:
                        ky = "Ring 2"
                        thing = player["Ring 2"]
                    elif itp in ["r3", "r3"]:
                        ky = "Ring 3"
                        thing = player["Ring 3"]
                    elif itp in ["r4", "R4"]:
                        ky = "Ring 4"
                        thing = player["Ring 4"]
                    print("what gem?")
                    InvGem = thing["Gems"]
                    itp = input("0-" + str(len(InvGem)) + ">   ")
                    while 0 <= int(itp) < len(InvGem):
                        itp = input("0-" + str(len(InvGem)) + ">   ")
                    gem = thing["Gems"][int(itp)]
                    print("Proceed? (y/n)")
                    itp = input(">   ")
                    while itp not in ["y", "Y"]:
                        itp = input(">   ")
                    player[ky] = act.UnsocketGem(thing, gem)
                    del gem, ky
                elif itp in ["i", "I"]:
                    itp = input("0-" + str(len(Inv)) + ">   ")
                    while 0 <= int(itp) < len(Inv):
                        itp = input("0-" + str(len(Inv)) + ">   ")
                    thing = Inv[int(itp)]
                    print("what gem?")
                    InvGem = thing[""]
                    itp = input("0-" + str(len(InvGem)) + ">   ")
                    while 0 <= int(itp) < len(InvGem):
                        itp = input("0-" + str(len(InvGem)) + ">   ")
                    gem = InvGem[int(itp)]
                    print("Proceed? (y/n)")
                    itp = input(">   ")
                    if itp in ["y", "Y"]:
                        Thing = act.UnsocketGem(thing, gem)
                        Inv[Inv.index(thing)] = Thing
                    del InvGem
        if itp in ["e", "E"]:
            Act = rnd.choices([1, 2, 3], [.6, .2, .2], k=1)[0]
        if Act == 1:
            creature = gen.GenerateCreature(
                int(
                    round(
                        math.ceil(player["Level"] * rnd.choices(
                            [0.05, .3, .5, .7], [.15, .35, .15, .35], k=1)[0] +
                                  region["Rank"]))))
            Creature = gen.ModifyObject(creature, region)
            btl.Battle(player, Creature, region)
            player["Current HP"] = player["Maximum HP"]
            print("You found loot!")
            Lt = gen.GenerateLoot(player, rnd.randint(1, 12),
                                  rnd.choice([.3, .5, .7, 1]))
            for k in Lt:
                print(str(Lt.index(k)) + ": " + str(k["Name"]))
            print(
                "pick up what? Pressing a key outside range quits looting: 0-"
                + str(len(Lt) - 1))
            R = len(Lt)
            itp = input(">   ")
            while int(itp) in range(R) and R > 0:
                os.system("cls")
                for k in Lt:
                    print(str(Lt.index(k)) + ": " + str(k["Name"]))
                print(
                    "pick up what? Pressing a key outside range quits looting: 0-"
                    + str(len(Lt) - 1))
                itp = input(">   ")
                if int(itp) > R - 1 or int(itp) < 0:
                    break
                player["Inventory"].append(Lt[int(itp)])
                del Lt[int(itp)]
                R = len(Lt)
            region["Unexplored Regions"] -= 1
            os.system("cls")
        elif Act == 2:
            print("You found loot!")
            Lt = gen.GenerateLoot(player, rnd.randint(1, 12),
                                  rnd.choice([.3, .5, .7, 1]))
            for k in Lt:
                print(str(Lt.index(k)) + ": " + str(k["Name"]))
            print(
                "pick up what? Pressing a key outside range quits looting: 0-"
                + str(len(Lt) - 1))
            R = len(Lt)
            itp = input(">   ")
            while int(itp) in range(R) and R > 0:
                os.system("cls")
                for k in Lt:
                    print(str(Lt.index(k)) + ": " + str(k["Name"]))
                print(
                    "pick up what? Pressing a key outside range quits looting: 0-"
                    + str(len(Lt) - 1))
                itp = input(">   ")
                if int(itp) > R - 1 or int(itp) < 0:
                    break
                player["Inventory"].append(Lt[int(itp)])
                del Lt[int(itp)]
                R = len(Lt)
            region["Unexplored Regions"] -= 1
            os.system("cls")
        elif Act == 3:
            Grd = 1 + int(rnd.uniform(0, 2) * region["Rank"])
            print(Exp)
            print("You Stumbled upon a guarded area protected by " + str(Grd) +
                  " Monsters! Proceed? (Y/N)?")
            itp = input(">   ")
            while itp not in ["n", "N", "y", "Y"]:
                os.system("cls")
                print(Exp)
                print("You Stumbled upon a guarded area protected by " +
                      str(Grd) + " Monsters! Proceed? (Y/N)?")
                itp = input(">   ")
            if itp in ["n", "N"]:
                pass
            elif itp in ["y", "Y"]:
                enemy = Grd
                while 0 < enemy <= Grd:
                    os.system('cls')
                    creature = gen.GenerateCreature(
                        rnd.choices([
                            round(player["Level"] * i + region["Rank"], 1)
                            for i in [.3, .5, .8, 1, 1.5, 2]
                        ], [.13, .11, .26, .42, .03, .02],
                                    k=1)[0])
                    Creature = gen.ModifyObject(creature, region)
                    btl.Battle(player,
                               Creature,
                               region,
                               dungeon=True,
                               left=enemy,
                               total=Grd)
                    player["Current HP"] = player["Maximum HP"]
                    enemy -= 1
                print("You won! Here's your prizes!")
                Lt = gen.GenerateLoot(player, rnd.choice([10, 15]),
                                      rnd.choice([.9, 1, 1.1, 1.2, 1.25]))
                for k in Lt:
                    print(str(Lt.index(k)) + ": " + str(k["Name"]))
                print(
                    "pick up what? Pressing a key outside range quits looting: 0-"
                    + str(len(Lt) - 1))
                itp = input(">   ")
                R = len(Lt)
                while itp in list(range(R)) and R > 0:
                    for k in Lt:
                        print(str(Lt.index(k)) + ": " + str(k["Name"]))
                    print(
                        "pick up what? Pressing a key outside range quits looting: 0-"
                        + str(R - 1))
                    itp = input(">   ")
                    if int(itp) > R - 1 or int(itp) < 0:
                        break
                    player["Inventory"].append(Lt[int(itp)])
                    del Lt[int(itp)]
                    R = len(Lt)
                region["Unexplored Regions"] -= 1
Example #23
0
def generateRandom(additionalAIUnits):
    def generateUnit(faction):
        unitTemplates = ['archer1', 'fighter1', 'defender1',
                         'rogue1', 'healer1', 'mage1']
        unitTemplate = random.choice(unitTemplates)
        u = Resources.unit(unitTemplate)
        u.setFaction(faction)
        #u.setFaction(0)
        return u

    def generateMapAndUnits():
        map_ = Resources.map('random')
        units = []
        nUnits = random.randint(4, 8)
        startColumn = random.randint(0, map_.width - (nUnits + 1) / 2)
        for i in xrange(0, nUnits):
            u = generateUnit(PLAYER_FACTION)
            if i < nUnits / 2:
                row = map_.height-1
                column = startColumn + i
            else:
                row = map_.height-2
                column = startColumn + (i - nUnits/2)
            map_.squares[column][row].setUnit(u)
            units.append(u)
        nUnits += additionalAIUnits
        startColumn = random.randint(0, map_.width - (nUnits + 1) / 2)
        for i in xrange(0, nUnits):
            u = generateUnit(NPC_HOSTILE_FACTION)
            if i < nUnits / 2:
                row = 0
                column = startColumn + i
            else:
                row = 1
                column = startColumn + (i - nUnits/2)
            map_.squares[column][row].setUnit(u)
            units.append(u)
        return (map_, units)

    def verifyMap(map_, units):
        for unit in units:
            map_.fillDistances(unit, unit.posn())
            for other in units:
                (x, y) = other.posn()
                if map_.squares[x][y].search == None:
                    return False
        return True

    validMap = False
    while not validMap:
        (map_, units) = generateMapAndUnits()
        validMap = verifyMap(map_, units)

    endingConditions = [Battle.PLAYER_DEFEATED,
                        Battle.DEFEAT_ALL_ENEMIES]
    battle = Battle.Battle(endingConditions, units, map_)

    lighting = Light.randomEnvironment(map_.width, map_.height)

    music = random.choice(['barbieri-lyta',
                           'barbieri-battle',
                           'barbieri-army-march'])
    
    return Scenario(map_, units, lighting,
                    battle, None, music)
Example #24
0
 def start_battle(self, player, enemy):
     battle = Battle(player, enemy)
     battle.start()