Example #1
0
    def _init_map_and_cm(self,mapName):
        if mapName == "srandom" or mapName == "sRandom" or mapName == "sr" or mapName == "sR":
            # Single player random -> adds AI
            self.mapName = str(random.randint(100,10000))
            m = Map("random", numPlayers = 2, AIPlayers = ["1"], seed = int(self.mapName))
        elif mapName == "random" or mapName == "Random" or mapName == "r" or mapName == "R":
            # Multi player random -> doesn't add AI
            self.mapName = str(random.randint(100,10000))
            m = Map("random", numPlayers = 2, seed = int(self.mapName))
        elif mapName.isdigit():
            m = Map("random", numPlayers = 2, seed = int(mapName))
            self.mapName = mapName
        else:
            m = Map(os.path.join("maps", mapName + ".map"))
            self.mapName = mapName
        # self.map = Map(os.path.join("maps", "random", "random487.map"))
        self.cm = collision_model.CollisionManagerGrid(
            -BLEED, m.w * CELL_SIZE + BLEED, -BLEED, m.h * CELL_SIZE + BLEED, CELL_SIZE / 2, CELL_SIZE / 2)
        m.cm = self.cm
        self.scroller = ScrollingManager(viewport=director.window)
        self.scroller.add(m)

        self.h = CELL_SIZE * m.h
        if self.h < WINDOW_HEIGHT:
            self.h = WINDOW_HEIGHT

        self.w = CELL_SIZE * m.w
        if self.w < WINDOW_WIDTH:
            self.w = WINDOW_WIDTH

        return m
Example #2
0
 def __init__(self, screen_size):
     self.screen = pygame.display.set_mode(screen_size, pygame.FULLSCREEN)
     self.screen.fill([255, 255, 255])
     self.map = Map(self.screen, screen_size)
     self.strategy = Strategy(self.screen, screen_size)
     self.information = Information(self.screen, screen_size)
     self.fullmap = FullMap(self.screen, screen_size)
Example #3
0
class Main:
    def __init__(self, screen_size):
        self.screen = pygame.display.set_mode(screen_size, pygame.FULLSCREEN)
        self.screen.fill([255, 255, 255])
        self.map = Map(self.screen, screen_size)
        self.strategy = Strategy(self.screen, screen_size)
        self.information = Information(self.screen, screen_size)
        self.fullmap = FullMap(self.screen, screen_size)

    def run(self):
        clock = pygame.time.Clock()
        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    return
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        pygame.quit()
                        return
                # Update all the modules
                self.map.update(event)
                self.strategy.update(event)
                self.fullmap.update()
                #               self.DroneI.update()
                pygame.display.update()
                clock.tick(60)
Example #4
0
    def load_data(self):
        root_folder = path.dirname(__file__)
        img_folder = path.join(root_folder, "images")
        fx_folder = path.join(root_folder, "sound")

        self.all_sprites = pygame.sprite.Group()
        self.walls = pygame.sprite.Group()
        self.fruits = pygame.sprite.Group()

        # MAPS WITHOUT COLLISION
        self.map = Map()
        self.map.load_from_file(MAP)
        self.map.create_sprites_from_map_data(self)

        # Load images
        self.head_image = pygame.image.load(path.join(
            IMG_FOLDER, SNAKE_HEAD)).convert_alpha()

        self.body_image = pygame.image.load(path.join(
            IMG_FOLDER, SNAKE_BODY)).convert_alpha()

        self.fruit_image = pygame.image.load(path.join(IMG_FOLDER,
                                                       FRUIT)).convert_alpha()

        # self.wally_image = pygame.image.load(
        #     path.join(IMG_FOLDER, WALL)).convert_alpha()

        # Load FX
        self.music = pygame.mixer.music.load(
            path.join(FX_FOLDER, BACKGROUND_MUSIC))
Example #5
0
 def build_output_based_on_hydrolic(self, water_shell_map_ascii_name,
                                    rpt_file,
                                    link_col_name,
                                    limit_node,
                                    inp_file_name,
                                    limit=1,
                                    merge_nodes=None):
     #   merge_nodes format: {1: [1,2,3], 2: [5], 6: [6]}
     sub_dic = self.build_sub_dicts_by_inp_file(inp_file_name, limit_node, merge_nodes)
     data_list = self.hydrolic(rpt_file, link_col_name, limit_node, limit, sub_dic)
     for i in range(len(data_list)):
         data_list[i] = int(data_list[i])
     water_shed_map = map_loader.load_map(WaterShellMap, water_shell_map_ascii_name)
     water_shed_m = water_shed_map.map
     self.output_for_watershell = Map()
     self.output_for_watershell.set_config(water_shed_m)
     self.build_basic_output_for_watershell()
     for i in range(len(water_shed_m.matrix)):
         for j in range(len(water_shed_m.matrix[i])):
             pixel = water_shed_m.matrix[i][j]
             if pixel == water_shed_m.no_data_value:
                 continue
             if pixel in data_list:
                 #print("pixel in data list:", pixel)
                 self.output_for_watershell.matrix[i][j] = 1
             else:
                 self.output_for_watershell.matrix[i][j] = 0
     return self.output_for_watershell
Example #6
0
 def test_list_maps(self):
     new_map = Map('xdps0')
     list_of_maps = new_map.list_maps()
     list_of_maps_top = list_of_maps[0]
     self.assertTrue(isinstance(list_of_maps_top, tuple))
     self.assertEqual(2, len(list_of_maps_top))
     self.assertTrue(isinstance(list_of_maps_top[0], str))
     self.assertTrue(isinstance(list_of_maps_top[1], str))
Example #7
0
def response_select(response):
    if response == Responses.map_direction:
        Say.phrase(Responses.map_direction)
        place = None

        while place is None:
            place = SpeechWorker.get_without_capture()
        print(place)
        place_name, directions = Map.get_to_place(place)
        Say.phrase(Responses.place_name(place_name))
        Say.phrase(Responses.directions_intent())

        for direction in directions:
            Say.phrase(direction)

    elif response == Responses.map_current_location:
        current_location = Map.where_am_i()
        for address in current_location:
            Say.phrase(address)

    elif response == Responses.ocr_on:
        OcrObject.flag = True
        Say.phrase(Responses.say_ocr_mode_on)
        OcrObject.ocr_thread = Ocr()
        OcrObject.ocr_thread.start()

    elif response == Responses.stop_ocr:
        OcrObject.flag = False
        OcrObject.ocr_thread.make_scan_page()
        OcrObject.ocr_thread.join()

    elif response == Responses.scan_page:
        if OcrObject.flag:
            Say.phrase(Responses.say_scan_page)
            OcrObject.ocr_thread.make_scan_page()
            ocr_text = OcrObject.ocr_thread.join()
            Say.phrase(ocr_text)
            response_select(Responses.ocr_on)

    elif response == Responses.get_nearest_bus_stop:
        stop_name, directions = Map.get_nearest_bus_stop()
        Say.phrase(Responses.bus_stop_name(stop_name))
        Say.phrase(Responses.directions_intent())

        for direction in directions:
            Say.phrase(direction)

    elif response == Responses.current_time:
        Say.phrase(get_current_time())

    elif response == Responses.name:
        Say.phrase(Responses.name)

    elif response == Responses.hello:
        Say.phrase(Responses.hello)

    else:
        Say.phrase(Responses.not_understand)
Example #8
0
    def _init_map_and_cm(self, mapName):
        if mapName == "srandom" or mapName == "sRandom" or mapName == "sr" or mapName == "sR":
            # Single player random -> adds AI
            self.mapName = str(random.randint(100, 10000))
            m = Map("random",
                    numPlayers=2,
                    AIPlayers=["1"],
                    seed=int(self.mapName))
        elif mapName == "random" or mapName == "Random" or mapName == "r" or mapName == "R":
            # Multi player random -> doesn't add AI
            self.mapName = str(random.randint(100, 10000))
            m = Map("random", numPlayers=2, seed=int(self.mapName))
        elif mapName.isdigit():
            m = Map("random", numPlayers=2, seed=int(mapName))
            self.mapName = mapName
        else:
            m = Map(os.path.join("maps", mapName + ".map"))
            self.mapName = mapName
        # self.map = Map(os.path.join("maps", "random", "random487.map"))
        self.cm = collision_model.CollisionManagerGrid(
            -BLEED, m.w * CELL_SIZE + BLEED, -BLEED, m.h * CELL_SIZE + BLEED,
            CELL_SIZE / 2, CELL_SIZE / 2)
        m.cm = self.cm
        self.scroller = ScrollingManager(viewport=director.window)
        self.scroller.add(m)

        self.h = CELL_SIZE * m.h
        if self.h < WINDOW_HEIGHT:
            self.h = WINDOW_HEIGHT

        self.w = CELL_SIZE * m.w
        if self.w < WINDOW_WIDTH:
            self.w = WINDOW_WIDTH

        return m
Example #9
0
    def build_map_from_ascii(self, ascii_file):
        map = Map()
        map.n_cols = int(ascii_file.readline().replace('ncols',
                                                       '').replace('\n', ''))
        map.n_rows = int(ascii_file.readline().replace('nrows',
                                                       '').replace('\n', ''))
        map.xll_corner = float(ascii_file.readline().replace('xllcorner',
                                                             '').replace(
                                                                 '\n', ''))
        map.yll_corner = float(ascii_file.readline().replace('yllcorner',
                                                             '').replace(
                                                                 '\n', ''))
        map.cell_size = int(ascii_file.readline().replace('cellsize',
                                                          '').replace(
                                                              '\n', ''))
        map.no_data_value = int(ascii_file.readline().replace(
            'NODATA_value', '').replace('\n', ''))
        #
        map.matrix = []
        for i in range(map.n_rows):
            line_str = ascii_file.readline()
            line_list = line_str.split(' ')
            line_list = line_list[:len(line_list) - 1]

            for j in range(len(line_list)):
                line_list[j] = float(line_list[j])
            if len(line_list) > map.n_cols:
                line_list = line_list[:map.n_cols]
            elif len(line_list) < map.n_cols:
                for j in range(map.n_cols - len(line_list)):
                    line_list.append(map.no_data_value)
            map.matrix.append(line_list)
        return map
Example #10
0
 def clear(self):
     self.final_price = 0
     self.price_for_sub = {}
     self.priority_pixels_for_sub = {}
     self.sub = {}
     self.priorities = {}
     self.config_map = Map()
     self.config_map = Map()
     self.output_map = Map()
     self.extra_volume_left = 0
     self.as_extra_volume_left = 0
Example #11
0
    def test_get_fail(self):
        #Arrange
        m = Map("mappy", "somefilepath")
        n = Map("flappy", "anotherfilepath")
        mStore = MapStore()

        mStore.add(m)
        mStore.add(n)

        #Act and Assert
        self.assertIsNone(mStore.get("tappy"))
Example #12
0
    def test_get(self):
        #Arrange
        m = Map("mappy", "somefilepath")
        n = Map("flappy", "anotherfilepath")
        mStore = MapStore()

        mStore.add(m)
        mStore.add(n)

        #Act and Assert
        self.assertEquals(m, mStore.get("mappy"))
