Exemplo n.º 1
0
def load_monsters(level_config):

    level = DungeonLevel.get(DungeonLevel.level_id == level_config['id'])

    for monster in level_config['monsters']:
        character_class = monster['character_class']
        new_character_class = CharacterClass(
            class_name=character_class['name'],
            max_hp=character_class['max_hp'],
            hp=character_class['hp'],
            defense=character_class['defense'],
            attack=character_class['attack'],
            speed=character_class['speed'],
        )
        new_character_class.save()

        new_monster = Character(
            level=level,
            name=monster['name'],
            ascii_char=monster['ascii_char'],
            fgcolor=json.dumps(monster['fgcolor']),
            bgcolor=json.dumps(monster['bgcolor']),
            character_state=monster['character_state'],
            character_class=new_character_class,
            inventory=Inventory()
        )
        new_monster.save()
Exemplo n.º 2
0
 def test_dungeon_contains_player(self):
     player = Character.get(Character.name == 'player')
     self.assertEqual(player.level.level_id, 1)
     self.assertEqual(player.ascii_char, '@')
     self.assertEqual(player.character_state, 'alive')
     self.assertIsNotNone(player.dungeon_object.coords)
     self.assertEqual(type(json.loads(player.dungeon_object.coords)), list)
    def play_game(self):
        """
        The main game loop
        """
        while True:  # Continue in an infinite game loop.
            self.game_state = 'playing' if self.player.character_state == 'alive' else None
            self.console_manager.main_console.clear()  # Blank the console.
            self.render_all()
            self.monsters = [
                m for m in (Character.select().join(DungeonLevel).where(
                    (DungeonLevel.level_id == self.dungeon.level.level_id)
                    & (Character.name != 'player')))
            ]
            self.items = [
                item for item in (Item.select().join(DungeonLevel).where((
                    DungeonLevel.level_id == self.dungeon.level.level_id)))
            ]

            if self.player.character_state == 'dead':
                CONSOLES['status'].drawStr(0, 4, 'You have died!')

            # TODO: Fix win condition
            # elif player.character_state == 'done':
            #     STATUS.move(0, 4)
            #     STATUS.printStr('CONGRADULATIONS!\n\nYou have found a Cone of Dunshire!')

            tdl.flush()  # Update the window.
            self.listen_for_events()
Exemplo n.º 4
0
 def test_dungeon_contains_monsters(self):
     monsters = [
         m for m in Character.select().join(DungeonLevel).where(
             (DungeonLevel.level_id == 1) & (Character.name != 'player'))
     ]
     self.assertEqual(len(monsters), 3)
     for m in monsters:
         self.assertIsNotNone(m.dungeon_object.coords)
         self.assertEqual(type(json.loads(m.dungeon_object.coords)), list)
Exemplo n.º 5
0
def load_player():
    character_class = PLAYER['character_class']
    new_character_class = CharacterClass(
        class_name=character_class['name'],
        max_hp=character_class['max_hp'],
        hp=character_class['hp'],
        defense=character_class['defense'],
        attack=character_class['attack'],
        speed=character_class['speed'],
    )
    new_character_class.save()

    new_player = Character(
        name=PLAYER['name'],
        ascii_char=PLAYER['ascii_char'],
        fgcolor=json.dumps(PLAYER['fgcolor']),
        bgcolor=json.dumps(PLAYER['bgcolor']),
        character_state=PLAYER['character_state'],
        character_class=new_character_class,
        inventory=Inventory()
    )
    new_player.save()
 def init_dungeon(self, level):
     self.dungeon_generator.generate(level)
     self.dungeon = (Dungeon.select().join(DungeonLevel).where(
         DungeonLevel.level_id == level.level_id).get())
     self.player = Character.get(Character.name == 'player')
     self.maze = [[
         DungeonTile(tile_dict['x'],
                     tile_dict['y'],
                     tile_dict['is_blocked'],
                     is_explored=tile_dict['is_explored'],
                     is_ground=tile_dict['is_ground'],
                     contains_object=tile_dict['contains_object'],
                     block_sight=tile_dict['block_sight'])
         for tile_dict in row
     ] for row in json.loads(self.dungeon.maze)]
Exemplo n.º 7
0
    def place_player(self, tile):
        """
        Place the player in the maze.
        """
        dungeon_object = DungeonObject(coords=json.dumps((tile.x, tile.y)),
                                       blocks=True)

        player = Character.get(Character.name == 'player')
        player.level = self.level
        player.dungeon_object = dungeon_object

        dungeon_object.save()
        player.save()

        tile.contains_object = True
