Example #1
0
def main():
    currentRoom = room.startRoom()

    print "Welcome to Pygame.\n"
    char = player.player()

    #while player is alive
    while char.chp > 0:
        #check to see if a monster is in the room, if so set it to monster
        monster = currentRoom.enter(char)
        #if there is a monster in the room, begin combat
        while currentRoom.monCount > 0 and monster != None:
            combat.combat(char, monster)
            currentRoom.monCount -= 1
            if char.chp < 1:
                char.death()
        #check for chance event
        currentRoom.rollChance(char)
        #display next room options
        currentRoom.nextRooms(currentRoom.exits)
        #(re)initialize results to None
        result = None
        #display game prompt. If the user selects a new room, restart the loop
        while not result:
            result = prompt(char, currentRoom)
            if isinstance(result, room.maps):
                currentRoom = result

    if char.chp < 1:
        char.death()
Example #2
0
def tower_of_beasts():
    global player_hp, tower_clear

    print("\n>>>> Tower of beasts")

    if tower_clear == False:

        print("\nYou see some horrid beastmen")

        combat("beastmen", 10, "display of savage fury!", 2)

        tower_clear = True

        if player_hp <= 5:
            print("\n>>>> You are badly wounded and should so something")

        elif player_hp >= 6:
            print("\n>>>> You're doing ok.")

        print("\n>>>> Having won you can look around the tower")

        tower_nav()

    else:

        print(">>>> You return to the tower")

        tower_nav()
Example #3
0
def main():
    currentRoom = room.startRoom()

    print "Welcome to Pygame.\n"
    char = player.player()

    #while player is alive
    while char.chp > 0:
        #check to see if a monster is in the room, if so set it to monster
        monster = currentRoom.enter(char)
        #if there is a monster in the room, begin combat
        while currentRoom.monCount > 0 and monster != None:
            combat.combat(char, monster)
            currentRoom.monCount -= 1
            if char.chp < 1:
                char.death()
        #check for chance event
        currentRoom.rollChance(char)
        #display next room options
        currentRoom.nextRooms(currentRoom.exits)
        #(re)initialize results to None
        result = None
        #display game prompt. If the user selects a new room, restart the loop
        while not result:
            result = prompt(char, currentRoom)
            if isinstance(result, room.maps):
                currentRoom = result



    if char.chp < 1:
        char.death()
def randMonster(strength, dice):
    global monsterStrength, monsterPic
    monsterStrength = strength
    if dice == "random":
        roll = random.randint(1, 5)
    else:
        roll = dice
    if strength == "weak":
        weakMonsters(roll)
    elif strength == "medium":
        mediumMonsters(roll)
    elif strength == "strong":
        strongMonsters(roll)
    elif strength == "boss":
        setLeprechaunPunish()
    if strength == "weak" or strength == "medium":
        if not keyBattle:
            audio.pygame.mixer.music.load('Audio/battle.ogg')
        else:
            audio.pygame.mixer.music.load('Audio/bossBattle.ogg')
    elif strength == "strong":
        audio.pygame.mixer.music.load('Audio/bossBattle.ogg')
    monsterPic = defaultMonsterPic
    if not finalBattle.punishBattle:
        audio.monsterRoar.play()
        audio.pygame.mixer.music.play(-1)
        pygame.mixer.music.set_volume(.4)
        encounterAnimation()
        DialogBox.displayText("A %s suddenly attacks!" % monster, yellow, "",
                              yellow, "", yellow, "", yellow, False)
    combat.combat()
Example #5
0
 def test_combat_kill_enemy_die(self, mock_stdout, mock_enemy):
     test_character = Character('Wayne', 10, [2, 3], 0)
     combat.combat(test_character)
     expected_stdout = "You find the scent of fresh blood oddly aromatic"
     expected_kill_count = 1
     actual_kill_count = test_character.get_kill_count()
     self.assertIn(expected_stdout, mock_stdout.getvalue())
     self.assertEqual(expected_kill_count, actual_kill_count)
Example #6
0
 def test_combat_kill_character_enemy_continue_battle(
         self, mock_input, mock_stdout, mock_enemy):
     test_character = Character('Wayne', 10, [2, 3], 0)
     with self.assertRaises(SystemExit):
         combat.combat(test_character)
         expected_stdout = 'The child is persistent! She continues to shoot you with the'
         expected_stdout_2 = 'You stab the screaming child again and do'
         self.assertIn(expected_stdout, mock_stdout.getvalue())
         self.assertIn(expected_stdout_2, mock_stdout.getvalue())
Example #7
0
    def player_end_turn(self, player):
        if player not in self.players_ended_turn:
            self.players_ended_turn.append(player)
        if len(self.players_ended_turn) == len(self.players):
            combat(self.players[0], self.players[1])

            for player in self.players:
                player.start_turn()
            self.players_ended_turn = []
Example #8
0
 def test_combat_kill_character_die(self, mock_input, mock_stdout,
                                    mock_enemy, mock_character):
     test_character = Character('Wayne', 10, [2, 3], 0)
     with self.assertRaises(SystemExit):
         combat.combat(test_character)
         expected_stdout = "You have been killed by a child. What kind of serial killer are you? Game Over.\n"
         expected_hp = 0
         actual_hp = test_character.get_health()
         self.assertIn(expected_stdout, mock_stdout.getvalue())
         self.assertEqual(expected_hp, actual_hp)