Example #13
0
    def game_update(self, data, *args):
        """ Update """
        self.update_count += 1
        if not self.map:
            self.map = Map(data, self.player_index)
            return

        self.map.update(data)
        # Source.
        largest_army = self.map.get_largest_owned_army()
        source = largest_army

        # Destination.
        dest = None
        if (self.map.general_tiles):
            dest = self.map.get_closest_enemy_general_tile(largest_army)
        elif (self.map.enemy_tiles):
            dest = self.map.get_closest_enemy_tile(largest_army)
        elif (self.map.empty_tiles):
            dest = self.map.get_closest_empty_tile(largest_army)

        # Next attack.
        path = self.map.construct_path(largest_army, dest)
        attack_dest = None
        if path:
            attack_dest = path[0]
            # Send attack command.
            self.attack(self.map.coord_to_index(source, self.map.width),
                        self.map.coord_to_index(attack_dest, self.map.width),
                        False)

        #Print to console.
        self.map.print_everything()
        if path:
            print("Moving from " + str(source) + " to " + str(attack_dest) +
                  " towards " + str(dest))
        else:
            print("Moving from " + str(source) + " towards " + str(dest))
        print("Path: " + str(path))
        print("Generals: " + str(self.map.generals))

        # Log to file.
        self.file.write("Turn " + str(self.update_count) + "\n")
        if path:
            self.file.write("Path: " + str(path))
            self.file.write("Source: " + str(source) + ", To: " +
                            str(attack_dest) + "\n")
            self.file.write("Moving toward: " + str(dest) + "\n")
        else:
            self.file.write("THERE ARE NO PATH PLEASE TAKE A LOOK")
            self.file.write("Source: " + str(source) + ", Dest: " + str(dest) +
                            "\n")
        self.file.write("\n-------------------\n")
Example #14
0
 def init(self, sub, priorities):
     self.final_price = 0
     self.price_for_sub = {}
     self.priority_pixels_for_sub = {}
     self.sub = sub
     self.priorities = priorities
     self.config_map = Map()
     self.output_map = Map()
     print("sub:", self.sub)
     self.config_map = self.sub[SubConsts.BASIC_LANDUSE_MAP].map
     self.build_basic_map_for_output_map()
     self.extra_volume_left = self.sub[SubConsts.EXTRA_VOLUME]
     self.as_extra_volume_left = 0
Example #15
0
    def test_list_all(self):
        # Arrange
        mp1 = Map("Test map 1", "")
        mp2 = Map("Test map 2", "")
        store = MapStore()
        store.add(mp1)
        store.add(mp2)

        # Act
        act = store.list_all()

        #Assert
        self.assertEqual(act, ["Test map 1", "Test map 2"])
Example #16
0
 def setup_spritemap(self):
     sheet = SpriteSheet("img/magecity_64p.png", 64, (0,0), (8,44))
     self.men_list = sum(sheet.image_list, [])
     length = len(self.men_list)
     size = (10, int(length/10))
     menu = Map("Palette", self, self.size, size, self.block, self.empty_tile)
     menu.setup(WHITE)
     for i, tile in enumerate(menu.group):
         tile.filename = "{}".format(i)
         tile.image = self.men_list[i]
         if i+1 >= length:
             break
     return menu
Example #17
0
def setup():
    global screen, game_controller, input_controller, main_tileset, map_level_1, player

    # Initializes pygame
    pygame.init()

    # Initializes the screen
    screen = pygame.display.set_mode(constants.SCREEN_SIZE, pygame.DOUBLEBUF)

    # Initializes the game controllers
    game_controller = GameController()
    input_controller = InputController()

    # Load the sprites
    main_tileset = Tileset(constants.FILEPATH_TILESET_MAIN, constants.TILESIZE)

    # Load the maps
    map_level_1 = Map()
    map_level_1.load_background(constants.FILEPATH_LEVEL1_BACKGROUND,
                                main_tileset)
    map_level_1.load_foreground(constants.FILEPATH_LEVEL1_FOREGROUND,
                                main_tileset)
    map_level_1.load_colliders(constants.FILEPATH_LEVEL1_COLLIDERS,
                               main_tileset)

    # Load the player
    player = Player(constants.FILEPATH_CHARSET)
Example #18
0
 def generate_map(cls, taken_spaces_map, room_positions, height, width):
     res = Map(height, width)
     for coordinates, room in room_positions:
         MapGen.place_room(res, room, coordinates)
     for x, line in enumerate(taken_spaces_map):
         for y, space_type in enumerate(line):
             if space_type == 3:
                 res.tile_map[x][y].terrain = ASSETS.get_asset(
                     'tiles', 'base_floor')
             elif space_type in [0, 2, 4]:
                 res.tile_map[x][y].terrain = ASSETS.get_asset(
                     'tiles', 'base_wall')
     res.reload_fov_map()
     return res
Example #19
0
    def test_remove_map_exception(self):
        #Arrange
        m = Map("mappy", "somefilepath")
        n = Map("flappy", "anotherfilepath")
        mStore = MapStore()

        mStore.add(m)
        mStore.add(n)

        mStore.remove(m)

        #Act and Assert
        with self.assertRaises(Exception):
            mStore.remove(m)
Example #20
0
 def __init__(self, size):
     Template.__init__(self, size)
     self.name = "World Editor 1.1"
     self.size = size
     self.block = 32
     self.dt = 0.
     self.empty_tile = pg.image.load("./tiles/Empty_tile_32p.png").convert_alpha()
     self.map_bg = Map("Background", self, self.size, (120,80), self.block, self.empty_tile)
     self.map_mg = Map("Middleground", self, self.size, (120,80), self.block, self.empty_tile)
     self.map_fg = Map("Foreground", self, self.size, (120,80), self.block, self.empty_tile)
     self.poi_map = Map("POI Map", self, self.size, (120,80), self.block, self.empty_tile)
     self.poi_menu = Map("POI Menu", self, self.size, (4,1), self.block, self.empty_tile)
     self.menus = [Map("Menu", self, self.size, (2,14), self.block, self.empty_tile)]
     self.pal_menu = Menu((128, 40), (0,21))
     self.pal_menu.add_buttons(2, ["New", "Pal-1"])
     self.pal_menu.set_bg_color(SUBBUTTON_COLOR)
     self.menu = self.menus[0]
     self.menu.xy[1] += 20
     self.men_list = []
     self.sprite_map = self.setup_spritemap()
     self.sprite_map.xy = [250,0]
     self.clip = pg.Rect(0,0, self.size[0],self.size[1])
     self.c_pos = self.clip.topleft
     self.show_full_map = False
     self.show_poi = False
     self.full_map = None
     self.current_tile = None
     self.current_menu = None
     self.ground_state = None
     self.right_m_pos = None
     self.right_m_button = False
     self.fill = False
     self.m_pos = None
     self.m_select_rect = pg.Rect(1,1,1,1)
     self.menu_button = Button((120, 20), (129,1), "Menu")
     self.pal_button = Button((128,20), (0,0), "Palette")
     self.drop_menu = Menu((120, 160), (129, 21))
     self.drop_menu.add_buttons(5, ["Save", "Load", "Sprites", "See Map", "Info"])
     self.drop_menu.set_bg_color(SUBBUTTON_COLOR)
     self.load_menu = self.setup_loadmenu()
     self.floating_text = FloatingText("no text", self.size)
     self.info_panel = Panel((self.size[0] - self.size[0]/3, self.size[1] - self.size[1]/3), (self.size[0]/6, self.size[1]/6))
     self.info_panel.setup_text([self.name, "Made by Aurelio Aguirre", "", "Use WASD to move around.", "Use E to toggle the Foreground.", "Use R to toggle the Middleground.", "Use Q to toggle the Point of Interest map."])
     self.setup()
     self.setup_poi()
     self.selected_map = self.map_bg
     self.alternative = ALTERNATIVE_MODE
     self.enable_alternative_mode()
Example #21
0
def reset(keep_player=False):
    global SCREEN_SIZE, RANDOM_SEED, MAP, PLAYER

    RANDOM_SEED += 1
    UI.clear_all()
    TurnTaker.clear_all()

    if keep_player:
        PLAYER.refresh_turntaker()
        PLAYER.levels_seen += 1

    else:

        if not PLAYER is None:
            print("Game Over")
            print("%d evidence in %d turns; %d levels seen" %(len(PLAYER.evidence),PLAYER.turns,PLAYER.levels_seen))

        PLAYER = Player()

    if not MAP is None:
        MAP.close()
        del MAP

    MAP = Map.random(RANDOM_SEED,SCREEN_SIZE-(0,4),PLAYER)
    MAP.generate()
Example #22
0
    def hydrology(self, **runoff_landa):
        self.output_hyrology = Map()

        if (runoff_landa.get("runoff_co_map", default=None) is None &
            runoff_landa.get("landa_map", default=None) is None):
            print("you have to give at least 1 map from runoff or landa !")
        else:
            if (runoff_landa.get("runoff_co_map", default=None) is not None) and (
                        runoff_landa.get("landa_map", default=None) is not None):
                runoff_coefficient_map_ascii = runoff_landa.get("runoff_co_map")
                self.landa_map = runoff_landa.get("landa_map")

                self.runoff_coefficient_map = map_loader.load_map(RunoffCoefficient, runoff_coefficient_map_ascii)
                runoff_coefficient_map = self.runoff_coefficient_map.map

                for i in range(len(self.runoff_coefficient_map.matrix)):
                    self.output_hyrology.matrix.append([])
                    for j in range(len(self.runoff_coefficient_map.matrix[i])):
                        if self.runoff_coefficient_map.matrix[i][j] != runoff_coefficient_map.no_data_value:
                            self.output_hyrology.matrix[i].append(
                                self.runoff_coefficient_map.matrix[i][j] + self.landa_map.matrix[i][j])
                        else:
                            self.output_hyrology.matrix[i].append(runoff_coefficient_map.no_data_value)

            else:
                if runoff_landa.get("runoff_co_map", default=None) is not None:
                    self.output_hyrology = self.runoff_coefficient_map
                if runoff_landa.get("landa_map", default=None) is not None:
                    self.output_hyrology = self.landa_map

        return self.output_hyrology
Example #23
0
def reset(keep_player=False):
    global SCREEN_SIZE, RANDOM_SEED, MAP, PLAYER

    RANDOM_SEED += 1
    UI.clear_all()
    TurnTaker.clear_all()

    if keep_player:
        PLAYER.refresh_turntaker()
        PLAYER.levels_seen += 1

    else:

        if not PLAYER is None:
            print("Game Over")
            print("%d evidence in %d turns; %d levels seen" %
                  (len(PLAYER.evidence), PLAYER.turns, PLAYER.levels_seen))

        PLAYER = Player()

    if not MAP is None:
        MAP.close()
        del MAP

    MAP = Map.random(RANDOM_SEED, SCREEN_SIZE - (0, 4), PLAYER)
    MAP.generate()