Exemplo n.º 8
0
def character_single(request, pk, format=None):
    try:
        character = Character.objects.get(pk=pk)
    except Character.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)
    if request.method == "PUT":
        print(request.data)
        serializer = CharacterSerializer(character, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    elif request.method == "DELETE":
        character = Character.get_object(pk)
        character.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
Exemplo n.º 9
0
def register(request):
    """
    Register the character (base information -> username, pass, mail)
    """
    context = RequestContext(request)
    register = False
    if request.method == 'POST':
        uniform = CharForm(data=request.POST)
        if uniform.is_valid():
            if uniform.cleaned_data['type'] == 'h':
                if Character.objects.filter(username=uniform.cleaned_data['username']).count() <= 0:
                    # create Hero
                    c = Character()
                    c.username = uniform.cleaned_data['username']
                    c.set_password(uniform.cleaned_data['password'])
                    c.email = uniform.cleaned_data['email']

                    r = Race.objects.all()[0]
                    c.race = r

                    c.save()
                    register = True
                    return HttpResponseRedirect(reverse('character.views.describe', args=(c.id,)))
                else:
                    print "Error ? -> existing user"
            else:
                if Character.objects.filter(username=uniform.cleaned_data['username']).count() <= 0:
                    # create GM -> gm->User
                    g = GM()
                    g.username = uniform.cleaned_data['username']
                    g.set_password(uniform.cleaned_data['password'])
                    g.email = uniform.cleaned_data['email']
                    g.save()
                    register = True
                    return render_to_response('system/main.html', {'master': g, 'reg': register}, context)
                else:
                    print "Error existing gm"
        else:
            print uniform.errors
    else:
        uniform = CharForm()

    return render_to_response('register/register.html', {'uniform': uniform, 'registered': register}, context)
Exemplo n.º 10
0
def do_character_travel(character: Character):
    if character.travel_destination is not None:
        travel_check = character.check_travelability(
            character.travel_destination)
        if travel_check is not None:
            pass
        else:
            travel_time, destination = character.perform_travel(
                character.travel_destination)
            character.add_notification(
                'messaging/messages/travel.html',
                'You arrive to {}'.format(destination.name),
                {
                    'travel_time': travel_time,
                    'destination': destination
                }
            )
        character.travel_destination = None
        character.save()
Exemplo n.º 11
0
 def test_can_create_character(self):
     character = Character(1)
     character.save()
     self.assertIsNotNone(character)
Exemplo n.º 12
0
def createCharacter(request):
    name = request.POST['name']
    character = Character(name=name, user_id=request.user.id)
    character.save()
    print(1)
    return redirect('/')
Exemplo n.º 13
0
def restore_character_hours(character: Character):
    character.hours_in_turn_left = 15*24
    if character.get_battle_participating_in() is not None:
        character.hours_in_turn_left /= 2
    character.save()
Exemplo n.º 14
0
    def generate(self, level):
        """
        Generates a new dungeon based the level
        @param level:
        """
        width = 80
        height = 45
        max_rooms = level.max_rooms
        max_room_size = level.max_room_size
        min_room_size = level.min_room_size

        self.level = level
        self.is_final_level = level.is_final_level
        self.dungeon_monsters = deque([
            m for m in Character.select().join(
                DungeonLevel).where((DungeonLevel.level_id == level.level_id)
                                    & (Character.name != 'player'))
        ])

        self.dungeon_items = deque([
            item for item in Item.select().join(DungeonLevel).where((
                DungeonLevel.level_id == level.level_id))
        ])

        # self.max_num_items = level.max_num_items
        # fill map with "blocked" tiles
        self.maze = [[DungeonTile(x, y, True) for y in range(height)]
                     for x in range(width)]

        rooms = []

        for r in range(max_rooms):
            # random width and height
            w = random.randint(min_room_size, max_room_size)
            h = random.randint(min_room_size, max_room_size)
            # random position without going out of the boundaries of the map
            x = random.randint(0, width - w - 1)
            y = random.randint(0, height - h - 1)

            # "DungeonRoom" class makes rectangles easier to work with
            new_room = DungeonRoom(x, y, w, h)

            # run through the other rooms and see if they intersect with this one
            failed = False
            for other_room in rooms:
                if new_room.intersect(other_room):
                    failed = True
                    break

            if not failed:
                # this means there are no intersections, so this room is valid

                # "paint" it to the map's tiles
                self._create_room(new_room)

                # center coordinates of new room, will be useful later
                new_x, new_y = new_room.center()

                if self.num_rooms > 0:
                    # connect it to the previous room with a tunnel
                    # center coordinates of previous room
                    (prev_x, prev_y) = rooms[self.num_rooms - 1].center()

                    # draw a coin (random number that is either 0 or 1)
                    if random.randint(0, 1) == 1:
                        # first move horizontally, then vertically
                        self._create_h_tunnel(prev_x, new_x, prev_y)
                        self._create_v_tunnel(prev_y, new_y, new_x)
                    else:
                        # first move vertically, then horizontally
                        self._create_v_tunnel(prev_y, new_y, prev_x)
                        self._create_h_tunnel(prev_x, new_x, new_y)

                # finally, append the new room to the list
                rooms.append(new_room)
                self.num_rooms += 1

        self.place_monsters_in_rooms()
        self.place_items_in_rooms()
        # if not level.final_level:
        #     self.place_stairs(rooms)

        # connect them with a tunnel
        self._create_h_tunnel(25, 55, 23)

        serialized_maze = json.dumps([[{
            'x': tile.x,
            'y': tile.y,
            'is_blocked': tile.is_blocked,
            'is_explored': tile.is_explored,
            'is_ground': tile.is_ground,
            'contains_object': tile.contains_object,
            'block_sight': tile.block_sight
        } for tile in row] for row in self.maze])

        new_dungeon = Dungeon(level=level,
                              width=width,
                              height=height,
                              maze=serialized_maze)
        new_dungeon.save()