Example #9
0
    def enter(self):
        print(
            dedent("""
        As you walk down the road you take stock of your situation.
        You are the only one in your village brave enough to strike against
        the evil that steals your kinfolk in the night. You alone hold the
        blade known to the world as...
        """))

        global sword
        sword = input('> ')
        player_inventory.append(sword)

        print("\nIndeed, the mighty sword", sword, "gives you strength.",
              "You know you must prevail. For the sake of your village.")

        print(
            dedent("""
        You come to a stop. A grisly sight bars your way: a pair of corpses,
        secured to poles by long ropey vines.The foul vegitation has wormed its
        way inside the bodies' eyes, ears, and mouths. To your horror, you
        realize the bodies are still moving...

        Do you attack the twitching corpses, or flee in terror?
        """))

        choice = input('> ')

        if "attack" in choice.lower() or "fight" in choice.lower():

            print("You fight!")
            combat("vine corpses", 7, "thorny clawed fist", 1)
            from combat import player_hp

            return 'sons'

        elif "flee" in choice.lower() or "run" in choice.lower():

            print(
                dedent("""
            You flee in terror. You are not the hero you hoped you were!
            """))
            dead("You fled")

        else:
            print("\nYou attempt to", choice.lower(),
                  "but the enemy is upon you first!")

            global player_hp
            player_hp -= 1
            print("\nDead limbs and thorns cut and wound you!")
            combat("vine corpses", 7, "thorny clawed fist", 1)
            from combat import player_hp

            return 'sons'
Example #10
0
    def enter(self):

        global player_hp, tower_clear

        print("\n>>>> Tower of beasts")

        if tower_clear is False:

            print(
                dedent("""
            Flanked by crumbling stone walls, the moss-covered tower stands
            proud despite the ravages of time. A tall, rust-bound portal bars
            the tower’s sole entrance, watched over by a leering demonic
            gargoyle. Rings of deep arrow slits pierce the thick walls and
            overarching battlements loom high above.

            You gently ease the portal open and make your way inside.

            The hot stench of rot rolls from the tower, raising bile in
            the back of your throat. The floor of the wide tower is covered
            in rotting hides of cattle, sheep and men. A narrow staircase
            spirals around the tower wall. Dark forms hang from chains spiked
            through the wall—surely these are your fellow countrymen!

            A pack of snarling beast-men slowly emerges from the shadows,
            bloody spears clutched in their gnarled hands!
            """))

            combat("beastmen", 10, "display of savage fury!", 2)

            from combat import player_hp

            tower_clear = True

            if player_hp <= 5:
                print("\n>>>> You are badly wounded and should so something")

            elif player_hp >= 6:
                print("You're doing ok.")

            print(
                dedent("""Having defeated the feral monstrosities you are
            able to catch your breath and view your surroundings.
            """))

            return 'tower nav'

        else:

            print("You return to the tower")

            return 'tower nav'
Example #11
0
def explore(current_zone):
    """Decides if an encounter occurs or not"""
    os.system("cls" if os.name == "nt" else "clear")
    if "dead" in player.status:
        print "You're too injured to fight. Rest at a town!"
        raw_input("Press \"Enter\" to continue...")
        return
    action = current_zone.getAction()
    if action == "encounter":
        opponent = current_zone.getEnemy()
        combat.combat(player, opponent)
    elif action == "nothing":
        print "Nothing of interest was found..."
        raw_input("Press \"Enter\" to continue...")
Example #12
0
def explore(current_zone):
    """Decides if an encounter occurs or not"""
    os.system("cls" if os.name == "nt" else "clear")
    if "dead" in player.status:
        print "You're too injured to fight. Rest at a town!"
        raw_input("Press \"Enter\" to continue...")
        return
    action = current_zone.getAction()
    if action == "encounter":
        opponent = current_zone.getEnemy()
        combat.combat(player, opponent)
    elif action == "nothing":
        print "Nothing of interest was found..."
        raw_input("Press \"Enter\" to continue...")
Example #13
0
def main():
    '''
    main routine of batch correction with combat
    '''

    try:

        logger.info('Loading parameters')
        parameters = fg_io.get_parameters()

        random.seed(4711)
        parameters['random_seed'] = 4711

        # data, pheno = get_data()
        #data, pheno = get_test_data()

        logger.info('Received data matrix of shape (genes x cells) = ' +
                    str(data.shape))
        logger.info('Found the following batches: ' +
                    str(set(pheno[Columns.BATCH])))
        logger.info('Calling combat for batch correction.')

        corr = cb.combat(data, pheno[Columns.BATCH])

        make_output(data, corr, pheno, parameters)

        logger.info('Done.')

    except Exception as inst:
        logger.error(type(inst))
        logger.error(inst)
        raise inst
Example #14
0
def fountain():
    global fountain_ooze, player_inventory
    print(">>>> Fountain")

    if fountain_ooze == False:
        print("Watch out for the oozes!")

        combat("Black Oozlings", 10, "mass of hot tar", 2)

        print("\nHaving escaped with your life you return to the courtyard")
        courtyard()

    else:
        print("Fortunately there is no ooze!")

        print("\nYou return to the courtyard.")
        courtyard()
Example #15
0
def road_to_keep():
    print(">>>> Road to keep")

    print('\n As you walk down the road you take stock of your situation.')
    print(
        'You are the only one in your village brave enough to strike against',
        'the evil that steals your kinfolk in the night.')
    print('You alone hold the blade known to the world as...\n')

    global sword
    sword = input('> ')
    player_inventory.append(sword)

    print("\nIndeed, the mighty sword", sword, "gives you strength.",
          "You know you must prevail. For the sake of your village.")

    print("\nYou come to a stop.")
    print(
        "\nA grisly sight bars your way: a pair of bodies, secured to poles by",
        "long ropey vines.")
    print("Wicked vines have wormed their way inside the bodies’", "eyes,"
          " ears, and mouths.")
    print("\nTo your horror, you realize the bodies are still moving...")
    print("\nDo you attack the twitching corpses, or flee in terror?")

    choice = input('> ')

    if "attack" in choice.lower() or "fight" in choice.lower():
        print("You fight!")
        combat("vine corpses", 7, "thorny clawed fist", 1)

        blacksmith_sons()

    elif "flee" in choice.lower() or "run" in choice.lower():
        print("You run in terror. You are not the hero you hoped you were!\n")
        dead("You fled")

    else:
        print("\nYou attempt to", choice.lower(),
              "but the enemy is upon you first!")
        global player_hp
        player_hp -= 1
        print("\nDead limbs and thorns cut and wound you!")
        combat("vine corpses", 7, "thorny clawed fist", 1)

        blacksmith_sons()