Example #24
0
    def test_list_all(self):
        #Arrange
        m = Map("mappy", "somefilepath")
        n = Map("flappy", "anotherfilepath")
        mStore = MapStore()

        mStore.add(m)
        mStore.add(n)

        #Act and Assert
        listy = []

        for i in mStore.list_all():
            listy.append(mStore.get(i))

        self.assertIn(m, listy)
        self.assertIn(n, listy)
Example #25
0
def init_map(map_name):
    """Initialize map

    Creates Map object, game window, sets references and globals and adds character.
    """
    global screen
    global tile_size
    global diagonal_move
    map = Map(map_name,
              tile_size,
              menu_height,
              diagonal_movement=diagonal_move)
    map_size = map.get_size()
    create_screen(map_size)
    map.set_screen(screen)
    set_current_map(map)
    add_character()
Example #26
0
 def loadmap(self, filename):
     load = LoadMap(filename)
     maplist = []
     for m in load.maps.values():
         a_map = Map(m["info"]["name"], self, m["info"]["size"], m["info"]["grid"], m["info"]["block"], self.empty_tile)
         if m["info"]["name"] == "Foreground" or m["info"]["name"] == "Middleground":
             a_map.setup(m["info"]["color"], 200)
         elif m["info"]["name"] == "POI Map":
             a_map.setup(m["info"]["color"], 150)
         else:
             a_map.setup(m["info"]["color"])
         for t in a_map.group:
             for i in m["tiles"]:
                 if list(t.rect.topleft) in m["tiles"][i]:
                     t.filename = i
                     if i[0] == "P":
                         t.image = self.poi_dict[i]
                         t.dirty = 1
                     else:
                         t.image = self.men_list[int(i)]
                         t.dirty = 1
         maplist.append(a_map)
     for j in maplist:
         if j.name == "Background":
             self.map_bg = j
         if j.name == "Middleground":
             self.map_mg = j
         if j.name == "Foreground":
             self.map_fg = j
         if j.name == "POI Map":
             self.poi_map = j
     print("Loading from file...")
Example #27
0
 def next_map(self):
     maps = glob('maps/*json')
     try:
         selected = maps[maps.index(self.selected_map) + 1]
     except (IndexError, ValueError):
         selected = maps[0]
     self.selected_map = selected
     settings.setValue('map', self.selected_map)
     return Map.read_spec(selected)['title']
Example #28
0
 def next_map(self):
     maps = glob('maps/*json')
     try:
         selected = maps[maps.index(self.selected_map) + 1]
     except (IndexError, ValueError):
         selected = maps[0]
     self.selected_map = selected
     settings.setValue('map', self.selected_map)
     return Map.read_spec(selected)['title']
Example #29
0
 def loadmaps(self):
     f = open('data/justrightmaps.yaml', 'r')
     dirtymaps = yaml.load(f, Loader=yaml.FullLoader)['Maps']
     pprint(dirtymaps)
     f.close()
     self.maps = {}
     for M in dirtymaps:
         MP = Map(M, dirtymaps[M])
         self.maps[M] = MP
Example #30
0
    def test_add_success(self):
        # Arrange
        mp = Map("Test map", "")
        store = MapStore()

        # Act
        store.add(mp)

        # Assert
        self.assertEqual(store.get("Test map"), mp)
Example #31
0
    def test_add_map_exception(self):
        #Arrange
        m = Map("mappy", "somefilepath")
        mStore = MapStore()

        mStore.add(m)

        #Act and Assert
        with self.assertRaises(Exception):
            mStore.add(m)
Example #32
0
    def get(self):
        mid = long(self.request.get('mid'))

        m = Map.get_by_id(mid)
        g = Game(mid=mid)
        g.put()
        gid = g.key().id()

        result = m.populate(gid)
        self.response.out.write(str(gid))
Example #33
0
    def test_get_success(self):
        # Arrange
        mp = Map("Test map", "")
        store = MapStore()
        store.add(mp)
        
        # Act
        act = store.get("Test map")

        # Assert
        self.assertEqual(act, mp)
Example #34
0
 def __init__(self, *args, **kwargs):
     QDeclarativeView.__init__(self, *args, **kwargs)
     context = self.rootContext()
     context.setContextProperty('menu', self)
     map_file = settings.value('map')
     if not map_file:
         map_file = glob('maps/*json')[0]
     self.selected_map = map_file
     self.setSource('menu.qml')
     self.setResizeMode(QDeclarativeView.SizeRootObjectToView)
     self.rootObject().initial_map(Map.read_spec(map_file)['title'])
Example #35
0
 def __init__(self, *args, **kwargs):
     QDeclarativeView.__init__(self, *args, **kwargs)
     context = self.rootContext()
     context.setContextProperty('menu', self)
     map_file = settings.value('map')
     if not map_file:
         map_file = glob('maps/*json')[0]
     self.selected_map = map_file
     self.setSource('menu.qml')
     self.setResizeMode(QDeclarativeView.SizeRootObjectToView)
     self.rootObject().initial_map(Map.read_spec(map_file)['title'])
Example #36
0
def main(screen):
    init_curses(screen)

    game_map = Map("map1")
    player = Player(game_map)
    textures = ["wall1", "wall2", "dragon", "tree"]

    Controller(Renderer(screen, player, textures)).start()

    curses.flushinp()
    curses.endwin()
Example #37
0
    def test_remove_success(self):
        # Arrange
        mp = Map("Test map", "")
        store = MapStore()
        store.add(mp)

        # Act
        store.remove(mp)

        # Assert
        self.assertEqual(store.list_all(), [])
Example #38
0
class TestMaps(unittest.TestCase):

    def setUp(self):
        Map.json_file = 'test_maps.json'
        self.test_data = Map('test_map', 32, 32)

    def test_load_map_from_json(self):
        loaded_test_map = self.test_data.load_map_from_json()
        self.assertEqual((16 * 16), len(loaded_test_map)
                         * len(loaded_test_map[0]))
        self.assertEqual(loaded_test_map[0][0].movement_cost, 0)
        self.assertEqual(loaded_test_map[10][8].movement_cost, 10)
Example #39
0
  def add_map(self, model, subject):
    m = Map(subject.uri)

    statement = RDF.Statement(subject,
                              RDF.Uri("http://www.w3.org/2000/01/rdf-schema#domain"),
                              None)
    for s in model.find_statements(statement):
      if s.object.is_resource():
        m.domain = str(s.object.uri)

    statement = RDF.Statement(subject,
                              RDF.Uri("http://www.w3.org/2000/01/rdf-schema#range"),
                              None)
    for s in model.find_statements(statement):
      if s.object.is_resource():
        m.range = str(s.object.uri)

    statement = RDF.Statement(subject,
                              RDF.Uri("http://okfnpad.org/flow/0.1/sparql"),
                              None)
    for s in model.find_statements(statement):
      if s.object.is_literal():
        m.sparql = s.object.literal_value['string']

    
    statement = RDF.Statement(subject,
                              RDF.Uri("http://okfnpad.org/flow/0.1/sparql-not"),
                              None)
    for s in model.find_statements(statement):
      if s.object.is_literal():
        m.sparql = s.object.literal_value['string']
	m.sparql_negate = 1


    statement = RDF.Statement(subject,
			      RDF.Uri("http://okfnpad.org/flow/0.1/assumption"),
			      None)
    for s in model.find_statements(statement):
      if s.object.is_literal():
	m.assumption = s.object.literal_value['string']

    # Add it in the list only if completed
    if m.is_completed():
      self.maps.append(m)
Example #40
0
    def __init__(self):
        super(GameController, self).__init__()
        self.selectedUnits = []  # Stores units that have been selected

        self.map = Map(os.path.join("maps", "level1.map"))
        self.map.draw_map()
        self.cm = collision_model.CollisionManagerGrid(
            0.0, self.map.w * CELL_SIZE, 0.0, self.map.h * CELL_SIZE, 32.0, 32.0)
        self.map.cm = self.cm

        self.scroller = ScrollingManager(viewport=director.window)
        self.scroller.add(self.map)

        # Arbitrary starting location. I suggest this is info be stored in each map file.

        self.scroller.set_focus((self.map.w * CELL_SIZE) /
                                16, (self.map.h * CELL_SIZE) / 16)
        self.infoLayer = InfoLayer(self.map, self.scroller, None)
        self.statusMenu = StatusMenu()
        self.add(self.infoLayer)

        self.curAction = None

        self.level = 1
        self.tutorial = Tutorial(self.level, self)

        self.horizontalSize = CELL_SIZE * self.map.w
        self.verticalSize = CELL_SIZE * self.map.h
        # self.mouseClickGraphic = Sprite(os.path.join("images", "menus",
        # "mouse_click_graphic.png"))
        
        #Handshake
        self.is_shake_selected = False
        self.source_handshake = None
        self.handshake_units_selected = []


        if self.horizontalSize < WINDOW_WIDTH:
            self.horizontalSize = WINDOW_WIDTH
        if self.verticalSize < WINDOW_HEIGHT:
            self.verticalSize = WINDOW_HEIGHT
Example #41
0
 def set_map(self, map_path):
     self.map_path = map_path
     self.old_cp = None
     self.game = Game(self)
     self.map = Map(self.game, map_path)
     self.map.failed.connect(self.sound.boom)
     self.map.failed.connect(self.failed)
     self.map.finished.connect(self.sound.win)
     self.rootObject().set_map_name(self.map.title)
     if hasattr(self, 'robot'):
         self.rootObject().robot_to_active_pos(*self.robot.position)
     self.draw_map()
     if self.map.background:
         self.rootObject().set_custom_background(self.map.background)
     self.map.finished.connect(self.win)
     if getattr(self, 'rt', None):
         self.rt.quit()
     try:
         self.robot.stop = True
     except AttributeError:
         pass
     self.rt = RoboThread()
     self.rt_pool.append(self.rt)
