Exemple #1
0
def test_init():
    p = Player(0)
    assert p.id == 0
    assert not p.turn
    assert not p.is_my_turn()
    p.toggle_turn()
    assert p.turn
    assert p.symbol == '-'
Exemple #2
0
 def __init__(self, **kw):
     super(Engine, self).__init__(**kw)
     self.player = Player()
     self.monsters = [genmonster(self._level) for i in range(self._level)]
     self._map = Map(player=self.player,
                     monsters=self.monsters,
                     _level=self._level,
                     _Z=self._maze)
Exemple #3
0
def test_init():
    p = Player(0)
    assert p.id == 0
    assert not p.turn
    assert not p.is_my_turn()
    p.toggle_turn()
    assert p.turn
    assert p.symbol == '-'
Exemple #4
0
def main():
    print_header()
    rolls = build_the_three_rolls()
    name = get_player_name()

    player1 = Player(name)
    player2 = Player("computer")

    game_loop(player1, player2, rolls)
Exemple #5
0
def main():
    print_header()
    rolls = read_rolls()

    name = get_players_name()
    player1 = Player(name)
    player2 = Player("computer")

    game_loop(player1, player2, rolls)
def game():
    print_header()

    rolls = build_three_rolls()

    name = get_players_name()
    player1 = Player(name)
    player2 = Player('Laptop')

    game_loop(player1, player2, rolls)
Exemple #7
0
def game_loop():
    creatures = [
        Creature('Toad', 1),
        Creature('Tiger', 12),
        Creature('Bat', 3),
        Creature('Dragon', 50),
        Creature('Evil Wizard', 1000),
    ]
    hero = Player('Gandolf', 75)
    while True:
        active_creature = choice(creatures)
        print(f'A {active_creature.name} of level {active_creature.level} has appeared from a dark and foggy forest...')
        print()

        cmd = input('Do you [a]ttack, [r]unaway, or [l]ook around? ')
        if cmd == 'a':
            print(f'The hero has {hero.hp} hit points')
            print(f'The {active_creature.name} has {active_creature.hp} hit points')
            while hero.is_alive() and active_creature.is_alive() and input('Continue? (y/n)').strip().lower() == 'y':
                hero.attack(active_creature)
                if not active_creature.is_alive():
                    print(f'The wizard has killed the {active_creature.name}')
                    creatures.remove(active_creature)
                    break

                active_creature.attack(hero)
                if not hero.is_alive():
                    print(f'The wizard was killed by the {active_creature.name}')
                    hero.heal(hero.max_hp)
                    break

                print(f'The hero has {hero.hp} hit points')
                print(f'The {active_creature.name} has {active_creature.hp} hit points')

        elif cmd == 'r':
            hero.heal(hero.max_hp)
            print(f'The wizard has healed')
        elif cmd == 'l':
            print(f'The wizard {hero.name} takes in the surroundings and sees:')
            for c in creatures:
                print(f' * A {c.name} of level {c.level}')
        else:
            print('Ok, exiting game... bye!')
            break

        if not creatures:
            print('You have defeated all the creates, well done!')
            break

        print()
Exemple #8
0
    def __init__(self):
        super(Dugeon, self).__init__()
        self.cells_count = 100
        self.rooms_group = pg.sprite.LayeredDirty()
        self.doors_group = pg.sprite.LayeredDirty()
        self.backgound = pg.sprite.LayeredDirty()
        self.visible_sprites = pg.sprite.LayeredDirty()

        self.doors = []
        self.cells = []
        while (len(self.cells) < self.cells_count):
            c = Cell()
            self.cells.append(c)
        self.rooms = self.select_main_rooms(self.cells)
        area, min_x, min_y = self.separate_cells(self.rooms)

        print("Dugeon dimentions With: %s  Heigth: %s" % area)

        w = area[0] + MAX_ROOM_W * TS2 + TS2
        h = area[1] + MAX_ROOM_H * TS2 + TS2
        self.image = pg.Surface((w, h))
        self.image.fill((0, 0, 0))
        self.bg_image = pg.Surface((SCREEN_RECT.w, SCREEN_RECT.h))
        self.bg_image.fill((0, 0, 0))
        self.rect = self.image.get_rect()
        self.clip_rooms(min_x, min_y)
        self.halls = self.connet_rooms(self.rooms)

        self.initial_room = random.choice(self.rooms)
        self.initial_room.spawed = True

        self.walls = []
        self.make_walls()
        # self.remove_useless_doors()
        self.fix_walls()

        self.player = Player(self.initial_room.rect.center, ALL_SPRITES)
        self.viewport = Viewport()
        self.viewport.update(self.player, self.rect)

        # Custom Cursor
        pg.mouse.set_visible(False)
        self.cursor = Cursor((0, 0), ALL_SPRITES)
        self.cursor.update(self.viewport)
        ALL_SPRITES.change_layer(self.cursor, 9)
    def test_player_get_damage_alive(self):
        player = Player('Robin Hood', ARCHER)
        player.health = 20

        player.get_damage(15)

        self.assertTrue(player.is_alive())