Example #16
0
 def test_rand(self):
     from random import choice
     from itertools import repeat
     for _ in repeat(1, 20):
         health = choice(range(1, 100))
         damage = choice(range(1, 100))
         self.assertEqual(combat(health, damage), 0 if
                          (health - damage) < 0 else health - damage)
Example #17
0
def bandit_camp_begin():
    """ 
    Story telling function (starts combat with bandits)
    """

    bandits = enemies.bandits()
    os.system("clear")
    print(
        "After almost 10 hours of rowing, you finally arrive to partly sunken, bandit cave."
    )
    time.sleep(2)
    print(
        "You stepped out of the boat and try to tie boats rope to big rock on a shore."
    )
    time.sleep(2)
    print("Suddenly you hear bandits war cry: Kill the intruder!!!!")
    time.sleep(2)
    print("You turn back to face this new danger!")
    print()
    input("Press Enter to continue...")
    combat.combat(bandits)
Example #18
0
def main():
    lists = sampleGame['objects']
    shipList = lists['shipList']
    friends = [ship for ship in shipList if ship['owner'] == 'ahw']
    enemies = [ship for ship in shipList if ship['owner'] == 'bearda']
    print (friends)
    print (enemies)

    root = tk.Tk()
    root.title("testCombat")
    tmp = combat(root, friends, enemies)
    print(tmp.combatOrders)
    root.mainloop()
Example #19
0
    def test_combat(self, r_result):
        pheno = pd.read_csv('bladder-pheno.csv', index_col=0)
        data = pd.read_csv('bladder-expr.csv', index_col=0)
        model = patsy.dmatrix("~ age + cancer", pheno, return_type="dataframe")

        t = time.time()
        p_result = combat(data, pheno['batch'], model, "age")

        print("{:.2f} seconds\n".format(time.time() - t))
        print(str(p_result.iloc[:5, :5]))

        p_result.to_csv("py-batch.csv")

        print((p_result - r_result).max().max())

        assert np.allclose(r_result, p_result)
def game_event():
    """
    Process the game play loop.

    POST-CONDITION make appropriate changes to character and monster according to events
    """

    # Combat
    if random.random() < 0.1:
        if not combat.combat():
            game_over()
    else:
        # Heal
        if character.get_hp() < character.MAX_HP():
            character.modify_hp(1)
            print("STRUCTURAL INTEGRITY +1 POINT", "\nYOUR STRUCTURAL INTEGRITY:", character.get_hp())
    map.print_map(character.get_coordinates())
Example #21
0
    def __init__(self, filename, windowname):

        self.TECH = TECHandler
        window = self.TECH.get_whndl(windowname)
        self.pycwnd = self.TECH.make_pycwnd(window)
        self.filename = filename
        self.file = open(self.filename, "r")
        self.combat = combat.combat(self)
        self.pickpocketing = pickpocketing(self)
        self.outdoor_basics = outdoor_basics(self)
        self.courses_mod = courses(self)
        self.directions = ['n', 's', 'e', 'w', 'ne', 'nw', 'se', 'sw']
        self.rotation = ['zz', 'zx', 'zc', 'zv', 'zb', 'zn', 'zm', 'za', 'zs', 'zd']
        # rotation = ['zzh', 'zxh', 'zch', 'zvh', 'zbh', 'znh', 'zmh', 'za', 'zsh']
        self.rollPattern = re.compile('Success: (\d+), Roll: (\d+)')
        self.matchPattern = re.compile('\d\.')
        self.free = True
        self.action_status = False
        self.in_combat = False
        self.pick = False
        self.outdoor = False
        self.paused = False
        self.courses = False
        self.courses_part_three = False

        self.last_direction = "n"
        self.last_cmd = ""
        self.expected = None
        self.corpse = 1
        self.queue = []
        self.current_action = Action.nothing
        self.data = self.file.read()
        self.size = len(self.data)
        self.top = Tk()
        self.poll()
        self.pause_button = Button(self.top, text="Pause", command=self.toggle_pause, padx=10, pady=10)
        self.reset_button = Button(self.top, text="Reset Queue", command=self.reset_queue, padx=10, pady=10)
        self.courses_button = Button(self.top, text="Start Courses", command=self.toggle_courses, padx=10, pady=10)
        self.course_part_button = Button(self.top, text="4-Part", command=self.toggle_course_part, padx=10, pady=10)
        self.course_part_button.pack()
        self.courses_button.pack()
        self.reset_button.pack()
        self.pause_button.pack()
        self.top.lift()
        self.top.mainloop()
Example #22
0
def executeGo(direction):
    
    """This function, given
    the direction (e.g. "south") updates the current room
    to reflect the movement of the player if the direction is a valid exit
    (and prints the name of the room into which the player is
    moving). Otherwise, it prints "You cannot go there."
    """
   
    global currentRoom
    foughtBox = False
    foughtSiren = False 
    foughtCyclops = False
    
    if isValidExit(currentRoom["exits"], direction):

        currentRoom = rooms[currentRoom["exits"][direction]]
        printRoom()
        print()
        
        
    else:
        print("No, you cannot go there")
        
    if currentRoom == rooms["basement"] and foughtBox == False:
        combat(box)
        foughtBox = True
    elif currentRoom == rooms["sirenLair"] and foughtSiren == False:
        combat(siren)
        foughtSiren = True
    elif currentRoom == rooms["redhole"] and itemList["panacea"] not in rooms["cyclops"]["items"]:
        print("You have not put the panacea in the Cyclops' Cave.")
        executeGo('south')
    elif currentRoom == rooms["redhole"] and itemList["panacea"] in rooms["cyclops"]["items"]:
        executeGo('north')
    elif currentRoom == rooms["blackhole"] and itemList["earplug"] not in player["inventory"]:
        executeGo('west')
    elif currentRoom == rooms["blackhole"] and itemList["earplug"] in player["inventory"]:
        executeGo('north')
    elif foughtCyclops == False and currentRoom == rooms["cyclops"]:
        combat(monsters["cyclops"])
        foughtCyclops = True
    elif currentRoom == rooms["cyclopsEntrance"] and shouted == True:
        rooms["cyclopsEntrance"]["exits"] = {
            
            "west":"calypsoCave",
            
            "south":"cyclops"}
        
    if currentRoom == rooms["ithaca"]:
        
        currentRoom = questions(currentRoom)