Example #42
0
class GameApp(QDeclarativeView):
    block_tpls = {
        Block: 'blocks/block.qml',
        Bomb: 'blocks/bomb.qml',
        Space: 'blocks/space.qml',
    }
    #current = 'blocks/active.qml'
    mega_start = Signal()

    def __init__(self, menu, settings, *args, **kwargs):
        QDeclarativeView.__init__(self, *args, **kwargs)
        self.exception = None
        self.sound = Sounder()
        self.menu = menu
        self.settings = settings
        self.rt_pool = []#fix fault
        self.setWindowTitle('findZbomb!')
        self.setSource('interface.qml')
        self.set_map(None)
        self.redraw()
        context = self.rootContext()
        context.setContextProperty('obj', self)
        self.mega_start.connect(self._mega_start)
        self.setResizeMode(QDeclarativeView.SizeRootObjectToView)
        code = self.settings.value('code')
        if code:
            self.rootObject().set_code(code)

    def set_map(self, map_path):
        self.map_path = map_path
        self.old_cp = None
        self.game = Game(self)
        self.map = Map(self.game, map_path)
        self.map.failed.connect(self.sound.boom)
        self.map.failed.connect(self.failed)
        self.map.finished.connect(self.sound.win)
        self.rootObject().set_map_name(self.map.title)
        if hasattr(self, 'robot'):
            self.rootObject().robot_to_active_pos(*self.robot.position)
        self.draw_map()
        if self.map.background:
            self.rootObject().set_custom_background(self.map.background)
        self.map.finished.connect(self.win)
        if getattr(self, 'rt', None):
            self.rt.quit()
        try:
            self.robot.stop = True
        except AttributeError:
            pass
        self.rt = RoboThread()
        self.rt_pool.append(self.rt)

    def draw_map(self):
        #grid = self.rootContext().contextProperty('mapGrid')
        root = self.rootObject()
        prepared_map = map(lambda items:
            map(lambda item: self.block_tpls[type(item)], items),
        self.map.map)
        root.draw_map(prepared_map)
        self.rootObject().robot_to_active_pos(*self.map.position)

        #print grid

    def redraw(self):
        if self.old_cp != self.map.cur_position:
            #self.draw_map()
            self.old_cp = self.map.cur_position
            if hasattr(self, 'robot'):
                self.rootObject().set_map_count(self.robot.moves)
                self.rootObject().robot_to_active_pos(*self.robot.position)
        if self.exception:
            if hasattr(self, 'robot'):
                self.robot.stop = True
            self.rootObject().show_exception(unicode(self.exception))
            self.exception = None
        QTimer.singleShot(300, self.redraw)

    @Slot(result=int)
    def start(self):
        self.set_map(self.map_path)
        self.rootObject().remove_notify()
        self.code = 'class Robot(BaseRobot):\n%s' % self.rootObject().get_code()
        self.mega_start.emit()
        return 0

    @Slot()
    def _mega_start(self):
        self.rt.start()

    def _start(self):
        Robot = BaseRobot#fix code highlighting
        self.exception = None
        try:
            exec(self.code)
            self.robot = Robot(self.map)
            self.map.put_robot(self.robot)
            self.rootObject().robot_to_active_pos(*self.robot.position)
        except Exception, e:
            self.exception = e
Example #43
0
from player import *

# Constants
TILE_SIZE = 32
INCREMENT_DISTANCE = 4  # By how much the coordinates change every frame.

# Runtime variables
clock = pygame.time.Clock()

# Resource variables
FPS = 20
x_size = 9  # Should always be odd, so that the player is in the dead middle
y_size = 9
screen = pygame.display.set_mode((x_size * TILE_SIZE, y_size * TILE_SIZE))
player_coords = (x_size / 2 * TILE_SIZE, y_size / 2 * TILE_SIZE)
grid = Map("map", (x_size, y_size))
grid.display(screen)
pygame.display.update()

p = Player()
p.initialize_frames()

pressed = {}
pressed["up"] = False
pressed["down"] = False
pressed["left"] = False
pressed["right"] = False

locked = False

Example #44
0
class GameController(Layer, EventDispatcher):
    is_event_handler = True

    def __init__(self):
        super(GameController, self).__init__()
        self.selectedUnits = []  # Stores units that have been selected

        self.map = Map(os.path.join("maps", "level1.map"))
        self.map.draw_map()
        self.cm = collision_model.CollisionManagerGrid(
            0.0, self.map.w * CELL_SIZE, 0.0, self.map.h * CELL_SIZE, 32.0, 32.0)
        self.map.cm = self.cm

        self.scroller = ScrollingManager(viewport=director.window)
        self.scroller.add(self.map)

        # Arbitrary starting location. I suggest this is info be stored in each map file.

        self.scroller.set_focus((self.map.w * CELL_SIZE) /
                                16, (self.map.h * CELL_SIZE) / 16)
        self.infoLayer = InfoLayer(self.map, self.scroller, None)
        self.statusMenu = StatusMenu()
        self.add(self.infoLayer)

        self.curAction = None

        self.level = 1
        self.tutorial = Tutorial(self.level, self)

        self.horizontalSize = CELL_SIZE * self.map.w
        self.verticalSize = CELL_SIZE * self.map.h
        # self.mouseClickGraphic = Sprite(os.path.join("images", "menus",
        # "mouse_click_graphic.png"))
        
        #Handshake
        self.is_shake_selected = False
        self.source_handshake = None
        self.handshake_units_selected = []


        if self.horizontalSize < WINDOW_WIDTH:
            self.horizontalSize = WINDOW_WIDTH
        if self.verticalSize < WINDOW_HEIGHT:
            self.verticalSize = WINDOW_HEIGHT

    def on_enter(self):
        super(GameController, self).on_enter()

        # TODO: this will at somepoint be an array of players
        # but it will go in the server code for multiplayer
        self.player = Player(0, self.map, self.cm, PLAYER_COLORS[0])
        self.player.setup(
        )  # Adds starting troops/buildings/research from the map file.

        self.ai = ComputerPlayer(
            1, self.map, self.cm, PLAYER_COLORS[1], self.player)
        self.ai.setup(
        )  # Adds starting troops/buildings/research from the map file.

        self.players = [self.player, self.ai]
        self.infoLayer.player = self.player.ID
        self.ai.run_basic_ai()

        # tutorial stuff
        if SHOW_TUTORIAL:
            self.tutorial.first_prompt("on_enter")
            self.player.push_handlers(
                self.tutorial.player_add_troop, self.tutorial.player_unit_attack, self.tutorial.player_add_building)
            self.push_handlers(
                self.tutorial.click_on_move, self.tutorial.click_on_action)

        self.player.push_handlers(self.on_loss)
        self.ai.push_handlers(self.on_loss)

        for player in self.players:
            self.schedule(player.step)
        self.schedule(self.step)

        self.bindings = {  # key constant : button name
            key.LEFT: 'left',
            key.RIGHT: 'right',
            key.UP: 'up',
            key.DOWN: 'down'
        }

        self.buttons = {  # button name : current value, 0 not pressed, 1 pressed
            'left': 0,
            'right': 0,
            'up': 0,
            'down': 0
        }

        self.mouse_flag = {
            'x': 0,
            'y': 0
        }

    def on_loss(self, loser):
        if loser.ID == 0:
            director.push(Scene(self.lost))
        else:
            director.push(Scene(self.won))

    def step(self, dt):
        # step is called every frame
        if self.mouse_flag["x"] == 0 and self.mouse_flag["y"] == 0:  # keyboard scrolling
            buttons = self.buttons
            move_dir = eu.Vector2(buttons['right'] - buttons['left'],
                                  buttons['up'] - buttons['down'])
        else:  # mouse scrolling
            move_dir = eu.Vector2(self.mouse_flag['x'], self.mouse_flag['y'])
        newPos = move_dir.normalize() * dt * MAP_SCROLL_SPEED
        newx, newy = self.clamp(newPos)
        self.scroller.set_focus(newx, newy)

    def clamp(self, pos):
        x, y = pos
        newx = self.scroller.fx + x
        newy = self.scroller.fy + y
        if newx <= 1:
            newx = 1.0
        elif newx >= self.horizontalSize - WINDOW_WIDTH:
            newx = self.horizontalSize - WINDOW_WIDTH + 1.0
        if newy <= 1:
            newy = 1.0
        elif newy >= self.verticalSize - WINDOW_HEIGHT:
            newy = self.verticalSize - WINDOW_HEIGHT + 1.0
        return newx, newy

    def on_mouse_motion(self, x, y, dx, dy):
        # x,y = self.scroller.pixel_from_screen(x,y)
        if x == 0:
            self.mouse_flag["x"] = -1.0
            self.mouse_flag["y"] = float(y - (WINDOW_HEIGHT /
                                         2)) / WINDOW_HEIGHT
        elif x == WINDOW_WIDTH or x == WINDOW_WIDTH - 1:
            self.mouse_flag["x"] = 1.0
            self.mouse_flag["y"] = float(y - (WINDOW_HEIGHT /
                                         2)) / WINDOW_HEIGHT
        elif y == 0:
            self.mouse_flag["y"] = -1.0
            self.mouse_flag["x"] = float(x - (WINDOW_WIDTH / 2)) / WINDOW_WIDTH
        elif y == WINDOW_HEIGHT or y == WINDOW_HEIGHT - 1:
            self.mouse_flag["y"] = 1.0
            self.mouse_flag["x"] = float(x - (WINDOW_WIDTH / 2)) / WINDOW_WIDTH
        else:
            self.mouse_flag["x"] = 0
            self.mouse_flag["y"] = 0

    def on_key_press(self, k, modifiers):
        if k == key.ESCAPE:
            theme_player.fadeout()

        binds = self.bindings
        if k in binds:
            self.buttons[binds[k]] = 1
            return True
        return False

    def on_key_release(self, k, m):
        # Determine the type of units we've selected so we can assign hotkeys
        # appropriately

        selType = None

        if len(self.selectedUnits) > 0:
            selType = type(self.selectedUnits[0])

        actNum = None
        if selType != None and issubclass(selType, Troop):
            actNum = {
                key.A: 0,  # A
                key.S: 1,  # S
                key.D: 2  # D
            }.get(k, None)
        elif selType != None and issubclass(selType, Building):
            actNum = {
                key.Q: 7,  # Q
                key.W: 3,  # W
                key.E: 5,  # E
                key.A: 1,  # A
                key.D: 0,  # D
                key.Z: 6,  # Z
                key.X: 2,  # X
                key.C: 4,  # C
            }.get(k, None)

        if actNum != None:
            # Loop through selected units and execute action associated with
            # hotkey.

            for unit in self.selectedUnits:
                # Make sure this unit has the action we're trying to execute
                # with the hotkey
                if actNum < len(unit.actionList):
                    # Execute the action. Also deselects the unit (all actions
                    # automatically deselect)

                    self.execute_action(unit.actionList[actNum], unit)

        # scrolling logic
        binds = self.bindings
        if k in binds:
            self.buttons[binds[k]] = 0
            return True
        return False

    # def on_mouse_press(self, x, y, buttons, modifiers):
    #     # Add the mouse down sprite to the map where the mouse was pressed.
    #     x, y = self.scroller.pixel_from_screen(x, y)
    #     self.mouseClickGraphic.position = euclid.Vector2(x, y)
    #     self.map.add(self.mouseClickGraphic, z = 10)

    def on_mouse_release(self, x, y, buttons, modifiers):
        # Mouse clicked. Perform unit selection, check for button presses, and executes actions.
        # Check if we clicked the minimap - if so, don't perform any selection logic on units behind the map.
        # for i in range(1000,1,-0.25):
            # self.mouseClickGraphic.scale = 0.001 * i
        # self.map.remove(self.mouseClickGraphic)
        if self.statusMenu.cm.objs_touching_point(x,y):
            director.pop()

        if self.infoLayer.miniMapToggled:
            # First check to see if the minimap is toggled to save our CM from
            # checking collisions if the minimap isn't up.
            minimap = self.infoLayer.cm.objs_touching_point(
                x - self.infoLayer.position[0], y - self.infoLayer.position[1])
            if self.infoLayer.miniMap in minimap:
                return
        x, y = self.scroller.pixel_from_screen(x, y)
        clicked_units = self.cm.objs_touching_point(x, y)

        for unit in clicked_units:
            if type(unit) == SurrenderButton:
                director.push(Scene(self.lost))

        # Set selectedUnits. If a vertex is clicked on, all troops in the
        # vertex are selected/unselected
        if buttons == 1:  # Left button clicked
            # Did we click on an action button?
            actionButton = get_action_button_clicked(clicked_units)
            if actionButton:
                # Clicked on an action button. Execute the action.
                self.execute_action(actionButton.name, actionButton.unitParent)
            elif clicked_units:
                if self.curAction:
                    # Attack
                    self.player.unit_attack(self.selectedUnits, clicked_units)
                    self.curAction = None
                else:
                    # If clicked on vertex or clicked on a single unit, switch
                    # select state of all units in vertex
                    self.select_units(clicked_units)
                    if constants.SOUND:
                        self.play_sound("click_troop.wav")
        # Move
        if clicked_units != set([]) and self.selectedUnits != []:
            if buttons == 4:  # Button == 4 means right click
                # Perform move action.
                self.execute_move(clicked_units)
            return True

    def __deselect_units_of_type(self, units, unitType):
        # Deselect buildings if we're selecting Troops.
        unitsToDeselect = []
        for unit in self.selectedUnits:
            if issubclass(type(unit), unitType):
                unitsToDeselect.append(unit)
        if unitsToDeselect != []:
            self.player.switch_units_select_state(
                unitsToDeselect, self.selectedUnits)

    def select_units(self, clicked_units):
        # Performs all selection logic. Sets the select state (inverts it) of
        # units that were just clicked on.
        if len(clicked_units) >= 1:
            clicked = None
            for item in clicked_units:
                if type(item) == Vertex:
                    clicked = item
                    break
                else:
                    clicked = item
            
            #Handshake
            if type(clicked) == Handshake:
                #seeing if the shake action is enabled
                if(self.source_handshake != None):
                    if  self.source_handshake == clicked:
                        self.is_shake_selected = False
                
                if self.is_shake_selected:
                    #constructing a list of vids
                    adjacency_vid_list = []
                    for vertex in self.source_handshake.curVertex.adjacentVertices:
                        adjacency_vid_list.append(vertex.vid)

                    #checking to see if edge exists already
                    if clicked.curVertex.vid not in adjacency_vid_list:
                        dest_handshake = clicked
                        edge = self.source_handshake.shake(dest_handshake, self.map)
                        self.cm.remove_tricky(self.source_handshake)
                        self.cm.remove_tricky(dest_handshake)
                        self.is_shake_selected = False
                        self.source_handshake = None
                    else:
                        utils.play_sound("error.wav")
                        self.player.switch_units_select_state(
                        [clicked], self.selectedUnits) 
                        self.is_shake_selected = False
                        pass
            else:
                self.is_shake_selected = False
                self.source_handshake = None


            if type(clicked) == Vertex:
                # Deselect all buildings if we're selecting troops.
                self.__deselect_units_of_type(self.selectedUnits, Building)
                self.player.switch_units_select_state(
                    clicked.troops, self.selectedUnits)
        
            elif issubclass(type(clicked), Unit) and clicked.pid == 0:
                # Deselect all troops if we're selecting a building, and vice
                # versa.
                #TODO: use Dave's player building and troop action list instead
                if issubclass(type(clicked), Building):
                    if type(clicked) == SoftwareUpdater:
                        self.player.update_research_action_button(clicked)
                    if type(clicked) == AlgorithmFactory:
                        self.player.update_troop_action_button(clicked)
                    self.__deselect_units_of_type(self.selectedUnits, Troop)
                elif issubclass(type(clicked), Troop):
                    self.__deselect_units_of_type(self.selectedUnits, Building)

                self.player.switch_units_select_state(
                    [clicked], self.selectedUnits)

        else:
            # More than one thing clicked on. Switch select state of all of
            # them.
            self.player.switch_units_select_state(
                clicked_units, self.selectedUnits)  # We COULD change this so only the unit with the higehst Z value get selected.

    def execute_move(self, clickedUnits):
        # Moves the selected troops (self.selectedUnits) to the destination
        # vertex (which is in clickedUnits)
        dest = None
        while type(dest) != Vertex and clickedUnits != ():
            dest = clickedUnits.pop()
        if type(dest) == Vertex:
            for selectedUnit in self.selectedUnits:
                if issubclass(type(selectedUnit), Troop):
                    if selectedUnit.player_move(dest, self.map, self.cm) == True and constants.SOUND:
                        # If we successfully moved, play the move sound.
                        self.play_sound("Move.wav")
                    selectedUnit.set_is_selected(False, self.map, self.cm, self.player)
                    self.selectedUnits = []
                    self.dispatch_event("click_on_move", type(selectedUnit), dest.vid)

    def execute_action(self, actionName, unit):
        # ActionButton <actionButton> clicked. Execute the action associated
        # with the button/building/vertex
        self.curAction = None
        # Need to add conditional to account for resource availability.
        self.player.switch_units_select_state([unit], self.selectedUnits)
        if actionName[0] == "B":
            # BUILD A BUILDING (also deselects the troop)
            if self.player.execute_build_building(actionName[1:], unit, self.selectedUnits) and constants.SOUND:
                self.play_sound("Clock.wav")
        elif actionName[0] == "T":
            # BUILD A TROOP (also deselects the building)
            if self.player.execute_build_troop(actionName[1:], unit, self.selectedUnits) and constants.SOUND:
                self.play_sound("Clock.wav")
        elif actionName[0] == "R":
            # RESEARCH
            if self.player.perform_research(actionName, unit, self.cm) and constants.SOUND:
                self.play_sound("Clock.wav")
        # BEGIN UPGRADES
        elif actionName == "USinkhole":
            unit.upgrade_to_sinkhole(self.player)
        elif actionName == "UPingOfDeath":
            unit.upgrade_to_pod(self.player)
        elif actionName == "UNMap":
            unit.upgrade_to_nmap(self.player)
        # BEGIN UTILITY
         #Handshake
        elif actionName == "Shake":
            self.is_shake_selected = True
            self.source_handshake = unit            
                #if type(troop) == Handshake and troop != unit:
                    #self.source_handshake = troop
                    #print "GOT ME A TROOP TO SELECT"
                    # Got the other selected handshake to shake with
                    #self.source_handshake = troop
                    #print self.source_handshake.pid
                    #print "MY SELECTED HANDSHAKE",troop
                    #unit.shake(troop)
                    # PLAY HANDSHAKE SOUND
                    #break
        elif actionName == "DEL":
            # TODO: we could have multple servers
            if issubclass(type(unit), Server):
                if self.player.numServers == 1:
                    self.add_surrender_button(unit)
            if constants.SOUND:
                self.play_sound("Eraser.wav")
            self.player.on_destruction(unit, self.selectedUnits)
        elif actionName == "CANCEL":
            self.player.cancel_cpu(unit)
        elif actionName == "Encrypt":
            unit.encrypt(unit.curVertex.troops, self.player)
        elif actionName == "Decrypt":
            unit.decrypt(self.player)
        elif actionName == "Ping":
            unit.ping(self.player.on_destruction, self.map, self.cm)

        else:
            self.curAction = actionName
            # dummy array, because we don't want to change self.selectedUnit
        self.dispatch_event("click_on_action", actionName)

    def play_sound(self, filename):
        sound = pyglet.resource.media('sounds/' + filename, streaming=False)
        sound.play()

    # No image, crash game
    def add_surrender_button(self, actionButton):
        self.player.has_server = False
        x = actionButton.position[0]
        y = actionButton.position[1]
        surrender = SurrenderButton(x, y)
        self.map.add(surrender, z=10)
        self.cm.add(surrender)