Exemple #10
0
def main():
    print('======== RPG ===========')

    player_name = input('Elige el nombre de tu personaje: ')
    player_class = input('Elige entre Arquero(1) y Guerrero(2): ')
    player = Player(player_name, player_class)
    room_count = 1
    enemy_count = 0

    while True:
        player.has_fled = False
        navigation_action = choose_action()
        encounter = decide_encounter(navigation_action)

        if has_enemy_in_encounter(encounter):
            enemy = create_enemy(encounter)
            print('Un {} salvaje aparecio'.format(enemy))

            while is_battle_active(player, enemy):

                print("\nTURNO DE", player_name)
                action = input('Elige accion: (1) Atacar, (2) Huir: ')
                print('Procesando acción...')
                time.sleep(1)
                player.attack(action, enemy)
                enemy.attack(player)
            enemy_count += 1
            print('derrotaste a {} enemigos'.format(enemy_count))
        room_count += 1
        print('Has pasado por la habitación nº', room_count)
        if not player.is_alive():
            print('Tu puntuación es de {} salas'.format(room_count))
            print('GAME OVERRRRRRR!!')
            break
    def test_player_get_damage_dead(self):
        player = Player('Robin Hood', ARCHER)
        player.health = 14

        player.get_damage(15)

        self.assertFalse(player.is_alive())
Exemple #12
0
import pygame
from time import sleep
from random import randint
from board import Square, Grid, Column
from actors import Player, Game

pygame.init()

WIDTH, HEIGHT = 640, 640
SIZE = 3
DISPLAY_SURF = pygame.display.set_mode((WIDTH, HEIGHT))

FONTOBJ = pygame.font.Font('lato.ttf', 48)

#players = Player(0, 'X'), Player(1, 'O'), Player(2, 'W'), Player(3, 'H')
players = Player(0, 'X'), Player(1, 'O')

white = 204, 204, 204
black = 54, 54, 54
tblack = 54, 54, 54, 128


def random_color():
    return randint(1, 192), randint(1, 192), randint(1, 192)