Example #23
0
def bandit_camp_alladin():
    """ 
    Story telling function (starts combat with alladin)
    """

    alladin_hum = enemies.alladin_hum()
    os.system("clear")
    print("YOU BLOODY BASTARD!! YOU KILLED MY COMRADES!!")
    time.sleep(1)
    for i in range(2):
        print(".")
        time.sleep(1)
    print(
        "You won't leave this cave alive! I am Alladin the Prince of Thieves!")
    time.sleep(2)
    print("Prepare to die!!!!!!!!!!!")
    print()
    input("Press Enter to continue...")
    return combat.combat(alladin_hum)
Example #24
0
def random_encounter(player_health):
    """Generate random int

  If the random int is 1, engage in battle

  :param: player_health: an int
  :precondition: must be an integer between 1 and 10
  :postconditon: generates random int, if it's 1, fight a wild kibble bag 
  :return: 3 integers
  """
    luck = random.randint(1, 4)
    if luck == 1:
        print(colors.yellow("A wild kibble bag has appeared"))
        remaining_health, enemies_killed, kibble = combat.combat(player_health)
        return remaining_health, enemies_killed, kibble

    else:
        remaining_health = health_gain(player_health)
        return remaining_health, 0, 0
Example #25
0
def main():
    ##  initialize()
    global enemyList
    x_cord = 67
    y_cord = 540
    gameDisplay.fill(white)
    pygame.display.update()
    GameExit = False
    while GameExit == False:
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_q:
                    GameExit = True
                if event.key == pygame.K_q:
                    #if the Q key is pressed, quit the game
                    gameExit = True

                elif event.key == pygame.K_LEFT:
                    # if the left key is pressed, the player x-coordinates will move left for 50 pixles (jump_movement) if the player is not out of bounds
                    x_cord = x_cord - 5
                    movement(x_cord, y_cord)
                elif event.key == pygame.K_RIGHT:
                    # if the right key is pressed the x-coordinates of the player will be moved right 50 pixles (jump_movemnt) if the player is not out of bounds
                    x_cord = x_cord + 5
                    movement(x_cord, y_cord)
                elif event.key == pygame.K_DOWN:
                    y_cord = y_cord + 5
                    movement(x_cord, y_cord)
                elif event.key == pygame.K_UP:
                    y_cord = y_cord - 5
                    movement(x_cord, y_cord)
        hit = check_if_hit(x_cord, y_cord)
        if (hit[0]):
            com = combat.combat(hit[1], enemyList, caracter_info, gameDisplay)
            for i in range(len(enemyList)):
                print(i)
                if enemyList[i][1] == com:
                    del enemyList[i]
                    break
Example #26
0
def main():
    itemSource = items.itemLoader()
    mobSource = mobs.mobLoader()
    currentRoom = room.startRoom()
    print "\033[2J"
    print """           WELCOME
                            ,--.
                           {    }
                           K,   }
                          /  ~Y`
                     ,   /   /
                    {_'-K.__/
                      `/-.__L._
                      /  ' /`\_}
                     /  ' /
             ____   /  ' /
      ,-'~~~~    ~~/  ' /_
    ,'             ``~~~  ',
   (                        Y
  {                         I
 {      -                    `,
 |       ',                   )
 |        |   ,..__      __. Y
 |    .,_./  Y ' / ^Y   J   )|
 \           |' /   |   |   ||
  \          L_/    . _ (_,.'(
   \,   ,      ^^""' / |      )
     \_  \          /,L]     /
       '-_~-,       ` `   ./`
          `'{_            )
              ^^\..___,.--`
    """ #This is super cheesy, but it's a nod to old school MUDs, which inspired this game
    char = player.player()

    #debug
    if char.name == "AlexRocks":
        potion = itemSource.makeItem(0)
        char.inventory.append(potion)
        armor = itemSource.makeArmor(0, "head")
        char.inventory.append(armor)
        armor2 = itemSource.makeArmor(1, "head")
        char.inventory.append(armor2)
        weapon = itemSource.makeWeapon(0, "weapon")
        char.inventory.append(weapon)
        weapon2 = itemSource.makeWeapon(1, "weapon")
        char.inventory.append(weapon2)
        twohand = itemSource.makeWeapon(1, "twohanded")
        char.inventory.append(twohand)
        shield = itemSource.makeArmor(1, "shield")
        char.inventory.append(shield)

    while char.currentHP > 0:
        # check to see if a monster is in the room, if so set it to monster
        monster = currentRoom.enter(char, mobSource, itemSource)
        print "\n" + currentRoom.desc
        # if there is a monster in the room, begin combat
        if not monster:
            print "You appear to be alone here."
        if currentRoom.monCount > 0 and monster:
            print monster.desc + "\n"
            time.sleep(1.5)
            with combat.combat(char, monster, currentRoom) as battle:
                while battle.running is True:
                    battle.getInput(char)
            currentRoom.monCount -= 1
            if char.currentHP < 1:
                char.death()
            del battle
        # check for chance event
        currentRoom.rollChance(char, itemSource)
        # if any items in room, show them
        currentRoom.roomContents()
        # display next room options
        currentRoom.nextRooms(currentRoom.exits)
        # (re)initialize results to None
        result = None
        # display game prompt. If the user selects a new room, restart the loop
        while not result:
            result = prompt.basePrompt(char, currentRoom)
            if isinstance(result, room.maps):
                currentRoom = result



    if char.currentHP < 1:
        char.death()