Example #45
0
from PySide.QtCore import QCoreApplication
from maps import Map
from robot import BaseRobot
from game import Game
import unittest
import sys


class Robot(BaseRobot):
    def on_start(self):
        self.go(self.RIGHT)

    def on_move(self, status):
        if status:
            self.go(self.RIGHT)
        print self.watch(self.RIGHT)


if __name__ == "__main__":
    app = QCoreApplication(sys.argv)
    g = Game()
    m = Map(g)
    r = Robot(m)
    m.put_robot(r)
Example #46
0
class Main(Template):
    def __init__(self, size):
        Template.__init__(self, size)
        self.name = "World Editor 1.1"
        self.size = size
        self.block = 32
        self.dt = 0.
        self.empty_tile = pg.image.load("./tiles/Empty_tile_32p.png").convert_alpha()
        self.map_bg = Map("Background", self, self.size, (120,80), self.block, self.empty_tile)
        self.map_mg = Map("Middleground", self, self.size, (120,80), self.block, self.empty_tile)
        self.map_fg = Map("Foreground", self, self.size, (120,80), self.block, self.empty_tile)
        self.poi_map = Map("POI Map", self, self.size, (120,80), self.block, self.empty_tile)
        self.poi_menu = Map("POI Menu", self, self.size, (4,1), self.block, self.empty_tile)
        self.menus = [Map("Menu", self, self.size, (2,14), self.block, self.empty_tile)]
        self.pal_menu = Menu((128, 40), (0,21))
        self.pal_menu.add_buttons(2, ["New", "Pal-1"])
        self.pal_menu.set_bg_color(SUBBUTTON_COLOR)
        self.menu = self.menus[0]
        self.menu.xy[1] += 20
        self.men_list = []
        self.sprite_map = self.setup_spritemap()
        self.sprite_map.xy = [250,0]
        self.clip = pg.Rect(0,0, self.size[0],self.size[1])
        self.c_pos = self.clip.topleft
        self.show_full_map = False
        self.show_poi = False
        self.full_map = None
        self.current_tile = None
        self.current_menu = None
        self.ground_state = None
        self.right_m_pos = None
        self.right_m_button = False
        self.fill = False
        self.m_pos = None
        self.m_select_rect = pg.Rect(1,1,1,1)
        self.menu_button = Button((120, 20), (129,1), "Menu")
        self.pal_button = Button((128,20), (0,0), "Palette")
        self.drop_menu = Menu((120, 160), (129, 21))
        self.drop_menu.add_buttons(5, ["Save", "Load", "Sprites", "See Map", "Info"])
        self.drop_menu.set_bg_color(SUBBUTTON_COLOR)
        self.load_menu = self.setup_loadmenu()
        self.floating_text = FloatingText("no text", self.size)
        self.info_panel = Panel((self.size[0] - self.size[0]/3, self.size[1] - self.size[1]/3), (self.size[0]/6, self.size[1]/6))
        self.info_panel.setup_text([self.name, "Made by Aurelio Aguirre", "", "Use WASD to move around.", "Use E to toggle the Foreground.", "Use R to toggle the Middleground.", "Use Q to toggle the Point of Interest map."])
        self.setup()
        self.setup_poi()
        self.selected_map = self.map_bg
        self.alternative = ALTERNATIVE_MODE
        self.enable_alternative_mode()

    def update(self, dt):
        self.dt = dt
        self.map_bg.update(dt)
        if not self.alternative:
            self.map_fg.update(dt)
            self.map_mg.update(dt)
            self.sprite_map.update(dt)
            self.menu.update(dt)
        self.poi_map.update(dt)
        self.poi_menu.update(dt)
        self.floating_text.update(dt)
        if self.drop_menu.buttons[0].active:
            self.savemap()
            self.drop_menu.buttons[0].active = False
        if self.drop_menu.buttons[2].active:
            self.selected_map = self.sprite_map
        else:
            self.selected_map = self.map_bg
        if not self.alternative:
            if self.pal_button.active:
                if self.pal_menu.clickinfo != None:
                    if self.pal_menu.clickinfo == "New":
                        self.new_palette()
                    else:
                        self.switch_palette(text=self.pal_menu.clickinfo)
                    self.pal_menu.clickinfo = None
        if self.map_bg.clipped:
            self.map_fg.map.set_clip()
            self.map_mg.map.set_clip()
            self.poi_map.map.set_clip()
            self.map_bg.clipped = False
        if self.c_pos != self.clip.topleft:
            self.c_pos = (self.c_pos[0] - self.map_bg.xy[0], self.c_pos[1] - self.map_bg.xy[1])
            self.clip.topleft = self.c_pos
        self.menu_button.update(self.dt)
        self.mouse_select()

    def draw(self):
        self.screen.fill(BLACK)

        # MAPs
        # Background
        self.map_bg.draw(self.screen, self.clip)
        if not self.alternative:
            # Middleground
            if self.ground_state == "MG":
                self.map_mg.xy = self.map_bg.xy
                self.map_mg.draw(self.screen, self.clip)

            # Foreground
            if self.ground_state == "FG":
                self.map_fg.xy = self.map_bg.xy
                self.map_fg.draw(self.screen, self.clip)

        # POI Map
        if self.show_poi:
            self.poi_map.xy = self.map_bg.xy
            self.poi_map.draw(self.screen, self.clip)

        # GUI
        if not self.alternative:
            self.menu.draw(self.screen)
        if self.show_poi:
            self.poi_menu.draw(self.screen)
        self.menu_button.draw(self.screen)
        if not self.alternative:
            self.pal_button.draw(self.screen)
        if self.menu_button.active:
            self.drop_menu.draw(self.screen)
        if self.pal_button.active:
            self.pal_menu.draw(self.screen)
        if self.drop_menu.buttons[1].active:
            self.load_menu.draw(self.screen)
        if self.drop_menu.buttons[2].active:
            self.sprite_map.draw(self.screen)
        if self.right_m_button:
            screen_rect = self.m_select_rect.copy()
            screen_rect.x += self.map_bg.xy[0]
            screen_rect.y += self.map_bg.xy[1]
            pg.draw.rect(self.screen, WHITE, screen_rect, 1)
        if self.show_full_map:
            if self.full_map:
                self.screen.blit(self.full_map, (0,0))
        self.info_panel.draw(self.screen)
        self.floating_text.draw(self.screen)