class Tile(Square):
    def __init__(self, display, *args, **kwargs):
        b_size = WIDTH / SIZE
        Square.__init__(self, *args, **kwargs)
        self.rect = pygame.Rect(self.x * b_size, self.y * b_size, b_size,
Exemple #13
0
class Engine(EventDispatcher):
    """This needs a docstring"""
    _level = NumericProperty(1)
    _map = ObjectProperty(None)
    monsters = ListProperty([])
    player = ObjectProperty(None, allownone=True)
    debug = BooleanProperty(False)
    outputfunc = ObjectProperty(None)
    _maze = ObjectProperty(None, force_dispatch=True)

    def __init__(self, **kw):
        super(Engine, self).__init__(**kw)
        self.player = Player()
        self.monsters = [genmonster(self._level) for i in range(self._level)]
        self._map = Map(player=self.player,
                        monsters=self.monsters,
                        _level=self._level,
                        _Z=self._maze)

    def __setstate__(self, state):
        self._map.__setstate__(state["map"])
        self.player.__setstate__(state["player"])
        self._level = state["level"]
        for monster, mstate in zip(self.monsters, state["monsters"]):
            monster.__setstate__(mstate)

    def __getstate__(self):
        return {
            "map": self._map.__getstate__(),
            "player": self.player.__getstate__(),
            "monsters": [m.__getstate__() for m in self.monsters],
            "level": self._level
        }

    def parse(self, text):
        if text in "adsw":
            self.move("adsw".index(text))
        if text in "f":
            for x, y in self.player.loe:
                if self._map[x, y]:
                    break
                for m in self.monsters:
                    if m.coords == [x, y]:
                        self.attack(self.player, m)
                        break

    def nxtlevel(self):
        self._level += 1
        self.reset(False)
        self.player.xp += 10
        self.player.torches += 2

    def cleanup(self):
        """"""
        for monster in self.monsters:
            if monster.hp <= 0:
                self.player.xp += (monster.level * 5) * self.player.exp
                self.player.gold += (monster.level * 10) * self.player.goldplus
                if dLife.roll() == 1:
                    life = 20
                    maxhp = getattr(self.player, "maxhp")
                    while True:
                        if self.player.hp + life > maxhp:
                            life -= 1
                        else:
                            break
                    if life > 0:
                        pass
                        self.outputfunc("+{} hp".format(life))
                    self.player.hp += life

        self.monsters = filter(lambda m: m.hp > 0, self.monsters)
        self._map.monsters = self.monsters
        if self.player.coords == self._map.exit:
            self.nxtlevel()
            return

        if self.player.hp <= 0:
            self.player._alive = False
            #player dead
            #replay = raw_input("Retry? y/n: ")
            #if replay == "y":
            #    self.reset(True)

            #    self._map.reset(1)
            #else:
            #   sys.exit()
        else:
            self.player.lvlup()

    def reset(self, player):
        if player:
            self.player.reset()
        self.monsters = [genmonster(self._level) for i in range(self._level)]
        self._map.monsters = self.monsters
        self._map.reset(self._level)

    def attack(self, atk, defend):
        """"""
        if ranf() <= atk.accuracy:
            hit = atk.attack - defend.defense
            if type(atk) == Player and self.player.equipped["Weapon"].stat.get(
                    "backstab", 0) == 1:
                hit = atk.attack * 3
            if ranf < 0.05:
                hit = hit * 2
            if hit < 0:
                hit = 0
            defend.hp -= hit
            self.outputfunc(" A Hit! {} has {} hp remaining".format(
                defend.name, defend.hp))
        else:
            self.outputfunc("{} missed!".format(atk.name))

    def move(self, direction):
        dx, dy = facing(self.player, direction)
        if not self._map.passable(self.player.mapx + dx,
                                  self.player.mapy + dy):
            return

        if (self.player.mapx + dx,
                self.player.mapy + dy) == self._map.entrance:
            self.outputfunc("You bang on the door")

            return

        if (self.player.mapx + dx,
                self.player.mapy + dy) == self._map.exit and direction != 3:
            return

        self.player.move(dx, dy)

    def monaction(self):
        for monster in self.monsters:
            monster.ai(self._map, self)
    def test_is_attack_avoided(self):
        player = Player('Robin Hood', ARCHER)
        player.health = 13

        player.get_damage(15)
        player.is_attack_avoided = 100
Exemple #15
0
def main_loop():
    loop_counter = 0
    loop_counter += 1
    if loop_counter == 1:
        atr = wiz_atr()
        name = atr[0]
        char = atr[1]
        level = atr[2]
        shield = atr[3]
        hero = Player(name, level, shield, char)
    # if you want new enemei just add it belov
    # name, atc, def, win text, lose text, atk_descr
    special_moves_list = ["stomp", "gromp", "bomb", "swomp", "chew"]
    special_move = random.choice(special_moves_list)

    enemies = [
        Humans('funny face', 2, 1, "whos laughin now, you stinky bastard?",
               "wizard cant beat face? at least you can"
               " beat his meat", "laughing at wizard very hardr"),
        Humans('happy lovers', 4, 2, "why they should be happy?",
               "they was so happy and cute so wizard kill himself"
               " to death", "kissing each other"),
        Humans('math teacher', 6, 1, "this is sweat revenge",
               "math teacher just beat wizrad till ded",
               "teach you about algoritms"),
        Monsters('fat mom', 5, 9,
                 "she was so fat so she nearly kill you, when falling dead",
                 "fat mom lay at wizard when he was casting majik spells",
                 "trying talk shit about wizzards"),
        Monsters('satan, the third', 7, 7, "at least it wasn't his brother",
                 "wizrds soul forever will be in hell and die",
                 "casting big fireball"),
        Monsters('giant spider bus', 8, 6, "no one seen such a glorious death",
                 "wizord've been drove to death", "riding in the storm"),
        Robots('two big shrobots with shoots', 6, 9, "GET OUT OF HERE TIN CAN",
               "wizard was shooted with shoots", "peu-peu big shoots-whoots"),
        Robots('robo dragon', 8, 10,
               "its time to get over with that japanies bullshit",
               "robo dragon was too cute so weezart melted because fire",
               "eating wizrados brain"),
        Robots(
            'robo slime of exquisite depravity', 12, 8,
            "yeah! get your stubid metal slime things off",
            "robo slime take out wizard to a date, he was cute and then die and you die too because cry and sad",
            "trying to gift metal roses to you"),
        Boss(
            'your social anxiety', 15, 15,
            "you win the battle, but not the war",
            f"Brave {hero.name} can resist fire and ice, but never can go out home and play with bois",
            "happens", special_move),
        Boss('wizard laziness', 16, 16,
             'wizard cant resist and lay down for relax',
             'meh, too lazy to write', 'wizzrd just lay down and sleep',
             'just relax bro')
    ]

    encouters = [
        'appears from the sky', 'materialise right in front of you',
        'got out from earth', 'commin from local subway', 'croos the road'
    ]
    atack_starter = [
        "its your chance for atac", "do smthng you dumbo", "FIGHT", "STRIFE!"
    ]
    # print(enemies)
    while True:
        active_creature = random.choice(enemies)
        current_encounter = random.choice(encouters)
        atack_start = random.choice(atack_starter)
        print(f"Beware! {hero.char} {hero.name} countinue his wey\r\n")
        while True:
            cmd1 = (
                input("[G]O FIND SMTHN, [I]NVENTORY AND STATS\r\n")).lower()

            if cmd1.find('g') != -1 or cmd1.find('go') != -1:
                print(
                    f"You moving forwrd and {active_creature.name} {current_encounter}. "
                    f"It has lvl {active_creature.level}")
                print(f"{atack_start}")
                break

            elif cmd1.find('i') != -1 or cmd1.find('inventory') != -1:
                hero.show_inventory()

        cmd2 = (input("[A]TACC, [C]RY, [R]UN, [Q]EXIT\r\n")).lower()
        if cmd2.find('a') != -1 or cmd2.find('atacc') != -1:
            while True:
                if hero.attack(active_creature):
                    enemies.remove(active_creature)
                    print("encrease your lvl and protection\r\n")
                    hero.level += 1
                    hero.shield += 1
                    break
                else:
                    a = hero.protecc(active_creature)
                    if a == False:
                        break

        elif cmd2.find('s') != -1 or cmd2.find('cry') != -1:
            hero.cry(active_creature)
            enemies.remove(active_creature)

        elif cmd2.find('r') != -1 or cmd2.find('run') != -1:
            hero.run(active_creature)
            enemies.remove(active_creature)

        elif cmd2.find('q') != -1 or cmd2.find('quit') != -1:
            quit()
        else:
            print('WHAT')

        if not enemies:
            print(
                f"You defleat all enemies. Congrats {hero.name} {hero.char}, you complete teh gaem "
                f"your end gaaem majik lvl is {hero.level} with protection {hero.shield}\r\n"
            )
            input("SORRY NOTHING")
            quit()
Exemple #16
0
def run_sim(time=300):
    global total_dmg, sim_list

    total_dmg = 0
    clock = 0
    clock_tick = 0.1

    gcd1a = gcd1
    gcd2a = gcd2
    gcd3a = gcd3

    char = Player(att_pwr=1171,
                  ele=1.4464,
                  c_rate=0.5523,
                  c_dmg=2.5,
                  skill_list=[
                      rosethorn, sunflower, super_sunflower, thorn_strike,
                      petal_storm, burr_toss, grasping_roots, flying_nettles
                  ])

    cosmic = soul()
    soul_buff = Buff(ap=cosmic.ap,
                     c_rate=cosmic.crit_buff,
                     c_dmg=cosmic.crit_dmg_buff,
                     duration=5,
                     name="soul")

    while clock < time:

        apl = []
        apl.append(apl_item(skill=flying_nettles, conditions=[clock < 5]))
        apl.append(
            apl_item(skill=grasping_roots,
                     conditions=[
                         all([
                             True if not poison.name == db.name else False
                             for db in target.debuffs
                         ])
                     ]))
        apl.append(apl_item(skill=thorn_strike))
        apl.append(
            apl_item(skill=flying_nettles,
                     conditions=[
                         any([
                             True if magnum_final.name == buff.name else False
                             for buff in char.buffs
                         ])
                     ]))
        apl.append(
            apl_item(
                skill=burr_toss,
                conditions=[
                    any([
                        True if burr_available.name == buff.name else False
                        for buff in char.buffs
                    ])
                ]))
        apl.append(
            apl_item(skill=petal_storm,
                     conditions=[
                         all([
                             True if not buff.name == bracelet.name else False
                             for buff in char.buffs
                         ])
                     ]))
        apl.append(apl_item(skill=super_sunflower))
        apl.append(apl_item(skill=sunflower))
        apl.append(apl_item(skill=rosethorn))

        #this is where the APL comes in
        if cosmic.remaining_cooldown <= 0:
            soul_buff.duration = cosmic.duration
            char.buffs.append(soul_buff)
            cosmic.remaining_cooldown = cosmic.cooldown
            cosmic.remaining_duration = cosmic.duration
#            print(clock, "add soul buff")

        for i, item in enumerate(apl):
            if item.can_use(item.skill.can_use(char, target)):
                print(round(clock, 2),
                      i,
                      item.skill.name,
                      char.current_focus,
                      sep=' | ')
                total_dmg += item.skill.cast(char, target)
                print([(buff.name, buff.stacks) for buff in char.buffs])
                print([(db.name, round(db.remaining, 2))
                       for db in target.debuffs])
                print([(sk.name, round(sk.remaining_cd, 2))
                       for sk in char.skills])
                print("---------------")
                break

        clock += clock_tick

        for ability in char.skills:
            ability.remaining_cd -= clock_tick

        cosmic.remaining_cooldown -= clock_tick
        cosmic.remaining_duration -= clock_tick
        for buf in char.buffs:
            buf.duration -= clock_tick
            if buf.duration <= 0 or buf.stacks <= 0:
                char.buffs.remove(buf)
#                print(clock, "remove buff: ", buf.name)
        for debuff in target.debuffs:
            debuff.remaining -= clock_tick
            if debuff.remaining % debuff.tick_interval == 0:
                total_dmg += char.attack_power * char.elemental * debuff.damage
            if debuff.remaining <= 0:
                target.debuffs.remove(debuff)

        gcd1a.wait_time -= clock_tick
        gcd2a.wait_time -= clock_tick
        gcd3a.wait_time -= clock_tick


#    sim_list.append(total_dmg/clock)
    sim_list.append(SimResult(damage=total_dmg, time=clock,
                              skills=char.skills))
Exemple #17
0
def player1():
    return Player('Player 1')
Exemple #18
0
class Dugeon(object):
    """docstring for Dugeon"""
    def __init__(self):
        super(Dugeon, self).__init__()
        self.cells_count = 100
        self.rooms_group = pg.sprite.LayeredDirty()
        self.doors_group = pg.sprite.LayeredDirty()
        self.backgound = pg.sprite.LayeredDirty()
        self.visible_sprites = pg.sprite.LayeredDirty()

        self.doors = []
        self.cells = []
        while (len(self.cells) < self.cells_count):
            c = Cell()
            self.cells.append(c)
        self.rooms = self.select_main_rooms(self.cells)
        area, min_x, min_y = self.separate_cells(self.rooms)

        print("Dugeon dimentions With: %s  Heigth: %s" % area)

        w = area[0] + MAX_ROOM_W * TS2 + TS2
        h = area[1] + MAX_ROOM_H * TS2 + TS2
        self.image = pg.Surface((w, h))
        self.image.fill((0, 0, 0))
        self.bg_image = pg.Surface((SCREEN_RECT.w, SCREEN_RECT.h))
        self.bg_image.fill((0, 0, 0))
        self.rect = self.image.get_rect()
        self.clip_rooms(min_x, min_y)
        self.halls = self.connet_rooms(self.rooms)

        self.initial_room = random.choice(self.rooms)
        self.initial_room.spawed = True

        self.walls = []
        self.make_walls()
        # self.remove_useless_doors()
        self.fix_walls()

        self.player = Player(self.initial_room.rect.center, ALL_SPRITES)
        self.viewport = Viewport()
        self.viewport.update(self.player, self.rect)

        # Custom Cursor
        pg.mouse.set_visible(False)
        self.cursor = Cursor((0, 0), ALL_SPRITES)
        self.cursor.update(self.viewport)
        ALL_SPRITES.change_layer(self.cursor, 9)

    def separate_cells(self, cells):
        """based on http://fisherevans.com/blog/post/dungeon-generation
        """
        touching = True
        interation = 0
        min_x = 0
        max_x = 0
        min_y = 0
        max_y = 0
        while touching:
            touching = False
            for i in range(len(cells)):
                a = cells[i]
                for j in range(i + 1, len(cells)):
                    b = cells[j]
                    if a.rect.colliderect(b.rect.inflate(TS4, TS4)):
                        touching = True
                        dx = min(a.rect.right - b.rect.left + TS4,
                                 a.rect.left - b.rect.right - TS4)
                        dy = min(a.rect.bottom - b.rect.top + TS4,
                                 a.rect.top - b.rect.bottom - TS4)
                        if (abs(dx) < abs(dy)):
                            dy = 0
                        else:
                            dx = 0

                        dxa = -dx / 2
                        dxb = dx + dxa
                        dya = -dy / 2
                        dyb = dy + dya

                        dxa = math.floor(((dxa + TS4 - 1) / TS4)) * TS4
                        dxb = math.floor(((dxb + TS4 - 1) / TS4)) * TS4
                        dya = math.floor(((dya + TS4 - 1) / TS4)) * TS4
                        dyb = math.floor(((dyb + TS4 - 1) / TS4)) * TS4

                        a.pos[0] += dxa
                        a.pos[1] += dya
                        b.pos[0] += dxb
                        b.pos[1] += dyb
                        min_x = min(min_x, a.pos[0], b.pos[0])
                        min_y = min(min_y, a.pos[1], b.pos[1])
                        max_x = max(max_x, a.pos[0], b.pos[0])
                        max_y = max(max_y, a.pos[1], b.pos[1])
                        a.rect.topleft = a.pos
                        b.rect.topleft = b.pos
        area = ((max_x - min_x), (max_y - min_y))
        return area, min_x, min_y

    def select_main_rooms(self, cells):
        seleted = []
        for room in cells:
            if (room.rect.w > MIN_ROOM_W * TS2
                    and room.rect.h > MIN_ROOM_H * TS2):
                room.seleted = True
                room.generate_image()
                seleted.append(room)
                room.add(ALL_SPRITES, self.rooms_group, self.backgound)

        print("Rooms selected as main rooms %s" % len(seleted))
        return seleted

    def connet_rooms(self, rooms):
        paths = []
        for i in range(len(rooms)):
            a = rooms[i]
            for j in range(i + 1, len(rooms)):
                skip = False
                b = rooms[j]
                ab_dist = math.pow(a.rect.centerx-b.rect.centerx, 2) + \
                    math.pow(a.rect.centery-b.rect.centery, 2)
                for k in range(len(rooms)):
                    if (k == i or k == j):
                        continue
                    c = rooms[k]
                    ac_dist = math.pow(a.rect.centerx-c.rect.centerx, 2) + \
                        math.pow(a.rect.centery-c.rect.centery, 2)

                    bc_dist = math.pow(b.rect.centerx-c.rect.centerx, 2) + \
                        math.pow(b.rect.centery-c.rect.centery, 2)

                    if (ac_dist < ab_dist and bc_dist < ab_dist):
                        skip = True
                if not skip:
                    ps = self.create_path(a.rect.center, b.rect.center)
                    paths += ps
        return paths

    def create_path(self, p1, p2):
        # A always left o B
        if (p1[0] < p2[0]):
            a = p1
            b = p2
        else:
            a = p2
            b = p1
        a = list(a)
        b = list(b)
        w = h = TS2
        # magic o make the perfect centered hallways
        a[0] -= TILE_SIZE
        a[1] -= TILE_SIZE
        b[0] -= TILE_SIZE
        b[1] -= TILE_SIZE
        a[0] = math.floor(((a[0] + TS2 - 1) / TS2)) * TS2
        a[1] = math.floor(((a[1] + TS2 - 1) / TS2)) * TS2
        b[0] = math.floor(((b[0] + TS2 - 1) / TS2)) * TS2
        b[1] = math.floor(((b[1] + TS2 - 1) / TS2)) * TS2

        clockwise = random.randint(0, 1) == 1
        dx = b[0] - a[0]
        # A avobe B
        if (a[1] < b[1]):
            dy = b[1] - a[1]
            if clockwise:
                r1 = pg.Rect(a[0], a[1], dx + w, h)
                r2 = pg.Rect(b[0], a[1], w, dy)
            else:
                r1 = pg.Rect(a[0], a[1], w, dy + h)
                r2 = pg.Rect(a[0], b[1], dx + w, h)
        else:
            dy = a[1] - b[1]
            if clockwise:
                r1 = pg.Rect(b[0], b[1], w, dy + h)
                r2 = pg.Rect(a[0], a[1], dx + w, h)
            else:
                r1 = pg.Rect(a[0], b[1], dx + w, h)
                r2 = pg.Rect(a[0], b[1], w, dy + h)

        h1 = Hallway(r1, ALL_SPRITES, self.backgound)
        h2 = Hallway(r2, ALL_SPRITES, self.backgound)
        return [h1, h2]

    def clip_rooms(self, min_x, min_y):
        for r in self.rooms:
            r.pos[0] += abs(min_x) + TS2
            r.pos[1] += abs(min_y) + TS2
            r.rect.topleft = r.pos

    def make_walls(self):
        for room in self.rooms:
            x, y = room.rect.topleft
            w = int(room.rect.w / TS2)
            h = int(room.rect.h / TS2)
            old_hall = None
            for i in range(w):
                for j in range(h):
                    if (j > 0 and j < h - 1) and (i > 0 and i < w - 1):
                        y += TS2
                        continue
                    wall = Wall((x, y), i, j, w, h)
                    hit_walls = pg.sprite.spritecollideany(wall, self.walls)
                    hit_rooms = pg.sprite.spritecollideany(
                        wall, self.rooms_group)
                    if not hit_walls or not hit_rooms:
                        hall = pg.sprite.spritecollideany(wall, self.halls)
                        if hall:
                            if old_hall != hall:
                                door = Door((x, y), i, j, w, h)
                                door.add(self.doors_group, ALL_SPRITES)
                                ALL_SPRITES.change_layer(door, 6)
                                self.doors.append(door)
                                door.room = room
                                room.doors.append(door)
                                old_hall = hall
                        else:
                            self.walls.append(wall)
                            ALL_SPRITES.add(wall)
                    y += TS2
                x += TS2
                y = room.rect.top
        for hall in self.halls:
            x, y = hall.rect.topleft
            x -= TS2
            y -= TS2
            w = int(hall.rect.w / TS2) + 2
            h = int(hall.rect.h / TS2) + 2
            for i in range(w):
                for j in range(h):
                    if (j > 0 and j < h - 1) and (i > 0 and i < w - 1):
                        y += TS2
                        continue
                    wall = Wall((x, y), i, j, w, h)
                    if not pg.sprite.spritecollideany(wall, ALL_SPRITES):
                        self.walls.append(wall)
                        ALL_SPRITES.add(wall)
                        ALL_SPRITES.change_layer(wall, 3)
                    else:
                        old_wall = pg.sprite.spritecollideany(wall, self.walls)
                        if old_wall:
                            old_wall.need_fix = True

                    y += TS2
                x += TS2
                y = hall.rect.top - TS2

    def remove_useless_doors(self):
        for i in range(len(self.doors)):
            a = self.doors[i]
            a.rect.inflate_ip(TS2, 0)
            walls_around = pg.sprite.spritecollide(a, self.walls, False)
            a.rect.inflate_ip(-TS2, TS2)
            if len(walls_around) < 2:
                walls_around = pg.sprite.spritecollide(a, self.walls, False)
                if len(walls_around) < 2:
                    a.kill()
                    continue
            a.rect.inflate_ip(TS2, 0)
            for j in range(i + 1, len(self.doors)):
                b = self.doors[j]
                if pg.sprite.collide_rect(a, b) and not b.locked:
                    b.kill()
            a.rect.inflate_ip(-TS2, -TS2)

    def fix_walls(self):
        pass
        # a = self.walls[0]
        # a.rect.inflate_ip(TS2, TS2)
        # walls_around = pg.sprite.spritecollide(a, self.walls, False)
        # for w in walls_around:
        # a.rect.inflate_ip(-TS2, -TS2)

    def handle_input(self, event):
        self.player.handle_input(event)
        # if event.type == pg.MOUSEMOTION:
        #     print(x1+x2, y1+y2)

    def update(self, dt):
        visible_walls = pg.sprite.spritecollide(self.viewport, self.walls,
                                                False)
        self.player.update(dt, self.walls, self.doors_group, self.cursor)
        self.viewport.update(self.player, self.rect)
        self.cursor.update(self.viewport)
        # BULLETS_GROUP.update(dt)
        ENEMIES_GROUP.update(dt, self.player)
        self.rooms_group.update()

        visible_sprites = pg.sprite.spritecollide(self.viewport, ALL_SPRITES,
                                                  False)
        self.visible_sprites.add(visible_sprites)
        for sprite in self.visible_sprites.sprites():
            if not sprite in self.backgound:
                self.visible_sprites.change_layer(sprite, sprite.rect.centery)
            else:
                self.visible_sprites.change_layer(sprite, sprite.layer)

            self.visible_sprites.change_layer(self.cursor, 9999)

            if sprite not in visible_sprites:
                self.visible_sprites.remove(sprite)

    def render(self, surface):
        # ALL_SPRITES.repaint_rect(self.viewport)
        self.image.blit(self.bg_image, (self.viewport.rect))
        self.visible_sprites.draw(self.image)
        BULLETS_GROUP.draw(self.image)
        ENEMIES_GROUP.draw(self.image)
        DECORATOR_GROUP.draw(self.image)
        surface.blit(self.image, (0, 0), self.viewport)
        self.viewport.render(surface)
Exemple #19
0
def get_players_name():
    name = input('What is your name? ')
    p1 = Player(name)
    print('Welcome {}!'.format(p1.name))
    p2 = Player('Computer')
    return (p1, p2)
Exemple #20
0
def player2():
    return Player('Player 2')
                print('Please choose a valid option')

            if not self.player.is_alive():
                print('Oh no! You lose!')
                break
            self.print_linebreak()
            self.player.stats()
            for e in self.enemies:
                e.stats()
            self.print_linebreak()

            if not self.enemies:
                print('You have won! Congratulations!')
                break


if __name__ == '__main__':
    enemies = [
        Ogre('Bob', 1, 3),
        Imp('Alice', 1)
    ]
    player = Player('Hercules', 1)
    Game(player, enemies).main()






#
Exemple #22
0
def main():
    """
    Sets up all the relevent object needed to run the game. This includes the 
    game engine, player, and all enemies in the game. The player and enemies load
    thier sprites from a list of paths in a json file that is loaded and referenced
    in a dict at the start. Once initalization finishes the game loop is run until
    the user exits. 
    """
    engine = neon_engine.NeonEngine('Neon Souls')

    engine.init_pygame()

    with open('player_sprites.json', 'r') as p_file:
        player_sprites = json.load(p_file)

    with open('sentinal_sprites.json') as file:
        sentinal_sprites = json.load(file)

    player_static = player_sprites['static_sprites']
    player_walking = player_sprites['walking_sprites']
    player_running = player_sprites['running_sprites']

    sentinal_sprites = sentinal_sprites['sprite_list']

    player = Player(player_static, player_walking, player_running, (128, 128),
                    'default', 2, 300, 400)
    engine.player_instance = player

    sentinal1 = SentinalEnemy(sentinal_sprites, (100, 100), [(400, 500),
                                                             (600, 500)],
                              engine.kill_enemy, 2, 300, 475)
    sentinal2 = SentinalEnemy(sentinal_sprites, (100, 100), [(1100, 0),
                                                             (1300, 0)],
                              engine.kill_enemy, 2, 1200, 400)
    sentinal3 = SentinalEnemy(sentinal_sprites, (100, 100), [(1500, 0),
                                                             (1700, 0)],
                              engine.kill_enemy, 2, 1600, 450)

    engine.enemy_list.append(sentinal1)
    engine.enemy_list.append(sentinal2)
    engine.enemy_list.append(sentinal3)
    gravity_manager = GravityManager()
    gravity_manager.add_gravity('default', (0, 15))

    gravity_manager.add_object(player)

    # create background and level
    init_map(engine, player, gravity_manager)

    overlay = Overlay(player)
    engine.objects.append(overlay)
    engine.drawables.add(overlay)

    pygame.time.set_timer(pygame.USEREVENT + 1,
                          1000 // league.Settings.gameTimeFactor)
    engine.movement_function = player.move_player
    engine.action_function = fire
    engine.physics_functions.append(player.process_gravity)

    engine.events[pygame.QUIT] = engine.stop
    engine.run()
Exemple #23
0
    def __init__(self, height, width, robot_info, drone_info, num_obstacles,
                 drone_latency):
        super(PMGridEnv, self).__init__()
        # Define action and observation space
        self.action_space = spaces.Discrete(N_DISCRETE_ACTIONS)
        # using image as input (can be channel-first or channel-last):
        self.observation_space = spaces.Box(low=0,
                                            high=255,
                                            shape=(height, width, 3),
                                            dtype=np.uint8)

        # To convert integer actions into string
        self.action_list = ['up', 'down', 'left', 'right']

        ## Canvas is the grid we are going to use
        self.canvas = Canvas(height, width)

        self.latency_factor = drone_latency

        ## Create the robots
        self.playerList = []
        for i in range(len(robot_info) // 3):
            x_loc, y_loc, size = robot_info[3 * i:3 * (i + 1)]
            self.playerList.append(
                Player(pos=[x_loc, y_loc], color='g', size=size))

        ### Add drone to the environememnt
        self.droneList = []
        for i in range(len(drone_info) // 3):
            x_loc, y_loc, size = drone_info[3 * i:3 * (i + 1)]
            self.droneList.append(
                Drone(pos=[x_loc, y_loc], color='b', size=size))

        ## Create the obstacle at random locations
        self.n_obj = num_obstacles  # number of objects
        self.obstacleList = []
        r_coords = np.random.randint(0, self.canvas.height,
                                     (self.n_obj))  # random rows
        c_coords = np.random.randint(0, self.canvas.width,
                                     (self.n_obj))  # random columns
        # Width and height would be chosen from 10,15,20,25,30 randomly
        for i in range(len(r_coords)):
            self.obstacleList.append(
                Obstacle(pos=[r_coords[i], c_coords[i]],
                         size=[
                             np.random.choice([10, 15, 20, 25, 30]),
                             np.random.choice([10, 15, 20, 25, 30])
                         ]))

        ### Environement image as a numpy array
        self.env_img = np.zeros(self.canvas.grid.shape + (3, ), dtype=np.uint8)
        ### Coverage information
        self.coverage = np.zeros(self.canvas.grid.shape, dtype=np.uint8)
        ### Obstacle map information
        self.obstacle_map = np.zeros(self.canvas.grid.shape, dtype=np.uint8)
        #### Drone Map
        self.drone_map = np.zeros(self.canvas.grid.shape + (3, ),
                                  dtype=np.uint8)
        #### Saving initial state for resets
        self.inital_state = [
            self.playerList.copy(),
            self.droneList.copy(),
            self.obstacleList.copy()
        ]
        #### Initializing locaal info for each robot
        for player in self.playerList:
            player.info = self.env_img.copy()
        ### Update entites in screen
        self.update_all()
        self.process_screen()
Exemple #24
0
def player():
    return Player('John')
Exemple #25
0

class GameState():
    stage = GameStage.start
    bullets = []
    asteroids = []
    initials = ''
    level = 1
    score = 0
    lives = 3
    player = None
    leader_board = {}


game = GameState()
game.player = Player(pos=(WIDTH / 2, HEIGHT / 2))
stars = create_star_scape(WIDTH, HEIGHT)
max_distance = min(WIDTH, HEIGHT) * .95

life_pos = 10
life_icons = []
for _ in range(3):
    icon = Actor('player', topleft=(life_pos, 10))
    life_pos += 32
    life_icons.append(icon)


def create_asteroids():
    game.asteroids = []
    for i in range(2 + game.level):
        game.asteroids.append(Asteroid((WIDTH, HEIGHT)))
Exemple #26
0
 def __init__(self, **kw):
     super(Engine,self).__init__(**kw)        
     self.player = Player()
     self.monsters = [genmonster(self._level) for i in range(self._level)]
     self._map = Map(player = self.player,monsters = self.monsters,
                     _level = self._level,_Z = self._maze)
Exemple #27
0
class Engine(EventDispatcher):
    """This needs a docstring"""
    _level = NumericProperty(1)
    _map = ObjectProperty(None)
    monsters = ListProperty([])
    player = ObjectProperty(None,allownone = True)
    debug = BooleanProperty(False)
    outputfunc = ObjectProperty(None)
    _maze = ObjectProperty(None,force_dispatch = True)
    def __init__(self, **kw):
        super(Engine,self).__init__(**kw)        
        self.player = Player()
        self.monsters = [genmonster(self._level) for i in range(self._level)]
        self._map = Map(player = self.player,monsters = self.monsters,
                        _level = self._level,_Z = self._maze)

    def __setstate__(self,state):
        self._map.__setstate__(state["map"])
        self.player.__setstate__(state["player"])
        self._level = state["level"]
        for monster,mstate in zip(self.monsters,state["monsters"]):
            monster.__setstate__(mstate)
    
    def __getstate__(self):
        return {"map":self._map.__getstate__(),"player":self.player.__getstate__(),
        "monsters":[m.__getstate__() for m in self.monsters],"level":self._level}
    
    def parse(self,text):
        if text in "adsw":
            self.move("adsw".index(text))
        if text in "f":
            for x,y in self.player.loe:
                if self._map[x,y]:
                        break
                for m in self.monsters:
                    if m.coords == [x,y]:
                        self.attack(self.player,m)
                        break
    def nxtlevel(self):
        self._level += 1
        self.reset(False)
        self.player.xp += 10
        self.player.torches += 2
                                            
    def cleanup(self):
        """"""
        for monster in self.monsters:
            if monster.hp <= 0:
                self.player.xp += (monster.level * 5) * self.player.exp
                self.player.gold += (monster.level * 10) * self.player.goldplus
                if dLife.roll() == 1:
                    life = 20
                    maxhp = getattr(self.player,"maxhp")
                    while True:
                        if self.player.hp + life > maxhp:
                            life -= 1
                        else:
                            break
                    if life > 0:
                        pass
                        self.outputfunc("+{} hp".format(life))
                    self.player.hp += life
                        
        self.monsters = filter(lambda m: m.hp > 0,self.monsters)
        self._map.monsters = self.monsters
        if self.player.coords == self._map.exit:
            self.nxtlevel()
            return
            
        if self.player.hp <= 0:
            self.player._alive = False
            #player dead
            #replay = raw_input("Retry? y/n: ")
            #if replay == "y":
            #    self.reset(True)
                
            #    self._map.reset(1)
            #else:
            #   sys.exit()
        else: 
            self.player.lvlup()
            
    def reset(self,player):
        if player:
            self.player.reset()
        self.monsters = [genmonster(self._level) for i in range(self._level)]
        self._map.monsters = self.monsters
        self._map.reset(self._level)  

    def attack(self,atk,defend):
        """"""
        if ranf() <= atk.accuracy:
            hit = atk.attack - defend.defense
            if type(atk) == Player and self.player.equipped["Weapon"].stat.get("backstab",0) == 1:
                hit = atk.attack*3
            if ranf < 0.05:
                hit = hit*2
            if hit < 0:
                hit = 0
            defend.hp -= hit
            self.outputfunc(" A Hit! {} has {} hp remaining".format(defend.name,defend.hp))
        else:
            self.outputfunc("{} missed!".format(atk.name))
           
    def move(self, direction):
        dx,dy = facing(self.player,direction)
        if not self._map.passable(self.player.mapx + dx,self.player.mapy + dy):
            return
            
        if (self.player.mapx + dx,self.player.mapy + dy) == self._map.entrance:
            self.outputfunc("You bang on the door")
            
            return
        
        if (self.player.mapx + dx,self.player.mapy + dy) == self._map.exit and direction != 3:
            return
            
        self.player.move(dx, dy)
    def monaction(self):
        for monster in self.monsters:
            monster.ai(self._map,self)
Exemple #28
0
WIDTH = 600
HEIGHT = 480
FPS = 60

# Screen
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()

# Title and icon of the windows
pygame.display.set_caption("Space Invaders")

# Instantiate sprites
player = Player(path='media/link',
                tiles_per_move=8,
                frames=5,
                speed=5,
                inf_scroll=False,
                surface=screen,
                pos=(100, 100))
enemy = Enemy(screen, inf_scroll=True)

enemies = pygame.sprite.Group(enemy)
all_sprites = pygame.sprite.Group(player, enemies)

# Game loop
running = True
iddle_move = 'IDDLE_DOWN'
while running:
    # Set the FPS
    clock.tick(FPS)