Example #27
0
def main():
    try:
        validResponse = False
        while not validResponse:
            loadSave = str(
                input("Would you like to load an existing save? [Y/N]? "))
            if loadSave == "Y" or loadSave == "N":
                validResponse = True
            else:
                print("That is not yes or no")
        if loadSave == "N":
            print("Beginning Game")
            player = CharCreator.main()
            board = createBoard(7, 7, player)
        elif loadSave == "Y":
            fileName = str(input("Input Saved Game's FileName"))
            board, player = load(fileName + ".sav")
            board.printBasicBoard()

    #main - handles the overarching game
    #load save (y/n)?
    #if no
    #create the player
    #create the board
    #if yes, load given save file.
    #check to make sure the file is a pickle file containing a legit save.
    #display the board
    #display character stats and other relevant info

        playerWon = False
        playerDead = False

        SPECIALCHAR = 100
        UP = 72
        DOWN = 80
        LEFT = 75
        RIGHT = 77
        Q = 113
        S = 115
        I = 105
        D = 100
        T = 116
        ordList = [SPECIALCHAR, UP, DOWN, LEFT, RIGHT, Q, S, I, D, T, 224]
        system("cls")
        print(
            "On the following map, you are marked as a 'P', enemies are 'E', various spacial anomalies are 'A' and your final challenge is marked as 'B'"
        )
        time.sleep(5)
        while not playerWon and not playerDead:
            #check if the player has won, or is dead. if either is true move to the appropriate endGame function, else move on
            system("cls")
            print(board.printBasicBoard())
            print(
                "Use the Arrow Keys to move, Q to Quit, S to Save, I to access inventory, or D to access stats: "
            )

            currentLoc = player.getLoc()
            startTile = board.getBoard()[currentLoc[1] - 1][currentLoc[0] - 1]

            playerChoice = ord(getch())
            if playerChoice in ordList:
                if playerChoice == 224:
                    playerMove = ord(getch())
                    board, player = move(board, player, playerMove)
                    newCoord = player.getLoc()
                    currentTile = board.getBoard()[newCoord[1] -
                                                   1][newCoord[0] - 1]
                    if isinstance(currentTile, gameObjects.EnemyTile):
                        player, combatResolution = combat.combat(
                            currentTile.getEnemy(), player)
                        if combatResolution == "W":
                            currentTile.removeEnemy()
                            board.setTile(newCoord[0], newCoord[1],
                                          gameObjects.MapTile(playerOcc=True))
                        elif combatResolution == "L":
                            playerDead = True
                            break
                        elif combatResolution == "R":
                            board, player = moveAway(board, player)
                        time.sleep(2)
                    elif isinstance(currentTile, gameObjects.BossTile):
                        encountersNeeded = 5
                        if player.getEncounters() >= 5:
                            player, combatResolution = bossCombat.combat(
                                currentTile.getBoss(), player)
                            if combatResolution == "W":
                                playerWon = True
                                break
                            elif combatResolution == "L":
                                playerLost = True
                                break
                        else:
                            print(
                                "You are not yet strong enough to face the boss, you must prove your mettle against at least 5 enemies first"
                            )
                            moveAway(board, player)
                    elif isinstance(currentTile, gameObjects.AnomalyTile):
                        anomaly = currentTile.getAnomaly()
                        player = encounter.main(anomaly, player)
                        board.setTile(newCoord[0], newCoord[1],
                                      gameObjects.MapTile(playerOcc=True))
                elif playerChoice == I:
                    player, curTurn = items.inventory(player)
                elif playerChoice == Q:
                    print("Press Q to quit immediately or S to save first")
                    playerChoice = ord(getch())
                    if playerChoice == Q:
                        break
                    elif playerChoice == S:
                        save(board, player)
                elif playerChoice == S:

                    save(board, player)
                    #clear screen
                    print("Game Saved")
                    print("Press Any Key to Exit")
                    key = ord(getch("..."))
                    #command to close window
                elif playerChoice == I:
                    player.useItem()
                elif playerChoice == D:
                    player.getStats()
                    print("------------")
                    input("Press Enter to Continue")
                elif playerChoice == T:
                    player.getStats()
                    print("Press Any Key to Continue...")
                    playerKey = getch()
                else:
                    print("Invalid")
            #player presses key move -> [UP/DOWN/LEFT/RIGHT ARROWS] OR Q [Quit] OR S [Save] OR I [Inventory]
            #player moves
            #MOVE()
            #player moves to an occupied tile
            #encounter = True
            #check if the tile contains the final boss
            #if the tile does contain the boss check the players number of enemy defeats
            #if the player has defeated enough enemies ask the player if they want to fight the boss
            #if yes initiate a battle with the final boss - combat.py
            #if you lose game over   -playerLoses()
            #elif you win game won   -playerWins()
            #else if player doesnt have enough encounters or dont want to fight, move the player away
            #move the player one tile based on RNG and position (Up,down,left,right)
            #loop random moves until a valid move is found.
            #while not valid move
            #moveAway()

            #if the tile doesnt contain the boss, check for an enemy or anomaly
            #if there is an enemy, fight it
            #if the player wins, display {encouragment} {celebration} and replace their current tile with a PlayerTile
            #elif the player loses, end the game {possibly lose a life}?
            #elif the player runs, move them 1 tile randomly
            #update the enemyTile with the enemies state after battle

            #else if there is an anomaly, player encounters the anomaly
            #set anomaly tile to player occupied
            #player moves to unoccupied tile
            #redraw board

            #use item
            #asks the player to choose an item from their inventory or cancel
            #if the player wants to use an item that is single use, warn them it will be wasted
            #if they still want to use it, use the item
            #else loop back to top

            #save
            #use a save function to save the board.
            #the board contains all objects and tiles and everything in play, so we should just need to save that one object.

            #quit
            #warns the player to save first [Q] to quit, [S] to save
            #if they choose to save, run the save function
            #else terminate the program.
        if playerWon == True:
            system("cls")
            print("You have emerged victorious from a dangerous galaxy")
            time.sleep(2)
            print(
                "By defeating the galactic boss you have earned the praises of all who know you, rest well hero"
            )
            time.sleep(2)
            print("Your Final Stats")
            print("-------------")
            print(player.getStats())
            time.sleep(10)
        elif playerLost == True:
            print("You have fallen to the evils of the galaxy")
            print("Fare thee well in the next life")
            time.sleep(10)
        else:
            pass
    except Exception as e:
        logging.basicConfig(filename='app.log', level=logging.INFO)
        logging.exception(e)