########################## Setup methods #######################################

    def enable_alternative_mode(self):
        if self.alternative:
            bgimage = pg.image.load("./img/CI Main 128.png").convert_alpha()
            self.map_bg = Map("Static Image", self, self.size, (120,80), 128, bgimage)
            self.map_bg.setup(BG_COLOR, alt=True)
            self.alternative = True

    def setup_loadmenu(self):
        folder = Path("./save")
        filelist = [f.basename() for f in folder.files("*.sav")]
        amount = len(filelist)
        menu = Menu((240, amount*21), (250, 21))
        menu.add_buttons(amount, filelist)
        menu.set_bg_color(WHITE)
        return menu

    def setup(self):
        self.map_bg.setup(BG_COLOR)
        self.map_fg.setup(FG_COLOR, 200)
        self.map_mg.setup(MG_COLOR, 200)
        self.menu.setup(PAL_COLOR)
        self.poi_map.setup(POI_MAP, alpha=150)
        self.poi_menu.setup(POI_MENU)

    def setup_poi(self):
        wall = pg.image.load("./tiles/Wall32.png").convert_alpha()
        door = pg.image.load("./tiles/Door32.png").convert_alpha()
        poi = pg.image.load("./tiles/POI32.png").convert_alpha()
        delete = pg.image.load("./tiles/Eliminate32.png").convert_alpha()
        self.poi_dict = OrderedDict((("Poi Wall", wall), ("Poi Door", door), ("Poi Symbol", poi), ("Delete", delete)))
        p = [i for i in self.poi_dict.keys()]
        for num, tile in enumerate(self.poi_menu.group):
            tile.image = self.poi_dict[p[num]]
            tile.rect = tile.image.get_rect()
            tile.rect.topleft = ((self.block*num), 1)
            tile.filename = p[num]
            tile.dirty = 1
        xplace = self.size[0] - self.block*4
        self.poi_menu.xy = [xplace, 1]

    def setup_spritemap(self):
        sheet = SpriteSheet("img/magecity_64p.png", 64, (0,0), (8,44))
        self.men_list = sum(sheet.image_list, [])
        length = len(self.men_list)
        size = (10, int(length/10))
        menu = Map("Palette", self, self.size, size, self.block, self.empty_tile)
        menu.setup(WHITE)
        for i, tile in enumerate(menu.group):
            tile.filename = "{}".format(i)
            tile.image = self.men_list[i]
            if i+1 >= length:
                break
        return menu

#################### Key and Mouse Methods #####################################

    def key_down(self, key):
        if key == K_ESCAPE:
            print("Quitting...")
            self.game_on == False
            self.end_game()

        if key == K_e:
            if self.ground_state == None or self.ground_state == "MG":
                self.ground_state = "FG"
            else:
                self.ground_state = None

        if key == K_r:
            if self.ground_state == None or self.ground_state == "FG":
                self.ground_state = "MG"
            else:
                self.ground_state = None

        if key == K_q:
            self.show_poi = not self.show_poi
            self.current_tile = None

        if key in (K_w, K_UP):
            self.selected_map.move["up"] = True
        if key in (K_a, K_LEFT):
            self.selected_map.move["left"] = True
        if key in (K_s, K_DOWN):
            self.selected_map.move["down"] = True
        if key in (K_d, K_RIGHT):
            self.selected_map.move["right"] = True

    def key_up(self, key):
        if key in (K_w, K_UP):
            self.selected_map.move["up"] = False
        if key in (K_a, K_LEFT):
            self.selected_map.move["left"] = False
        if key in (K_s, K_DOWN):
            self.selected_map.move["down"] = False
        if key in (K_d, K_RIGHT):
            self.selected_map.move["right"] = False

    def mouse_down(self, button, pos):
        not_menu = True
        if button == 1:
            # First we check for the unique states, Info Panel and Full Map.
            if not self.info_panel.display:
                if not self.show_full_map:
                    # Now we check for menu buttons being clicked, and switch our
                    # not_menu switch if they are. From here the rest is handled by update.
                    if self.menu_button.click(pos):
                        not_menu = False
                    elif self.pal_button.click(pos):
                        not_menu = False
                    if self.menu_button.active:
                        if self.drop_menu.click(pos):
                            not_menu = False
                    if self.pal_button.active:
                        if self.pal_menu.click(pos):
                            not_menu = False
                    # Assuming we are in our main menu we check for the the buttons being clicked.
                    # This part is allowed to happen WHILE maps are also being manipulated. (not_menu is not switched)
                    if self.drop_menu.buttons[1].active:
                        if self.load_menu.click(pos):
                            self.loadmap(self.load_menu.clickinfo)
                    elif self.drop_menu.buttons[3].active:
                        self.show_map()
                        self.drop_menu.buttons[3].active = False
                    elif self.drop_menu.buttons[4].active:
                        self.info_panel.display_panel()
                        self.drop_menu.buttons[4].active = False
                    # Here we look for our Maps. Basically we are moving a tile from one map to another.
                    # We just need to pick the right one, and they should all overwrite each other.
                    # In other words, only one map is active at a time.
                    if not_menu:
                        if self.drop_menu.buttons[2].active: # Tiles are showing.
                            self.find_tile(pos, self.sprite_map, self.menu)
                        elif self.show_poi: # POI Map is up.
                            self.find_tile(pos, self.poi_menu, self.poi_map)
                        elif self.ground_state == "FG": # we are on the Foreground map.
                            self.find_tile(pos, self.menu, self.map_fg)
                        elif self.ground_state == "MG": # We are on the middleground map.
                            self.find_tile(pos, self.menu, self.map_mg)
                        else: # We default to the Background map.
                            self.find_tile(pos, self.menu, self.map_bg)
                else:
                    # While the full map is up, any left mouse click will deactivate it.
                    self.show_full_map = False
            else:
                self.info_panel.click(pos)

        if button == 3:
            if not self.show_full_map:
                self.right_m_button = True
                self.right_m_pos = pos
            else:
                self.take_image(self.full_map)

    def mouse_up(self, button, pos):
        if button == 3:
            self.right_m_button = False
            self.right_m_pos = pos
            new_rect = self._invert_rect(self.m_select_rect)

            if self.show_poi:
                self.group_select(new_rect, self.poi_map.group)
            elif self.ground_state == "FG":
                self.group_select(new_rect, self.map_fg.group)
            elif self.ground_state == "MG":
                self.group_select(new_rect, self.map_mg.group)
            else:
                self.group_select(new_rect, self.map_bg.group)

    def mouse_motion(self, button, pos, rel):
        self.m_pos = pos

    def mouse_select(self):
        if self.right_m_button:
            old_pos = (self.right_m_pos[0] - self.map_bg.xy[0], self.right_m_pos[1] - self.map_bg.xy[1])
            new_pos = (self.m_pos[0] - self.map_bg.xy[0], self.m_pos[1] - self.map_bg.xy[1])
            self.m_select_rect = pg.Rect(1,1,1,1)
            xoff, yoff = new_pos[0] - old_pos[0], new_pos[1] - old_pos[1]
            self.m_select_rect.inflate_ip(xoff, yoff)
            self.m_select_rect.topleft = old_pos

    def _invert_rect(self, rect):
            new_rect = pg.Rect(1,1,1,1)
            new_rect.size = rect.size
            if rect.width < 0:
                new_rect.width *= -1
            if rect.height < 0:
                new_rect.height *= -1
            if rect.left > rect.right:
                new_rect.left = rect.right
            else:
                new_rect.left = rect.left
            if rect.top > rect.bottom:
                new_rect.top = rect.bottom
            else:
                new_rect.top = rect.top
            return new_rect

###################### Button Activated Methods ################################

    def group_select(self, rect, group):
        for sprite in group:
            if sprite.rect.colliderect(rect):
                self.change_tile(sprite)

    def find_tile(self, pos, menu, bg_map):
        found = False
        for tile in menu.group:
            map_pos = (pos[0] - menu.xy[0], pos[1] - menu.xy[1])
            if tile.rect.collidepoint(map_pos):
                found = True
                menu.fill = True
                menu.select_rect(tile.rect)
                menu.draw_border = True
                self.current_tile = tile
                self.current_menu = menu.name
            if found:
                break
        if not found:
            for tile in bg_map.group:
                map_pos = (pos[0] - bg_map.xy[0], pos[1] - bg_map.xy[1])
                if tile.rect.collidepoint(map_pos):
                    self.change_tile(tile)
                    bg_map.clear_map()
        return found

    def change_tile(self, tile):
        if self.current_tile != None:
            if self.current_tile.filename != "Delete":
                tile.filename = self.current_tile.filename
                tile.image = self.current_tile.image
                tile.dirty = 1
            else:
                print("Removing Tile!")
                tile.filename = "Empty_tile"
                tile.image = self.empty_tile
                tile.dirty = 1

    def new_palette(self):
        self.menus.append(Map("Menu", self, self.size, (2,14), self.block, self.empty_tile))
        self.menus[-1].setup(WHITE)

        size = self.pal_menu.size
        self.pal_menu.change_size((size[0], size[1]+20))
        num = len(self.menus)
        self.pal_menu.add_buttons(1, ["Pal-{}".format(num)])
        self.switch_palette(ind=-1)

    def switch_palette(self, ind=None, text=None):
        if ind:
            self.menu = self.menus[ind]
        elif text:
            self.menu = self.menus[int(text[-1])-1]