Example #28
0
def play():
    game = True
    while game == True:
        cprint(r"""
        _
       (_)
       |=|              __  __
       |=|              ||  ||  ____  ___     ____    __||__
   /|__|_|__|\          ||__||  ||    ||\\    || ))   --||--
  (    ( )    )         ||__||  ||-   ||_\\   || \\     ||
   \|\/\"/\/|/          ||  ||  ||__  ||  \\  ||  \\    ||
     |  Y  |            ||  ||
     |  |  |           '--''--'              OF
     |  |  |
    _|  |  |                     __           __
 __/ |  |  |\                    \ \         / /
/  \ |  |  |  \                   \ \       / / ___     __       ____   ____
   __|  |  |   |                   \ \     / /  ||\\    ||      //  \\  || ))
/\/  |  |  |   |\                   \ \   / /   ||_\\   ||____  ||  ||  || \\
 <   +\ |  |\ />  \                  \ \_/ /    ||  \\  \|----  \\__//  ||  \\
  >   + \  | LJ    |                  \___/
        + \|+  \  < \
  (O)      +    |    )                        By Alexander Egbert
   |             \  /\
 ( | )   (o)      \/  )
_\\|//__( | )______)_/
        \\|//

            """, "cyan")
        newgame = True
        if functions.saves_list() != []:
            save_exists = True
        else:
            save_exists = False

        menu = ['NEW GAME', 'QUIT TO DESKTOP']
        if save_exists:
            menu.insert(0, 'LOAD GAME')
        for i, option in enumerate(menu):
            print('{}'.format(i) + colored(': {}'.format(option), 'red'))
        choice = input('Selection: ')
        while not functions.is_input_integer(choice):
            cprint("You must enter a valid number to select an option.", "red")
            choice = input('Selection: ')
        choice = int(choice)
        if menu[choice] == 'NEW GAME':
            pass  # proceed as new game
        elif menu[choice] == 'LOAD GAME':
            newgame = False
        elif menu[choice] == 'QUIT TO DESKTOP':
            game = False
            continue

        if newgame == False:
            try:
                player = functions.load_select()
                if player == SyntaxError:  # if something's broken, go back to main menu
                    continue
            except:  # if something's broken, go back to main menu
                continue

        else:
            player = Player()
            universe = Universe()
            player.universe = universe

        if newgame:
            # intro_scene.intro()  # Comment this out to disable the intro sequence
            player.universe.build(player)
            player.map = player.universe.starting_map
            player.location_x, player.location_y = (player.universe.starting_position)

        room = player.universe.tile_exists(player.map, player.location_x, player.location_y)

        if newgame:
            for item in player.inventory:
                # if item.name == "Rock":
                #     player.eq_weapon = item
                #     item.isequipped = True
                if item.name == "Tattered Cloth" or item.name == "Cloth Hood":
                    item.isequipped = True
        print(room.intro_text())
        player.main_menu = False
        check_time = time.time()
        auto_save_timer = check_time
        mark_health = player.hp
        while player.is_alive() and not player.victory and not player.main_menu:
            player.time_elapsed += (time.time() - check_time)
            auto_save_timer += (time.time() - check_time)
            if auto_save_timer > 300:  # autosave timer
                functions.autosave(player)
                auto_save_timer = 0
            check_time = time.time()
            room = player.universe.tile_exists(player.map, player.location_x, player.location_y)
            player.current_room = room
            if player.universe.game_tick > 0:
                player.current_room.last_entered = player.universe.game_tick
            else:
                player.current_room.last_entered = 1
            room.evaluate_events()
            room.modify_player(player)
            if mark_health != player.hp:
                player.show_bars(True,False)  # show just the health bar if the player's current HP has changed
                mark_health = player.hp
            player.refresh_moves()
            functions.check_for_npcs(room)
            functions.check_for_items(room)
            functions.check_for_objects(room)
            combat_list = functions.check_for_combat(player)
            if len(combat_list) > 0:  # Check the state of the room to see if there are any enemies
                print(colored("Jean readies himself for battle!","red"))
                combat.combat(player, combat_list)

            if player.is_alive() and not player.victory:
                player.stack_inv_items()
                print("\nChoose an action:\n")
                available_actions = room.adjacent_moves()
                available_moves = colored('| ', "cyan")
                for action in available_actions:
                    available_moves += (colored(action, "green")) + colored(' | ',"cyan")
                print(available_moves)
                print("\n\nFor a list of additional commands, enter 'c'.\n")
                action_input = input('Action: ')
                available_actions = room.available_actions()
                count_args = action_input.split(' ')
                arbitrary_action = True
                if len(count_args) == 1:
                    for action in available_actions:
                        for key in action.hotkey:
                            if action_input == key:
                                arbitrary_action = False
                                player.do_action(action, **action.kwargs)
                elif len(count_args) > 1:
                    for action in available_actions:
                        for key in action.hotkey:
                            if count_args[0] == key:
                                join_args = ' '.join(count_args[1:])
                                player.do_action(action, join_args)
                                arbitrary_action = False
                                break
                    if arbitrary_action:
                        lower_phrase = count_args[1].lower()
                        for i, object in enumerate(room.objects_here):
                            search_item = object.name.lower() + ' ' + object.idle_message.lower()
                            if lower_phrase in search_item and not object.hidden:
                                for keyword in object.keywords:
                                    if count_args[0] == keyword:
                                        object.__getattribute__(keyword)()
                                break

                else:
                    cprint("Jean isn't sure exactly what he's trying to do.", 'red')
            time.sleep(0.5)
Example #29
0
 def __init__(self, name = '', command_echelon = 'Team', side = 'BLUE', template=None, sim = None):    
   # Pointer to Simulator (non-templated)
   self.sim = sim
   
   # identity (non-templated)
   self['name'] = name
   self['side'] = side
   
   # Command echelon level
   self['command_echelon'] = command_echelon
   self['echelon_name'] = name
   
   # Actual unit size
   self['size'] = 'Team'
     
   # TOE (Get rid of TOE as public variable)
   self.template = template
   self['TOE'] = ''
   self.personel = {}
   self.vehicle = {}
   self['sensors'] = []
   
   # Logistics ###############################
   self.cargo = supply_package()
   
   # Command and Control #####################
   # Human factors in the TOEM format
   self['fatigue'] = self['morale'] = self['suppression'] = 0
   
   # Pointer to HIGHER and TF HIGHER (if any)
   self['HQ'] = None
   self['OPCON'] = None
   
   # List of immediate subordinates
   self['subordinates'] = []
   self['detached'] = []
   
   # Intelligence state data
   self['contacts'] = {}
   
   # Communications and Situations
   self['SITREP'] = {}
   self.COMMindex = 0
   self.COMMNets = []
   
   
   # Agents ##################################
   self['agent'] = agent(self)
   self.agentData = {}
   self['log'] = sandbox_log()
   self['staff queue'] = []
   self['OPORD'] = OPORD()
   
   # Location, heading, speed and disposition (non-templated)
   self.SetPosition( position_descriptor() ) #vect_5D()
   self['stance'] = 'deployed'
   self['readiness'] = 0.0
   self['dismounted'] = True
   
   # Blank models (In case the templates are incomplete)
   self.SetModelCombat(combat())
   self.SetModelIntelligence(intelligence())
   self.SetModelC4I(C4I())
   self.SetModelLogistics(logistics())
   self.SetModelMovement(movement())
   
   # Misc internal stuff
   self['ground engagements'] = []
   self['activities this pulse'] = []
   self['last pulse'] = None
   
   # Overiding Icon symbol
   self['icon'] = {}
   self['icon']['IFF'] = 'FRIEND'
   self['icon']['type'] = MapSym[self['TOE']][1]
   self['icon']['char'] = MapSym[self['TOE']][0]
    
   # template information
   if self.sim and self.template:
     self.sim.data.FetchData(self, 'unit', self.template)
     
   # Set the cargo to the capacity to a basic load
   if not self.cargo:
     self.cargo = self.GetBasicLoad(self)
Example #30
0
            "Sorry, I didn't catch that. Are you Fighter, Wizard, or Rogue? "))

player = class_dict.get(class_input)

time.sleep(2)

print(
    f"I hope your adventure in Borovia fares well, {name_input} the {class_input}. "
)

time.sleep(2)

print(f"""Here are your stats: 
    Health is {player.health}
    Attack is {player.attack_power}
    Defense is {player.defense}""")

time.sleep(2)

print("For reasons you can't remember, you are walking in the woods.")

time.sleep(2)

print("You come across an Orc. Scary! It attacks!")

time.sleep(2)

current_enemy = Orc(150, 10, 10, "Bregor the Stonebutt")

combat(player, current_enemy)
Example #31
0
    def enter(self):

        global fountain_ooze, fled_ooze, player_inventory

        #        print(">>>> Fountain")

        if fountain_ooze is False:

            print(
                dedent("""
            As you move forwards you can see that the toad fountain is adorned
            with red gemstone eyes and jeweled fangs within the loathsome maw.
            The ooze in the fountain bubbles and then suddenly lurches
            outwards, animated by some unknown force. Splitting into several
            strange shapes it moves towards you with evil intent...

            What will you do?
            """))

            while True:
                choice = input("> ")

                #                print(">>>>", choice)

                if (choice.lower() == "attack" or choice.lower() == "fight"):

                    combat("Black Oozlings", 10, "mass of hot tar", 3)

                    print(
                        dedent("""
                    Having escaped with your life you decide you deserve a
                    little reward. You spend half an hour or so prying away at
                    the fountain and make yourself several gemstones richer,
                    before returning to the courtyard.
                    """))

                    fountain_ooze = True

                    player_inventory.append("Red gemstones")

                    return 'courtyard'

                elif "powder" in choice:

                    print(
                        dedent("""
                    You hurl the green powder at the strange oozes. They errupt
                    into flames, thrash around and then melt away.

                    Pleased with yourself you decide you deserve a little
                    reward. You spend half an hour or so prying away at the
                    fountain and make yourself several gemstones richer, before
                    returning to the courtyard.
                    """))

                    fountain_ooze = True

                    player_inventory.append("Red gemstones")

                    return 'courtyard'

                # elif:
                #    choice.lower() == "flee" or choice.lower() == "run":

                #    print(dedent("""
                #    You flee from the ooze, dashing back to the courtyard.
                #    """))

                #    fled_ooze == "True"

                else:
                    print("\nYou attempt to", choice.lower(),
                          "but the enemy is upon you first!")

                    combat("Black Oozlings", 10, "mass of hot tar", 3)

                    print(
                        dedent("""
                    Having escaped with your life you decide you deserve a
                    little reward. You spend half an hour or so prying away at
                    the fountain and make yourself several gemstones richer,
                    before returning to the courtyard.
                    """))

                    fountain_ooze = True

                    player_inventory.append("Red gemstones")

                    return 'courtyard'

        else:
            print("Fortunately there is no ooze!")

            print("\nYou return to the courtyard.")

            return 'courtyard'
Example #32
0
 def test(self):
     self.assertEqual(combat(100, 5), 95)
     self.assertEqual(combat(83, 16), 67)
     self.assertEqual(combat(20, 30), 0)