# <-------This Needs adjustment, needs to differentiate between Layers-------->
    def show_map(self):
        full_map = pg.Surface((40*64, 40*64))
        for tile in self.map_bg.group:
            full_map.blit(tile.image, tile.rect.topleft)
        for tile in self.map_mg.group:
            if tile.filename != "Empty_tile":
                full_map.blit(tile.image, tile.rect.topleft)
        for tile in self.map_fg.group:
            if tile.filename != "Empty_tile":
                full_map.blit(tile.image, tile.rect.topleft)
        self.full_map = pg.transform.smoothscale(full_map, self.size)
        self.show_full_map = True

    def take_image(self, surf):
        folder = Path("./image")
        amount = len(folder.files("*.jpg"))
        filename = "{}{}{}{}".format(folder, "/map", amount, ".jpg")
        pg.image.save(surf, filename)

    def savemap(self):
        if not self.alternative:
            saving = SaveMap()
            saving.add_map(self.map_bg)
            saving.add_map(self.map_mg)
            saving.add_map(self.map_fg)
            saving.add_map(self.poi_map)
            saving.write_to_file()
        else:
            saving = SaveMap()
            saving.add_map(self.poi_map)
            saving.write_to_file()

    def loadmap(self, filename):
        load = LoadMap(filename)
        maplist = []
        for m in load.maps.values():
            a_map = Map(m["info"]["name"], self, m["info"]["size"], m["info"]["grid"], m["info"]["block"], self.empty_tile)
            if m["info"]["name"] == "Foreground" or m["info"]["name"] == "Middleground":
                a_map.setup(m["info"]["color"], 200)
            elif m["info"]["name"] == "POI Map":
                a_map.setup(m["info"]["color"], 150)
            else:
                a_map.setup(m["info"]["color"])
            for t in a_map.group:
                for i in m["tiles"]:
                    if list(t.rect.topleft) in m["tiles"][i]:
                        t.filename = i
                        if i[0] == "P":
                            t.image = self.poi_dict[i]
                            t.dirty = 1
                        else:
                            t.image = self.men_list[int(i)]
                            t.dirty = 1
            maplist.append(a_map)
        for j in maplist:
            if j.name == "Background":
                self.map_bg = j
            if j.name == "Middleground":
                self.map_mg = j
            if j.name == "Foreground":
                self.map_fg = j
            if j.name == "POI Map":
                self.poi_map = j
        print("Loading from file...")