Example #33
0
         -5)  #if player wants to flee, it tries to minus 5 currency
     if ciggies == False:  #if deducted amount is greater than current ciggies, returns False
         print 'Not enough ciggies, you gotta fight %s.' % mob_name
         raw_input()
         fight = True
         flee = False  #unsure if this will go back to start in if loop?
     else:  #able to deduct ciggies and avoid fight
         money = ciggies
         print "%s grunts and accepts the 5 ciggies, you now have %d ciggies left." % (
             mob_name, money)
         battled = True
         train_fight = False
         fight = False  #exists loop, goes onto ????
 else:
     alive, loot, money = combat.combat(player_hp, player_att,
                                        player_def, mob_hp, mob_att,
                                        mob_def, mob_name, money)
     if (alive == True) and (loot > 0):
         level_hp, level_att, level_def = combat.victory()
         player_hp += level_hp
         player_att += level_att
         player_def += level_def
         money += loot
         print "\nYou gained %d HP, %d attack, %d defence.  Your stats are now: %d HP, %d ATT, %d DEF." % (
             level_hp, level_att, level_def, player_hp, player_att,
             player_def)
         print "You found %d ciggies on the crumpled corpse of %s.  Now you have %d." % (
             loot, mob_name, money)
         battled = True
         train_fight = False
         fight = False
from character import warrior, mage, priest
from enemy import goblin, murloc
from team import team
from combat import combat
#**************************************Place character into World*************#
warrior_gar = warrior("Orc", "Garrosh")
mage_jen = mage("human", "Jaina")
priest_and = priest("human", "Anduin")
my_team = team([warrior_gar, mage_jen, priest_and], 1)

enemy1 = goblin(1)
enemy2 = goblin(1)
enemy3 = murloc(1)
enemy_team = team([enemy1, enemy2, enemy3], 0)

first_combat = combat(my_team, enemy_team)

first_combat.combat_start()
#**************************************Eof************************************#
Example #35
0
    def __init__(self, filename, windowname):

        self.TECH = TECHandler
        window = self.TECH.get_whndl(windowname)
        self.pycwnd = self.TECH.make_pycwnd(window)
        self.filename = filename
        self.file = open(self.filename, "r")
        self.combat = combat.combat(self)
        self.pickpocketing = pickpocketing(self)
        self.outdoor_basics = outdoor_basics(self)
        self.courses_mod = courses(self)
        self.directions = ['n', 's', 'e', 'w', 'ne', 'nw', 'se', 'sw']
        self.rotation = [
            'zz', 'zx', 'zc', 'zv', 'zb', 'zn', 'zm', 'za', 'zs', 'zd'
        ]
        # rotation = ['zzh', 'zxh', 'zch', 'zvh', 'zbh', 'znh', 'zmh', 'za', 'zsh']
        self.rollPattern = re.compile('Success: (\d+), Roll: (\d+)')
        self.matchPattern = re.compile('\d\.')
        self.free = True
        self.action_status = False
        self.in_combat = False
        self.pick = False
        self.outdoor = False
        self.paused = False
        self.courses = False
        self.courses_part_three = False

        self.last_direction = "n"
        self.last_cmd = ""
        self.expected = None
        self.corpse = 1
        self.queue = []
        self.current_action = Action.nothing
        self.data = self.file.read()
        self.size = len(self.data)
        self.top = Tk()
        self.poll()
        self.pause_button = Button(self.top,
                                   text="Pause",
                                   command=self.toggle_pause,
                                   padx=10,
                                   pady=10)
        self.reset_button = Button(self.top,
                                   text="Reset Queue",
                                   command=self.reset_queue,
                                   padx=10,
                                   pady=10)
        self.courses_button = Button(self.top,
                                     text="Start Courses",
                                     command=self.toggle_courses,
                                     padx=10,
                                     pady=10)
        self.course_part_button = Button(self.top,
                                         text="4-Part",
                                         command=self.toggle_course_part,
                                         padx=10,
                                         pady=10)
        self.course_part_button.pack()
        self.courses_button.pack()
        self.reset_button.pack()
        self.pause_button.pack()
        self.top.lift()
        self.top.mainloop()
Example #36
0
    def __init__(self, name="", command_echelon="Team", side="BLUE", template=None, sim=None):
        # Pointer to Simulator (non-templated)
        self.sim = sim

        # identity (non-templated)
        self["name"] = name
        self["side"] = side

        # Command echelon level
        self["command_echelon"] = command_echelon
        self["echelon_name"] = name

        # Actual unit size
        self["size"] = "Team"

        # TOE (Get rid of TOE as public variable)
        self.template = template
        self["TOE"] = ""
        self.personel = {}
        self.vehicle = {}
        self["sensors"] = []

        # Logistics ###############################
        self.cargo = supply_package()

        # Command and Control #####################
        # Human factors in the TOEM format
        self["fatigue"] = self["morale"] = self["suppression"] = 0

        # Pointer to HIGHER and TF HIGHER (if any)
        self["HQ"] = None
        self["OPCON"] = None

        # List of immediate subordinates
        self["subordinates"] = []
        self["detached"] = []

        # Intelligence state data
        self["contacts"] = {}

        # Communications and Situations
        self["SITREP"] = {}
        self.COMMindex = 0
        self.COMMNets = []

        # Agents ##################################
        self["agent"] = agent(self)
        self.agentData = {}
        self["log"] = sandbox_log()
        self["staff queue"] = []
        self["OPORD"] = OPORD()

        # Location, heading, speed and disposition (non-templated)
        self.SetPosition(position_descriptor())  # vect_5D()
        self["stance"] = "deployed"
        self["readiness"] = 0.0
        self["dismounted"] = True

        # Blank models (In case the templates are incomplete)
        self.SetModelCombat(combat())
        self.SetModelIntelligence(intelligence())
        self.SetModelC4I(C4I())
        self.SetModelLogistics(logistics())
        self.SetModelMovement(movement())

        # Misc internal stuff
        self["ground engagements"] = []
        self["activities this pulse"] = []
        self["last pulse"] = None

        # Overiding Icon symbol
        self["icon"] = {}
        self["icon"]["IFF"] = "FRIEND"
        self["icon"]["type"] = MapSym[self["TOE"]][1]
        self["icon"]["char"] = MapSym[self["TOE"]][0]

        # template information
        if self.sim and self.template:
            self.sim.data.FetchData(self, "unit", self.template)

        # Set the cargo to the capacity to a basic load
        if not self.cargo:
            self.cargo = self.GetBasicLoad(self)