class Interface():
    """
    """
    def __init__(self, level, bg_color, pygame):
        """
        Initialize the game's interface
        """
        # Setup variables
        self._level = level
        self._pygame = pygame
        self._bg_color = bg_color

        #Start in player 1 move mode
        self.mode = Modes.Move

        # Load the level information
        # This method also initialize the screen size
        #   according to the map size
        self._loadLevel()

        #Load all the sounds
        self.sound_controller = SoundsController()

        # The status bar
        self.status_bar = pygame.Rect(0, self._map_resolution[1],
                                     self._screen_resolution[0],
                                     STATUS_BAR_HEIGHT)

        # The power bar
        self.power_bar = pygame.Rect(COLUMN_WIDTH + (COLUMN_WIDTH - 100)/2 , self._map_resolution[1] + 80,
                                     100,
                                     POWER_BAR_HEIGHT)

        self.power_outline = self.power_bar.copy()
        self.power_outline.w -= 1
        self.power_outline.h -= 1

        #Set friendly fire
        self.friendly_fire = True

        # Current power
        self.current_power = 20
        self.current_power_increasing = True

        #Initialize tanks
        self.p1_tank = Tank([70, 560], 1)
        self.p2_tank = Tank([1110, 560], 2)

        #Initilize turn number
        self.turn = 1
        #The first one to play is random (not always player 1)
        self.players_turn = randrange(2)+1

        #Set the number of turns
        self.num_teams = 2

        #Load the map information
        self._map = Map(level, bg_color)

        #Initialize the screen
        self._windowSurfaceObj = pygame.display.set_mode(self._screen_resolution)
        self._windowSurfaceObj.fill(bg_color)

        self._map.paintMountain(self._windowSurfaceObj)
        self.draw_bar()
        self.draw_tank(self.p1_tank)
        self.draw_tank(self.p2_tank)

    def _loadLevel(self):
        """
        Load the level information
        """
        #gets the filename
        filename = "maps/" + self._level + ".lvl"
        
        map_file = open(filename, 'r')
        
        # Move up to the line with the size of the map
        line = map_file.readline()
        while line.find("Size: ") < 0:
            line = map_file.readline()
            if line == "":
                raise Exception ("Expected Map Size.")

        # Get the size of the map
        line = line.lstrip("Size: ")
        line = line.strip()
        size = line.split('x')
        map_width, map_height = size
        map_width = int(map_width)
        map_height = int(map_height)

        # Move up to the line with the tank area
        line = map_file.readline()
        while line.find("TankArea: ") < 0:
            line = map_file.readline()
            if line == "":
                raise Exception ("Expected Tank Area.")

        # Get the size of the map
        line = line.lstrip("TankArea: ")
        self._tank_area = line.strip()

        self._map_resolution = (map_width, map_height)
        self._screen_resolution = (map_width, map_height+STATUS_BAR_HEIGHT)

    def update(self):
        """
        Update the interface. This method is called on every frame.
        """
        #Update the display
        self._pygame.display.update()

        # draw the bar
        self.draw_bar()

        #Check if we are supposed to draw the shot
        if self.mode == Modes.Draw_Shot:

            if self.shot_path_index < len(self.shot_path):
                
                #Erase old bullet
                if self.shot_path_index > 0:
                    pos = self.shot_path[self.shot_path_index-1]
                    x = pos[0]
                    y = pos[1]
                    self.erase_shot(x,y)

                #Draw current shot position
                pos = self.shot_path[self.shot_path_index]
                x = pos[0]
                y = pos[1]

                #Check for bounds
                if x >= 0 and y >= 0 and x < self._map_resolution[0] and   y < self._map_resolution[1]:

                    #Get the circle inside the rectangle
                    circle_rect = self.draw_shot(x,y)

                    #Check if the shot hit an obstacle
                    #  For example: if it hit the mountain or a tank
                    if self.shot_path_index > 2 and circle_rect.colliderect(self.p1_tank.get_rect()):
                        self.erase_shot(x,y)
                        self.finish_shot_firing(False, did_hit_team=1)
                    elif self.shot_path_index > 2 and circle_rect.colliderect(self.p2_tank.get_rect()):
                        self.erase_shot(x,y)
                        self.finish_shot_firing(False, did_hit_team=2)
                    elif self._map.didShotHitMountain(circle_rect, self.current_power, self._windowSurfaceObj):
                        self.erase_shot(x,y)
                        self.finish_shot_firing(True, pos=(x,y))



                #Increase the index
                self.shot_path_index += 1

            #If this is the last time, erase the shot
            elif self.shot_path_index == len(self.shot_path) and self.shot_path_index > 0:
                pos = self.shot_path[self.shot_path_index-1]
                x = pos[0]
                y = pos[1]
                self.erase_shot(x,y)

                self.finish_shot_firing(False)

            #Redraw both tanks (just in case the shot hit the tank)
            self.erase_tank(self.p1_tank)
            self.draw_tank(self.p1_tank)
            self.erase_tank(self.p2_tank)
            self.draw_tank(self.p2_tank)

            #If game over
            if self.mode == Modes.GameOver:
                #Call animation to destroy the tank
                self.explode_tank(self.enemy_team)


    def draw_bar(self):
        """
        Draws the info bar on the bottom of the screen. 
        """        
        #draw the background of the bar
        pygame.draw.rect(self._windowSurfaceObj, STATUS_BAR_COLOR, self.status_bar)
        
        #draw the outline of the bar
        outlineRect = self.status_bar.copy()
        outlineRect.w -= 1
        outlineRect.h -= 1
        pygame.draw.rect(self._windowSurfaceObj, OUTLINE_COLOR, outlineRect, 2)

        #draw lines between players information
        pygame.draw.line(
            self._windowSurfaceObj,
            OUTLINE_COLOR,
            (COLUMN_WIDTH, self._map_resolution[1]),
            (COLUMN_WIDTH, self._map_resolution[1]+STATUS_BAR_HEIGHT))

        pygame.draw.line(
            self._windowSurfaceObj,
            OUTLINE_COLOR,
            (2*COLUMN_WIDTH, self._map_resolution[1]),
            (2*COLUMN_WIDTH, self._map_resolution[1]+STATUS_BAR_HEIGHT))

        #draw player 1's information
        y = 0
        y += 5 + self.draw_info_text('Player 1', MEDIUM_FONT, MEDIUM_FONT_SIZE, y, 0)
        y += self.draw_info_text('HP:        {:10.1f}%'.format(self.p1_tank.get_hp_as_percentage()), FONT, FONT_SIZE, y, 0)
        y += self.draw_info_text('Angle:    {:10.1f}°'.format(self.p1_tank.get_angle()), FONT, FONT_SIZE, y, 0)
        self.draw_info_text('Power:  {:10.1f}%'.format(self.p1_tank.get_power_as_percentage()), FONT, FONT_SIZE, y, 0)

        #draw game information
        y = 0
        if self.mode == Modes.GameOver:
            y += 5 + self.draw_info_text('Game Over!', BIG_FONT, BIG_FONT_SIZE, y, 1)
            y += self.draw_info_text('Player {} won!'.format(self.players_turn), MEDIUM_FONT, MEDIUM_FONT_SIZE, y, 1)
        else:
            y += 5 + self.draw_info_text('Day {}'.format(self.turn), BIG_FONT, BIG_FONT_SIZE, y, 1)
            y += self.draw_info_text('Player {}\'s turn'.format(self.players_turn), FONT, FONT_SIZE, y, 1)


        #If we are firing, draw the power bar
        if self.mode == Modes.Firing:
            
            self.calculate_power()
            self.power_bar.w = self.current_power
            
            pygame.draw.rect(self._windowSurfaceObj, (POWER_BAR_COLOR[0]+self.current_power,POWER_BAR_COLOR[1]-self.current_power,POWER_BAR_COLOR[2]) , self.power_bar)
            pygame.draw.rect(self._windowSurfaceObj, OUTLINE_COLOR, self.power_outline, 2)


        #draw player 2's information
        y = 0
        y += 5 + self.draw_info_text('Player 2', MEDIUM_FONT, MEDIUM_FONT_SIZE, y, 2)
        y += self.draw_info_text('HP:        {:10.1f}%'.format(self.p2_tank.get_hp_as_percentage()), FONT, FONT_SIZE, y, 2)
        y += self.draw_info_text('Angle:    {:10.1f}°'.format(abs(self.p2_tank.get_angle())), FONT, FONT_SIZE, y, 2)
        self.draw_info_text('Power:  {:10.1f}%'.format(self.p2_tank.get_power_as_percentage()), FONT, FONT_SIZE, y, 2)



    def draw_info_text(self, text, font, font_size, y, column):
        """
        Draws given text with given information.
        """
        line_text = font.render(text, True, FONT_COLOR)
        self._windowSurfaceObj.blit(
            line_text,
            (column*COLUMN_WIDTH + PAD, self._map_resolution[1] + y + PAD))
        return font_size + PAD

    def draw_tank(self, tank):
        """
        Draws given tank
        """
        pos = tank.get_position()
        barrel_pos = tank.get_barrel_position()

        #Rotate the barrel image
        barrel_img = pygame.transform.rotate(tank.image_barrel, tank.get_angle())

        #Calculate the barrel's fixed position - because of the rotation
        y = math.sin(math.radians(abs(tank.get_angle())))*44

        #Defines the x according to the tank and update the initial shot position
        if tank.team == 1:
            x = 0
            tank.set_shot_start_position(barrel_pos[0] + barrel_img.get_width(), barrel_pos[1]-y)
        else: 
            x = 56 - barrel_img.get_width()
            tank.set_shot_start_position(barrel_pos[0] + x, barrel_pos[1]-y)

        #Draw the tank and the barrel
        self._windowSurfaceObj.blit(tank.image, (pos[0],pos[1]))
        self._windowSurfaceObj.blit(barrel_img, (barrel_pos[0] + x,barrel_pos[1]-y))
        pygame.display.flip()

    def draw_shot(self, x,y):
        """
        Draw a shot on given positon
        """
        return pygame.draw.circle(self._windowSurfaceObj, SHOT_COLOR, (x,y), SHOT_RADIUS)

    def erase_shot(self, x,y):
        """
        Erase a shot on given position
        """
        pygame.draw.circle(self._windowSurfaceObj, self._bg_color, (x,y), SHOT_RADIUS)


    def calculate_power(self):
        """
        Calculates the new power.

        It should increase every frame until it reaches 100.
        After, it decreases until 20 - and keeps going like this until
        the user hits space again
        """
        if self.current_power > 80:
            rate = 3.5
        elif self.current_power > 60:
            rate = 2.3
        elif self.current_power > 40:
            rate = 1.8
        elif self.current_power > 20:
            rate = 1.1
        else:
            rate = 0.5

        if self.current_power_increasing:
            self.current_power += rate

            if self.current_power >= 100:
                self.current_power = 100
                self.current_power_increasing = False

        else:
            self.current_power -= rate

            if self.current_power <= 0:
                self.current_power = 0
                self.current_power_increasing = True

        self.cur_team.update_power(self.current_power)

    def erase_tank(self, tank):
        """
        Erases tank
        """
        pygame.draw.rect(self._windowSurfaceObj, self._bg_color, (tank.position[0],tank.position[1]-45,103,85))
        #pygame.draw.rect(self._windowSurfaceObj, self._bg_color, tank.get_rect())
    
    def explode_tank(self, tank):
        """
        Animation to destroy tank
        """
        self.erase_tank(tank)

    @property
    def cur_team(self):
        """
        Returns the string name of the tank who's turn it currently is. 
        """
        if self.players_turn == 1:
            return self.p1_tank
        else:
            return self.p2_tank
       
    @property
    def enemy_team(self):
        """
        Returns the string name of the tank who's turn it currently is. 
        """
        if self.players_turn == 1:
            return self.p2_tank
        else:
            return self.p1_tank


    def move_tank(self, value):
        """
        Move the tank according to if the left or right arrow was pressed

        """
        if self.mode != Modes.Move:
            return
        
        #Get the current tank
        current_tank = self.cur_team

        #Erase it
        self.erase_tank(current_tank)

        #Move it accordingly
        if value == "left":
            current_tank.move_tank([-3,0])

        else:
            current_tank.move_tank([3,0])
        
        #Redraw it
        self.draw_tank(current_tank)

    def change_angle(self, value):
        """
        Change the angle of the tank barrel according to if the up 
        or down arrow key was pressed
        """
        if self.mode != Modes.Move:
            return

        #Get the current tank
        current_tank = self.cur_team

        #Erase it
        self.erase_tank(current_tank)

        #Change the angle accordingly
        if value == "up":
            current_tank.change_barrel_angle(1)

        else:
            current_tank.change_barrel_angle(-1)
            
        #Redraw the tank
        self.draw_tank(current_tank)


    def select_power(self):
        """
        After hitting space to fire, we need to use a timer or somthing
        between events to calculate how hard the shot should be.
        This will eventually read from the arduino potentiometer value and pass that 
        to the shot class. 
        So maybe for now we will hard code it to be (0-100)

        """
        if self.mode != Modes.Move:
            return

        self.change_mode(Modes.Firing)
        
        #self.draw_power_bar()
        #self.


    def release_power(self):
        if self.mode != Modes.Firing:
            return

        self.fire_shot()
        self.current_power = 20
        self.current_power_increasing = True


    def fire_shot(self):
        """
        Creates a shot according toa power value given
        Then creates the effects that follow a shot being fired
        """
        
        self.change_mode(Modes.Draw_Shot)

        enemy_tank = self.enemy_team
        current_tank = self.cur_team

        self.current_shot = Shot(self.current_power, current_tank.get_angle(), current_tank, enemy_tank, self._map_resolution[1], self._map_resolution[0])
        self.shot_path = self.current_shot.get_path()
        self.shot_path_index = 0 

        #play shot sound
        self.sound_controller.play("TankFire");
        #self.sound_controller.play("BombDrop");
         

    def finish_shot_firing(self, didHitMountain, did_hit_team=0, pos=None):
        """
        This method is called after we finish drawing the shot and need to finish the player's turn
        """

        enemy_tank = self.enemy_team
        current_tank = self.cur_team


        if self.players_turn == 1:
            enemy_team_number = 2
        else:
            enemy_team_number = 1

        if pos:
            self.explosion(pos[0], pos[1], 15)
        elif did_hit_team != 0:
            if did_hit_team == 1:
                pos = [(self.p1_tank.get_rect().x + (self.p1_tank.get_rect().w/2)),(self.p1_tank.get_rect().y + (self.p1_tank.get_rect().h/2))]
            elif did_hit_team == 2:
                pos = [(self.p2_tank.get_rect().x + (self.p2_tank.get_rect().w/2)),(self.p2_tank.get_rect().y + (self.p2_tank.get_rect().h/2))]

            self.explosion(pos[0], pos[1], 25)
            

        #If we didn't hit the mountain and did hit the other tank, decrease his hp
        if not didHitMountain and did_hit_team == enemy_team_number:
            enemy_tank.take_damage(self.current_power*HIT_PERCENTAGE)

            #If the enemy was killed, game over!
            if not enemy_tank.active:
                self.change_mode(Modes.GameOver)
                self.erase_tank(enemy_tank)
                return

        #If we didn't hit the mountain, friendly fire is on and we did hit ourselves
        if not didHitMountain and self.friendly_fire and did_hit_team == self.players_turn:
            current_tank.take_damage(self.current_power*HIT_PERCENTAGE)

            #If the played killed himself, game over!
            if not current_tank.active:
                if self.players_turn == 1:
                    self.players_turn = 2
                else:
                    self.players_turn = 1

                self.change_mode(Modes.GameOver)
                self.erase_tank(current_tank)
                return

        self.change_mode(Modes.Move)
        self.next_turn()


    def next_turn(self):
        self.turn +=1

        #Updates the the player's turn variable
        # Which is, whoever turn is it
        if self.players_turn == 1:
            self.players_turn = 2
        else:
            self.players_turn = 1


    def change_mode(self, mode):
        if self.mode == mode:
            return

        self.mode = mode

    def explosion(self, x, y, radius):
        """
        Creates an explosion animation centered at x,y with a radius
            Note: the animation is poorly done, but it's better than nothing.
                   and there's no time to improve it, unfortunatelly
        """
        self.sound_controller.play("Explosion")

        for i in range(1,10):
            pygame.draw.circle(self._windowSurfaceObj, ( round(100+(i*10)),round(100-(i*10)),0) , (round(x),round(y)), round((radius/10)*i))
            self._pygame.display.update()

        for i in range(10,1):
            pygame.draw.circle(self._windowSurfaceObj, ( round(100+(i*10)),round(100-(i*10)),0) , (round(x),round(y)), round((radius/10)*i))
            self._pygame.display.update()
        
        pygame.draw.circle(self._windowSurfaceObj, self._bg_color, (round(x),round(y)), round(radius))
Example #48
0
 def enable_alternative_mode(self):
     if self.alternative:
         bgimage = pg.image.load("./img/CI Main 128.png").convert_alpha()
         self.map_bg = Map("Static Image", self, self.size, (120,80), 128, bgimage)
         self.map_bg.setup(BG_COLOR, alt=True)
         self.alternative = True
    def __init__(self, level, bg_color, pygame):
        """
        Initialize the game's interface
        """
        # Setup variables
        self._level = level
        self._pygame = pygame
        self._bg_color = bg_color

        #Start in player 1 move mode
        self.mode = Modes.Move

        # Load the level information
        # This method also initialize the screen size
        #   according to the map size
        self._loadLevel()

        #Load all the sounds
        self.sound_controller = SoundsController()

        # The status bar
        self.status_bar = pygame.Rect(0, self._map_resolution[1],
                                     self._screen_resolution[0],
                                     STATUS_BAR_HEIGHT)

        # The power bar
        self.power_bar = pygame.Rect(COLUMN_WIDTH + (COLUMN_WIDTH - 100)/2 , self._map_resolution[1] + 80,
                                     100,
                                     POWER_BAR_HEIGHT)

        self.power_outline = self.power_bar.copy()
        self.power_outline.w -= 1
        self.power_outline.h -= 1

        #Set friendly fire
        self.friendly_fire = True

        # Current power
        self.current_power = 20
        self.current_power_increasing = True

        #Initialize tanks
        self.p1_tank = Tank([70, 560], 1)
        self.p2_tank = Tank([1110, 560], 2)

        #Initilize turn number
        self.turn = 1
        #The first one to play is random (not always player 1)
        self.players_turn = randrange(2)+1

        #Set the number of turns
        self.num_teams = 2

        #Load the map information
        self._map = Map(level, bg_color)

        #Initialize the screen
        self._windowSurfaceObj = pygame.display.set_mode(self._screen_resolution)
        self._windowSurfaceObj.fill(bg_color)

        self._map.paintMountain(self._windowSurfaceObj)
        self.draw_bar()
        self.draw_tank(self.p1_tank)
        self.draw_tank(self.p2_tank)