def test_a_star_blocked_by_environment(self): m = Map(10, 10) m.generate_from_ascii("models/maps/10by10divided.txt") start = m.tile_matrix[1][1] end = m.tile_matrix[1][7] path = m.a_star(start, end, CONST.jets, limit=20) assert (len(path) == 0)
def main(): """Initializes pygame and music and starts the gameloop""" pygame.init() map = Map(32, 18) clock = pygame.time.Clock() start_music("sfx/onestop.mid") map.generate_from_ascii("models/maps/TheBlock.txt") map.quick_board_32_18() view = View(map) ev_handler = EventHandler() controller = Controller(view, map) ev_handler.register_listener(controller) main_menu(clock, view) tutorial_screen(clock, view) map.switch_turns() while 1: clock.tick(30) view.update_view() for event in pygame.event.get(): ev_handler.post(event) if map.sharks_routed() or map.jets_routed(): break end_game(clock, view) game_over(clock, view)
def test_simple_move(self): m = Map(10, 10) m.generate_from_ascii("models/maps/10by10.txt") g = GreaserUnit(4, 4, m, CONST.jets) assert (g.move(5, 4)) assert (g.x == 5 and g.y == 4) assert (m.unit_at(5, 4) is g)
def __init__(self, level): super(GameManager, self).__init__() self.observers = [] # keep observers #set game options self.level = level self.map = Map('resources/maps/game_map.tmx') EnemyBrain() EnemyBrain.instance.set_map(self.map) self.count_of_available_player_tanks = 2 self.standart_tanks_count = 3 self.fast_tanks_count = 3 self.heavy_tanks_count = 3 self.count_of_max_enemy_tanks_on_map = 2 self.spawn_index = 0 self.tanks = [] self.bullets = [] self.bonuses = [] self.add_base() self.timeout = 500 self.enemy_way_nodes = []
def main(): cprint( ' ███▄ ▄███▓ ▒█████ ███▄ █ ██████ ▄▄▄█████▓▓█████ ██▀███ ██▓███ ██▓ ▄▄▄ ███▄ █ ▓█████▄▄▄█████▓ ', 'green') cprint( ' ▓██▒▀█▀ ██▒▒██▒ ██▒ ██ ▀█ █ ▒██ ▒ ▓ ██▒ ▓▒▓█ ▀ ▓██ ▒ ██▒ ▓██░ ██▒▓██▒ ▒████▄ ██ ▀█ █ ▓█ ▀▓ ██▒ ▓▒', 'green') cprint( ' ▓██ ▓██░▒██░ ██▒▓██ ▀█ ██▒░ ▓██▄ ▒ ▓██░ ▒░▒███ ▓██ ░▄█ ▒ ▓██░ ██▓▒▒██░ ▒██ ▀█▄ ▓██ ▀█ ██▒▒███ ▒ ▓██░ ▒░', 'green') cprint( ' ▒██ ▒██ ▒██ ██░▓██▒ ▐▌██▒ ▒ ██▒░ ▓██▓ ░ ▒▓█ ▄ ▒██▀▀█▄ ▒██▄█▓▒ ▒▒██░ ░██▄▄▄▄██ ▓██▒ ▐▌██▒▒▓█ ▄░ ▓██▓ ░ ', 'green') cprint( ' ▒██▒ ░██▒░ ████▓▒░▒██░ ▓██░▒██████▒▒ ▒██▒ ░ ░▒████▒░██▓ ▒██▒ ▒██▒ ░ ░░██████▒▓█ ▓██▒▒██░ ▓██░░▒████▒ ▒██▒ ░ ', 'green') cprint( ' ░ ▒░ ░ ░░ ▒░▒░▒░ ░ ▒░ ▒ ▒ ▒ ▒▓▒ ▒ ░ ▒ ░░ ░░ ▒░ ░░ ▒▓ ░▒▓░ ▒▓▒░ ░ ░░ ▒░▓ ░▒▒ ▓▒█░░ ▒░ ▒ ▒ ░░ ▒░ ░ ▒ ░░ ', 'green') cprint( ' ░ ░ ░ ░ ▒ ▒░ ░ ░░ ░ ▒░░ ░▒ ░ ░ ░ ░ ░ ░ ░▒ ░ ▒░ ░▒ ░ ░ ░ ▒ ░ ▒ ▒▒ ░░ ░░ ░ ▒░ ░ ░ ░ ░ ', 'green') cprint( ' ░ ░ ░ ░ ░ ▒ ░ ░ ░ ░ ░ ░ ░ ░ ░░ ░ ░░ ░ ░ ░ ▒ ░ ░ ░ ░ ░ ', 'green') cprint( ' ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ', 'green') print() player = Player(hp=30) map = Map() player.set_location(map.get_starting_location()) game = CommandInterpreter(player, map) game.run()
def testInvalidAttack(self): m = Map(10, 10) m.generate_from_ascii("models/maps/10by10.txt") s = SquabblerUnit(8, 4, m, CONST.jets) b = BruiserUnit(8, 5, m, CONST.jets) ##blocked by teammate assert (not s.attack(7, 4)) assert (not s.attack(8, 5))
def test_move_on_friendly_far(self): m = Map(3, 10) m.generate_from_ascii("models/maps/corridor.txt") g = GreaserUnit(0, 0, m, CONST.jets) g1 = GreaserUnit(0, 5, m, CONST.jets) assert (not g.move(0, 5)) assert (g.move(0, 4))
def testMoveAroundEnemy(self): m = Map(3, 10) m.generate_from_ascii("models/maps/corridor.txt") g = GreaserUnit(1, 2, m, CONST.jets) b1 = BruiserUnit(2, 3, m, CONST.sharks) ##blocked by teammate b2 = BruiserUnit(1, 3, m, CONST.sharks) ##blocked by teammate assert (g.move(1, 4))
def test_can_go_out_of_bounds(self): m = Map(10, 10) m.generate_from_ascii("models/maps/10by10.txt") m.can_go_through(-1, 0, CONST.jets) m.can_go_through(8, 0, CONST.jets) m.can_go_through(0, 8, CONST.jets) m.can_go_through(0, -1, CONST.jets)
def test_bruiser_special_collide(self): m = Map(10, 10) m.generate_from_ascii("models/maps/10by10.txt") s = GreaserUnit(8, 3, m, CONST.sharks) g = GreaserUnit(8, 4, m, CONST.sharks) b = BruiserUnit(8, 5, m, CONST.jets) assert (b.special_attack(8, 4)) assert (m.unit_at(8, 3) is s)
def test_squabbler_special(self): m = Map(10, 10) m.generate_from_ascii("models/maps/10by10.txt") s = SquabblerUnit(8, 3, m, CONST.jets) g = GreaserUnit(8, 4, m, CONST.sharks) gw = g.wit s.special_attack(8, 4) assert (g.demoralize)
def testAttackComplex(self): m = Map(10, 10) m.generate_from_ascii("models/maps/10by10.txt") s = SquabblerUnit(8, 3, m, CONST.jets) b = BruiserUnit(8, 5, m, CONST.sharks) ##blocked by teammate h = b.hp assert (s.attack(8, 5)) assert (b.hp < h)
def testAttackSimple(self): m = Map(10, 10) m.generate_from_ascii("models/maps/10by10.txt") g = GreaserUnit(8, 3, m, CONST.jets) b = BruiserUnit(8, 4, m, CONST.sharks) ##blocked by teammate s = b.hp assert (g.attack(8, 4)) assert (b.hp < s)
def testMoveThroughFriendly(self): m = Map(10, 10) m.generate_from_ascii("models/maps/10by10funnel.txt") g = GreaserUnit(4, 3, m, CONST.jets) b = BruiserUnit(4, 4, m, CONST.jets) ##blocked by teammate assert (g.move(4, 6)) assert (g.x == 4 and g.y == 6) assert (m.unit_at(4, 6) is g)
def test_a_star_long_blocked_by_enemy(self): m = Map(10, 10) m.generate_from_ascii("models/maps/10by10funnel.txt") start = m.tile_matrix[4][1] end = m.tile_matrix[4][7] g = GreaserUnit(4, 4, m, CONST.sharks) #shark blocking the path path = m.a_star(start, end, CONST.jets, limit=20) assert (len(path) == 0)
def test_bruiser(self): n = Map(6, 4) n.generate_from_ascii("models/maps/6by4.txt") b = BruiserUnit(0, 0, n, CONST.jets) assert (b.max_hp >= CONST.bruiser_min_hp and b.max_hp <= CONST.bruiser_max_hp) assert (b.map == n) assert (b.finesse >= CONST.bruiser_min_finesse and b.finesse <= CONST.bruiser_max_finesse) assert (b.x == 0 & b.y == 0)
def test_recreate_astar_no_path_bug(self): m = Map(32, 18) m.generate_from_ascii("models/maps/TheBlock.txt") g1 = GreaserUnit(12, 11, m, CONST.jets) g3 = GreaserUnit(15, 11, m, CONST.sharks) g4 = GreaserUnit(14, 12, m, CONST.sharks) b1 = BruiserUnit(16, 12, m, CONST.sharks) s3 = SquabblerUnit(15, 13, m, CONST.sharks) g1.valid_moves()
def test_rect_map(self): n = Map(6, 4) n.generate_from_ascii("models/maps/6by4.txt") assert (isinstance(n.tile_matrix[0][0], WallTile)) assert (isinstance(n.tile_matrix[5][0], WallTile)) assert (isinstance(n.tile_matrix[4][2], RoadTile)) assert (isinstance(n.tile_matrix[0][3], GrassTile)) assert (isinstance(n.tile_matrix[3][1], ConcreteTile)) assert (isinstance(n.tile_matrix[5][3], SceneryTile))
def test_recreate_astar_no_path_bug(self): m = Map(32,18) m.generate_from_ascii("models/maps/TheBlock.txt") g1 = GreaserUnit(12, 11, m, CONST.jets) g3 = GreaserUnit(15, 11, m, CONST.sharks) g4 = GreaserUnit(14, 12, m, CONST.sharks) b1 = BruiserUnit(16, 12, m, CONST.sharks) s3 = SquabblerUnit(15, 13, m, CONST.sharks) g1.valid_moves()
def test_a_star_zero_length(self): m = Map(10, 10) m.generate_from_ascii("models/maps/10by10.txt") start = m.tile_matrix[1][1] end = m.tile_matrix[1][1] path = m.a_star(start, end, CONST.jets) assert (len(path) == 1) assert (path[0] == start) assert (path[len(path) - 1] == end)
def test_squabbler(self): n = Map(6, 4) n.generate_from_ascii("models/maps/6by4.txt") s = SquabblerUnit(2, 2, n, CONST.jets) assert (s.max_hp >= CONST.squabbler_min_hp & s.max_hp <= CONST.squabbler_max_hp) assert (s.finesse >= CONST.squabbler_min_finesse & s.finesse <= CONST.squabbler_max_finesse) assert (s.x == 2 & s.y == 2) assert (s.team == CONST.jets)
def test_greaser_special(self): m = Map(10, 10) m.generate_from_ascii("models/maps/10by10.txt") s = SquabblerUnit(8, 3, m, CONST.jets) g = GreaserUnit(8, 4, m, CONST.sharks) b = BruiserUnit(8, 5, m, CONST.jets) bh = b.hp sh = s.hp assert (g.special_attack(8, 5)) assert (bh > b.hp and sh > s.hp)
def test_a_star_long_obstacles(self): m = Map(10, 10) m.generate_from_ascii("models/maps/10by10funnel.txt") start = m.tile_matrix[8][1] end = m.tile_matrix[1][6] path = m.a_star(start, end, CONST.jets, limit=20) for tile in path: assert (m.can_go_through(tile.x, tile.y, CONST.jets)) assert (path[0] == start) assert (path[len(path) - 1] == end)
def test_greaser(self): n = Map(6, 4) n.generate_from_ascii("models/maps/6by4.txt") g = GreaserUnit(2, 2, n, CONST.jets) assert (g.max_hp >= CONST.greaser_min_hp & g.max_hp <= CONST.greaser_max_hp) assert (g.finesse >= CONST.greaser_min_finesse & g.finesse <= CONST.greaser_max_finesse) assert (g.x == 2 & g.y == 2) assert (g.team == CONST.jets)
def main(): """Initializes pygame and music and starts the gameloop""" pygame.init() map = Map(32, 18) clock = pygame.time.Clock() start_music("sfx/onestop.mid") map.generate_from_ascii("models/maps/TheBlock.txt") map.quick_board_32_18() view = View(map) ev_handler = EventHandler() controller = Controller(view, map) ev_handler.register_listener(controller) main_menu(clock, view) tutorial_screen(clock, view) map.switch_turns() while 1: clock.tick(30) view.update_view() for event in pygame.event.get(): ev_handler.post(event) if map.sharks_routed() or map.jets_routed(): break end_game(clock,view) game_over(clock, view)
def test_a_star_short_unobstructed(self): m = Map(10, 10) m.generate_from_ascii("models/maps/10by10.txt") start = m.tile_matrix[5][5] end = m.tile_matrix[4][4] path = m.a_star(start, end, CONST.jets) assert (len(path) == 3) for tile in path: assert (m.can_go_through(tile.x, tile.y, CONST.jets)) assert (path[0] == start) assert (path[len(path) - 1] == end)
def test_a_star_long_blocked_by_friendly(self): m = Map(10, 10) m.generate_from_ascii("models/maps/10by10funnel.txt") start = m.tile_matrix[4][1] end = m.tile_matrix[4][7] g = GreaserUnit(4, 4, m, CONST.jets) path = m.a_star(start, end, CONST.jets, limit=20) for tile in path: assert (m.can_go_through(tile.x, tile.y, CONST.jets)) assert (path[0] == start) assert (path[len(path) - 1] == end)
def test_square_map(self): m = Map(10, 10) m.generate_from_ascii("models/maps/10by10.txt") assert (isinstance(m.tile_matrix[0][0], WallTile)) assert (isinstance(m.tile_matrix[0][9], GrassTile)) assert (isinstance(m.tile_matrix[4][1], ConcreteTile)) assert (isinstance(m.tile_matrix[1][9], SceneryTile)) assert (isinstance(m.tile_matrix[2][9], RoadTile)) assert (isinstance(m.tile_matrix[3][9], GrassTile)) assert (isinstance(m.tile_matrix[4][9], ConcreteTile)) assert (isinstance(m.tile_matrix[9][9], WallTile))
def GET(self, hash, factor_id): if 'map' not in web.web_session or web.web_session.map != hash: raise web.seeother('/') try: m = Map(hash=hash) except MapException: raise web.seeother('/') factor = m.get_factor(factor_id) if factor: return render.base(render.map.edit_factor(factor, hash)) show_map(m)
def __init__(self, file_direction="", graph=[]): #Inicializa Mapa, este crea una matriz con nodos super(TemplateWindow, self).__init__() self.setupUi(self) self.Map = Map(graph, file_direction, file_direction) self.graph = self.Map.get_graph() self.landPaths = [] self.load_coords() self.load_graph() self.load_lands() self.assign_widgets() self.show()
def test_neighboring_tiles_some_good(self): m = Map(10, 10) m.generate_from_ascii("models/maps/10by10.txt") n = Node(m.tile_matrix[4][1], 0, None) neighbors = m.neighboring_tiles(n, CONST.jets) up = m.tile_matrix[4][0] down = m.tile_matrix[4][2] right = m.tile_matrix[5][1] left = m.tile_matrix[3][1] assert (len(neighbors) == 2) assert (up not in neighbors) assert (down in neighbors) assert (right in neighbors) assert (left not in neighbors)
def test_piece_at(self): m = Map(10, 10) m.generate_from_ascii("models/maps/10by10.txt") g = GreaserUnit(2, 2, m, CONST.jets) assert (m.unit_at(2, 2) == g) m.delete_unit(g) assert (m.unit_at(2, 2) == None)
def game_play(screen): map_index = 1 effect_sound = pygame.mixer.Sound("../sounds/abc.wav") SQUARE_SIZE = 40 map = Map() out_game = False pygame.mixer.music.load("../sounds/lactroi.wav") pygame.mixer.music.play(-1) while map_index != 6 and not out_game: map.build_map(map_index) done = False while not done: dx = 0 dy = 0 for event in pygame.event.get(): if event.type == pygame.QUIT: done = True out_game = True elif event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: dx = -1 elif event.key == pygame.K_RIGHT: dx = 1 elif event.key == pygame.K_UP: dy = -1 elif event.key == pygame.K_DOWN: dy = 1 if dx != 0 or dy != 0: [next_px, next_py] = map.player.next_position(dx, dy) if map.check_in_map(next_px, next_py) and not map.check_lose(): map.player.move(dx, dy) effect_sound.play() if map.player.dic_player == map.bat.dic_bat: map.player.dic_player = map.add_bat() if map.player.dic_player == map.gem.dic_gem: done = True map_index += 1 print_map(map, screen, map_index - 1) print_square(screen, SQUARE_SIZE, map.width, map.height) print_text_box(screen) if map.check_around(): print_text(map, screen) pygame.display.flip() if map.check_lose(): done = True out_game = True print_lose(screen) pygame.display.flip() time.sleep(2) if map_index == 6: print_win(screen) pygame.display.flip() time.sleep(2)
def GET(self): data = web.input() hash = data.map if not hash: raise web.seeother('/') try: m = Map(hash=hash) except MapException: raise web.seeother('/') data = m.get_chart_data() if not data: return json.dumps({'success': False}) return json.dumps({'success': True, 'data': data})
def __init__(self,level): super(GameManager, self).__init__() self.observers = [] # keep observers #set game options self.level = level self.map = Map('resources/maps/game_map.tmx') EnemyBrain() EnemyBrain.instance.set_map(self.map) self.count_of_available_player_tanks = 2 self.standart_tanks_count = 3 self.fast_tanks_count = 3 self.heavy_tanks_count = 3 self.count_of_max_enemy_tanks_on_map = 2 self.spawn_index = 0 self.tanks = [] self.bullets = [] self.bonuses = [] self.add_base() self.timeout = 500 self.enemy_way_nodes = []
def test_neighboring_tiles_all_good(self): m = Map(10, 10) m.generate_from_ascii("models/maps/10by10.txt") x = 4 y = 5 n = Node(m.tile_matrix[x][y], 0, None) neighbors = m.neighboring_tiles(n, CONST.jets) up = m.tile_matrix[x][y-1] down = m.tile_matrix[x][y+1] right = m.tile_matrix[x+1][y] left = m.tile_matrix[x-1][y] assert (len(neighbors) == 4) assert (up in neighbors) assert (down in neighbors) assert (right in neighbors) assert (left in neighbors)
def test_1(): map = Map("ressource/map01.txt") assert len(map.start) == 1 assert len(map.goal) == 1 toto = Hero(map) toto.position = map.start[0] assert toto.position.getx == 0 assert toto.position.gety == 0 toto.move('left') # outside the map assert toto.position.getx == 0 assert toto.position.gety == 0 toto.move('up') # outside the map assert toto.position.getx == 0 assert toto.position.gety == 0 toto.move('right') # in the wall assert toto.position.getx == 0 assert toto.position.gety == 0 toto.move('down') # OK assert toto.position.getx == 1 # new x assert toto.position.gety == 0 map.items.append(Position(5, 5)) # put an Item in the list len_items = len(map.items) toto.position = Position(4, 5) # put the hero near the item toto.move('down') # move onto the new items print('coucou {}'.format(toto.position)) assert len_items == len( map.items) + 1 # the item has been removed from the list
class Test(unittest.TestCase): def setUp(self): self.map_obj = Map() self.valid_map = ['START: (0, 0)', 'GO (1000)'] self.not_valid_map = ['START: (0, 0)', 'FLY'] def test_not_valid_map(self): self.assertNotEqual(True, self.map_obj.is_valid(self.not_valid_map)) def test_valid_map(self): self.assertEqual(True, self.map_obj.is_valid(self.valid_map)) def test_valid_map_interpret(self): self.assertEqual([('START', ['0', '0']), ('GO', ['1000'])], self.map_obj.interpret(self.valid_map))
def __init__(self,Map = Map(), characters=list()): super(CharacterEditionWindow,self).__init__() self.setupUi(self) #self.land_path = land_Paths self.Map = Map self.characters = characters self.actual_character = None self.characters_paths = list() self.images_lst.setMinimumHeight(100) if len(characters) == 0: self.characters.append(Character(name="NUEVO PERSONAJE",Map=self.Map)) else: for e in self.characters: e.make_new_copy_of_map(self.Map) self.load_characters_layout() self.load_characters() self.assign_events() SecundaryBtnStyleEnabled = "QPushButton:enabled{background-color:#343a40;border-radius:6px;color:#ffffff;font-family:Verdana;text-decoration:none;}" PrimaryBtnStyleEnabled = "QPushButton:enabled{background-color:#4e73df;border-radius:6px;color:#ffffff;font-family:Verdana;text-decoration:none;}" btnStyleDisabled = " QPushButton:disabled{background-color:#949494;border-radius:6px;font-family:Verdana;text-decoration:none; }" clickEffect = "QPushButton:pressed{border-style:solid;border-width:1px;}" self.accept_btn.setStyleSheet(btnStyleDisabled + PrimaryBtnStyleEnabled + clickEffect) self.go_back_btn.setStyleSheet(btnStyleDisabled + SecundaryBtnStyleEnabled + clickEffect) self.accept_btn.setDisabled(True) self.name_txt.setPlaceholderText("Nombre de personaje") self.name_txt.setMaxLength(15) self.setStyleSheet("font-family:Verdana;") self.showMaximized()
def POST(self): data = web.input() hash = data.mapHash factor = data.factorName if not hash: raise web.seeother('/') try: m = Map(hash=hash) except MapException: raise web.seeother('/') if not factor: show_map(m) editable = is_editable(m, data) if editable: m.add_factor(factor) show_map(m, editable)
def test_add_remove_unit(self): m = Map(10, 10) m.generate_from_ascii("models/maps/10by10.txt") g = GreaserUnit(2, 2, m, CONST.jets) assert (m.tile_matrix[2][2].is_occupied) assert (not m.tile_matrix[3][3].is_occupied) b = BruiserUnit(3, 3, m, CONST.jets) assert (m.tile_matrix[3][3].is_occupied) s = SquabblerUnit(4, 4, m, CONST.jets) assert (m.tile_matrix[4][4].is_occupied) m.delete_unit(g) assert (not m.tile_matrix[2][2].is_occupied) m.delete_unit(b) assert (not m.tile_matrix[3][3].is_occupied) m.delete_unit(s) assert (not m.tile_matrix[4][4].is_occupied)
def POST(self): data = web.input() hash = data.mapHash factor_id = data.factorId factor_name = data.factorName if not hash or not factor_id or not factor_name: raise web.seeother('/') if 'map' not in web.web_session or web.web_session.map != hash: raise web.seeother('/') try: m = Map(hash=hash) except MapException: raise web.seeother('/') factor = m.get_factor(factor_id) if factor: m.edit_factor(factor_id, factor_name) show_map(m)
def POST(self): data = web.input() hash = data.map f = data.f koef = data.koef if not hash: return json.dumps({'success': False, 'error': 'Incorrect data'}) try: m = Map(hash=hash) except MapException: return json.dumps({'success': False, 'error': 'Incorrect data'}) if not f: return json.dumps({'success': False, 'error': 'Incorrect data'}) editable = is_editable(m, data) if editable: m.change_koef(f, koef) return json.dumps({'success': True}) return json.dumps({'success': False, 'error': 'Access denied'})
def POST(self): data = web.input() hash = data.map f1 = data.f1 f2 = data.f2 effect = data.effect if not hash: return json.dumps({'success': False, 'error': 'Incorrect data'}) try: m = Map(hash=hash) except MapException: return json.dumps({'success': False, 'error': 'Incorrect data'}) if not f1 or not f2: return json.dumps({'success': False, 'error': 'Incorrect data'}) editable = is_editable(m, data) if editable: m.change_factor_effect(f1, f2, effect) return json.dumps({'success': True}) return json.dumps({'success': False, 'error': 'Access denied'})
class MainWindow(QtGui.QWidget): def __init__(self, main, path): super(MainWindow, self).__init__() print('>start init main_view') self.main = main self.path = path # init sets self.width_editline = 100 # naglowek self.header = QtGui.QLabel('<h1><b>Albedo Ziemi</b></h1>', self) # # zadeklarowanie wymiarow mapy #self.map = Map(self.x, self.y) self.map = Map(600, 800) # # definicja tablicy rgb self.rgb = [] self.map.init_pixels0() # # nalozenie obrazu na mape self.map.set_pixels() self.map_item = QtGui.QLabel() self.width_map = self.screen_size()['w']-self.width_editline self.height_map = self.screen_size()['h']*self.width_editline self.map_item.setScaledContents(True) self.map_item.setPixmap(QtGui.QPixmap.fromImage(self.map.map)) # check button self.sun = QtGui.QCheckBox('słońce') self.emision = QtGui.QCheckBox('emisja') self.heat = QtGui.QCheckBox('przewodnictwo') #self.const_albedo = QtGui.QCheckBox('rodzaj albedo') self.map_world = QtGui.QCheckBox('wczytanie poprzedniej mapy') self.albedo_mode = QtGui.QComboBox() # editline self.editlines = { 'calls': QtGui.QLineEdit(self), 'albedo_land': QtGui.QLineEdit(self), 'albedo_sea': QtGui.QLineEdit(self), 'coof_reemision': QtGui.QLineEdit(self), 'coof_dyfusion': QtGui.QLineEdit(self), 'sun_const': QtGui.QLineEdit(self), 'meridian_amount': QtGui.QLineEdit(self), 'parallel_amount': QtGui.QLineEdit(self), 'land_specific_heat': QtGui.QLineEdit(self), 'sea_specific_heat': QtGui.QLineEdit(self), } # labels #self.meridian_amount = QLabel('ilość południków: '+str(0), self) #self.parallel_amount = QLabel('ilość równoleżników: '+str(0), self) #self.time = QtGui.QLabel('czas: '+str(0), self) # button self.button = {} self.button["generate"] = QtGui.QPushButton('Generuj') self.button["kill"] = QtGui.QPushButton('Zabij') self.button["test"] = QtGui.QPushButton('Testuj') # napis self.min_temp_value = QtGui.QLabel(str('n/a'), self) self.max_temp_value = QtGui.QLabel(str('n/a'), self) self.avr_temp_value = QtGui.QLabel(str('n/a'), self) self.avr_albedo_value = QtGui.QLabel(str('n/a'), self) #TODO temperatury dac na wyswietlanie w okienku self.year_value = QtGui.QLabel(str('n/a'), self) self.day_value = QtGui.QLabel(str('n/a'), self) self.time_value = QtGui.QLabel(str('n/a'), self) # utworzenie obiektu pod wywolanie symulatora if check_system() == 'linux': self.wywolanie = Calling(self.path.path['simulator'], self, self.main) elif check_system() == 'windows': self.wywolanie = Calling(self.path.path['simulator_win'], self, self.main) #ustawienia self.albedo_mode.setEditable(True) self.albedo_mode.addItems(['1', '2', '3', '4']) self.albedo_mode.setMaximumWidth(100) for key in self.editlines: self.editlines[key].setMaximumWidth(self.width_editline) self.editlines['calls'].setText(str(self.wywolanie.calls_parameters['ilosc_wywolan'])) self.editlines['meridian_amount'].setText(str(self.wywolanie.calls_parameters['ilosc_poludnikow'])) self.editlines['parallel_amount'].setText(str(self.wywolanie.calls_parameters['ilosc_rownoleznikow'])) self.editlines['albedo_land'].setText(str(self.wywolanie.calls_parameters['albedo_parametr_lad'])) self.editlines['albedo_sea'].setText(str(self.wywolanie.calls_parameters['albedo_parametr_morze'])) self.editlines['coof_reemision'].setText(str(self.wywolanie.calls_parameters['wspulczynnik_reemisji'])) self.editlines['coof_dyfusion'].setText(str(self.wywolanie.calls_parameters['wsp_dyf'])) self.editlines['sun_const'].setText(str(self.wywolanie.calls_parameters['stala_sloneczna'])) self.editlines['land_specific_heat'].setText(str(self.wywolanie.calls_parameters['cieplo_wlasciwe_lad'])) self.editlines['sea_specific_heat'].setText(str(self.wywolanie.calls_parameters['cieplo_wlasciwe_morze'])) self.sun.setChecked(True) self.emision.setChecked(True) self.heat.setChecked(True) #self.const_albedo.setChecked(True) self.map_world.setChecked(True) self.initUI() # inicjalizacja widget'ow i layout'u def initUI(self): #layout header_l = [ ('stretch',), ('widget', self.header), ('stretch',), ] self.header_box = self.box('horizontal', header_l) min_temp_l = [ ('widget', QtGui.QLabel('temp min:', self)), ('widget', self.min_temp_value), ] max_temp_l = [ ('widget', QtGui.QLabel('temp maks:', self)), ('widget', self.max_temp_value), ] avr_temp_l = [ ('widget', QtGui.QLabel('temp śr.:', self)), ('widget', self.avr_temp_value), ] avr_albedo_l = [ ('widget', QtGui.QLabel('albedo śr.:', self)), ('widget', self.avr_albedo_value), ('widget', self.albedo_mode) ] time_l = [ ('widget', QtGui.QLabel('czas', self)), ('widget', self.year_value), ('widget', QtGui.QLabel('rok,', self)), ('widget', self.day_value), ('widget', QtGui.QLabel('dzień,:', self)), ('widget', self.time_value), ] self.min_temp_box = self.box('horizontal', min_temp_l) self.max_temp_box = self.box('horizontal', max_temp_l) self.avr_temp_box = self.box('horizontal', avr_temp_l) self.avr_albedo_box = self.box('horizontal', avr_albedo_l) self.time_box = self.box('horizontal', time_l) side_bar_l = [ ('stretch',), # editline ('widget', QtGui.QLabel('ilość południków', self)), ('widget', self.editlines['meridian_amount']), ('widget', QtGui.QLabel('ilość równoleżników', self)), ('widget', self.editlines['parallel_amount']), ('widget', QtGui.QLabel('stała słoneczna', self)), ('widget', self.editlines['sun_const']), ('widget', QtGui.QLabel('współczynnik reemisji', self)), ('widget', self.editlines['coof_reemision']), ('widget', QtGui.QLabel('współczynnik dyfuzji', self)), ('widget', self.editlines['coof_dyfusion']), ('stretch',), # radio button ('widget', self.sun), ('widget', self.emision), ('widget', self.heat), ('stretch',), # editline (continued) ('widget', QtGui.QLabel('współczynnik albedo dla lądu', self)), ('widget', self.editlines['albedo_land']), ('widget', QtGui.QLabel('współczynnik albedo dla morza', self)), ('widget', self.editlines['albedo_sea']), #TODO rodzaj albedo #('widget', self.const_albedo), ('widget', QtGui.QLabel('ilość wywołań', self)), ('widget', self.editlines['calls']), #TODO cieplo wlasciwe ladu ('widget', QtGui.QLabel('ciepło właściwe lądu', self)), ('widget', self.editlines['land_specific_heat']), #TODO cieplo wlasciwe morza ('widget', QtGui.QLabel('ciepło właściwe morza', self)), ('widget', self.editlines['sea_specific_heat']), #TODO czyt_mape_swiata ('widget', self.map_world), ('widget', QtGui.QLabel('rodzaj albedo', self)), ('widget', self.albedo_mode), ('stretch',), # labels #('widget', self.meridian_amount), #('widget', self.parallel_amount), ('layout', self.min_temp_box), ('layout', self.max_temp_box), ('layout', self.avr_temp_box), ('layout', self.avr_albedo_box), ('layout', self.time_box), ('stretch',), # button ('widget', self.button["generate"]), ('widget', self.button["kill"]), #('widget', self.button["test"]), ('stretch',), ] self.side_bar_box = self.box('vertical', side_bar_l) print('side bar width:', self.side_bar_box.contentsRect().width()) #self.width_map = 800 #self.height_map = self.width_map/5 map_hl = [ ('stretch',), ('widget', self.map_item), ('stretch',), ] self.map_hbox = self.box('horizontal', map_hl) map_vl = [ ('stretch',), ('layout', self.map_hbox), ('stretch',), ] self.map_vbox = self.box('vertical', map_vl) bottom_l = [ ('layout', self.map_vbox), ('layout', self.side_bar_box), ] self.bottom_box = self.box('horizontal', bottom_l) main_l = [ ('layout', self.header_box), ('layout', self.bottom_box), ] self.mainbox = self.box('vertical', main_l) #podpiecie przyciskow slots = { 'generate': self.generate, 'test': self.test, 'kill': QtCore.QCoreApplication.instance().quit, } self.slot_conn(slots) self.setLayout(self.mainbox) self.show() self.main.statusBar().showMessage('Symulator w stanie gotowości.') # ustawienie rozmiaru labela mapy self.width_map = self.screen_size()['w'] - self.side_bar_box.contentsRect().width()*1.5 self.height_map = self.width_map/2 self.set_map_label_size() # definicja podpiec def slot_conn(self, slots={}): for key in slots: self.button[key].clicked.connect(slots[key]) print(">checkpoint: slots plugging for key: ", key, 'in class: ', self.__class__.__name__) # definicje funkcji podpinanych do przyciskow def generate(self): self.main.statusBar().showMessage('Trwają symulacje...') self.generate_map() self.main.statusBar().showMessage('Symulator jest w stanie gotowości.') print('generuje') def kill(self): print('morduje') #print(self.albedo_mode.itemData(self.albedo_mode.currentIndex())) self.main.stacked_widget.removeWidget(self.main.stacked_widget.currentWidget()) def test(self): #print(self.albedo_mode.itemData(self.albedo_mode.currentIndex())) print(self.albedo_mode.currentText()) #print('test przycisku test') # pomocnicza metoda do budowania layout'u def box(self, el_type, elems): if el_type == 'vertical': box = QtGui.QVBoxLayout() elif el_type == 'horizontal': box = QtGui.QHBoxLayout() for elem in elems: if elem[0] == 'stretch': box.addStretch(1) elif elem[1] is not None: if elem[0] == 'widget': box.addWidget(elem[1]) elif elem[0] == 'layout': box.addLayout(elem[1]) return box def temp_to_rgb(self): self.rgb = [] for row in self.map_data.map_data: row_rgb = [] for item in row: if item < self.min_temp: self.min_temp = item if item > self.max_temp: self.max_temp = item item_rgb = {} item_rgb['r'] = item item_rgb['g'] = item item_rgb['b'] = item row_rgb.append(item_rgb) self.rgb.append(row_rgb) def generate_map(self): # definiowanie parametrow calls_temp = self.editlines['calls'].text() if calls_temp != '': self.wywolanie.calls_parameters['ilosc_wywolan'] = calls_temp meridian_amount_temp = self.editlines['meridian_amount'].text() if meridian_amount_temp != '': self.wywolanie.calls_parameters['ilosc_poludnikow'] = meridian_amount_temp parallel_amount_temp = self.editlines['parallel_amount'].text() if parallel_amount_temp != '': self.wywolanie.calls_parameters['ilosc_rownoleznikow'] = parallel_amount_temp albedo_sea_temp = self.editlines['albedo_sea'].text() if albedo_sea_temp != '': self.wywolanie.calls_parameters['albedo_parametr_morze'] = albedo_sea_temp albedo_land_temp = self.editlines['albedo_land'].text() if albedo_land_temp != '': self.wywolanie.calls_parameters['albedo_parametr_lad'] = albedo_land_temp coof_reem = self.editlines['coof_reemision'].text() if coof_reem != '': self.wywolanie.calls_parameters['wspulczynnik_reemisji'] = coof_reem coof_dyf = self.editlines['coof_dyfusion'].text() if coof_dyf != '': self.wywolanie.calls_parameters['wsp_dyf'] = coof_dyf sun_const = self.editlines['sun_const'].text() if sun_const != '': self.wywolanie.calls_parameters['stala_sloneczna'] = sun_const sun = self.sun.isChecked() emis = self.emision.isChecked() heat = self.heat.isChecked() #c_albedo = self.const_albedo.isChecked() world = self.map_world.isChecked() if sun: self.wywolanie.calls_parameters['fun_slonce'] = 1 else: self.wywolanie.calls_parameters['fun_slonce'] = 0 if emis: self.wywolanie.calls_parameters['fun_emisja'] = 1 else: self.wywolanie.calls_parameters['fun_emisja'] = 0 if heat: self.wywolanie.calls_parameters['fun_wymiana_ciepla'] = 1 else: self.wywolanie.calls_parameters['fun_wymiana_ciepla'] = 0 albedo_mode = self.albedo_mode.currentText() if albedo_mode == '1': self.wywolanie.calls_parameters['albedo_rodzaj'] = 1 elif albedo_mode == '2': self.wywolanie.calls_parameters['albedo_rodzaj'] = 2 elif albedo_mode == '3': self.wywolanie.calls_parameters['albedo_rodzaj'] = 3 elif albedo_mode == '4': self.wywolanie.calls_parameters['albedo_rodzaj'] = 4 else: print('zadne albedo_mode nie zostalo wybrane') # if c_albedo: # self.wywolanie.calls_parameters['albedo_rodzaj'] = 1 # else: # self.wywolanie.calls_parameters['albedo_rodzaj'] = 0 if world: self.wywolanie.calls_parameters['czyt_mape_swiata'] = 1 else: self.wywolanie.calls_parameters['czyt_mape_swiata'] = 0 self.wywolanie.run() #tymczasowo przerwanie funkcji return # tutaj ustawianie wartosci # # odczyt pliku self.map_data = None if check_system() == 'linux': self.map_data = DataStorage(self.path.path['simulator'] + 'temperatura_0.txt') elif check_system() == 'windows': self.map_data = DataStorage(self.path.path['simulator_win'] + 'temperatura_0.txt') self.x = self.map_data.rows self.y = self.map_data.columns print('x map', self.x) print('y map', self.y) self.min_temp = float('inf') self.max_temp = 0 map_old = self.map self.map = Map(self.x, self.y) #del map_old self.temp_to_rgb() #print('rgb:\n', self.rgb) #zmieniam recznie max, min #self.min_temp = 300 #self.max_temp = 400 # # definicja obrazu mapy self.range_temp = self.max_temp-self.min_temp print('x rgb', len(self.rgb)) print('y rgb', len(self.rgb[0])) self.map.init_pixels(self.rgb, self.min_temp, self.range_temp) # # nalozenie obrazu na mape self.map.set_pixels() # # przypiecie obrazu self.map_item.setPixmap(QtGui.QPixmap.fromImage(self.map.map)) # # ustawianie napisow #self.min_temp_value.setText(str(int(self.min_temp-273.15))) #self.max_temp_value.setText(str(int(self.max_temp-273.15))) def screen_size(self): rec = QtGui.QApplication.desktop().screenGeometry() height = rec.height() width = rec.width() return {'w': width, 'h': height} def set_map_label_size(self): w = self.width_map h = self.height_map self.map_item.setMaximumWidth(w) self.map_item.setMaximumHeight(h) self.map_item.setMinimumWidth(w) self.map_item.setMinimumHeight(h)
def test_can_go_through_unit(self): m = Map(10, 10) m.generate_from_ascii("models/maps/10by10.txt") g = GreaserUnit(4, 5, m, CONST.jets) assert (m.can_go_through(4, 5, CONST.jets)) assert (not m.can_go_through(4, 5, CONST.sharks))
def __init__(self, main, path): super(MainWindow, self).__init__() print('>start init main_view') self.main = main self.path = path # init sets self.width_editline = 100 # naglowek self.header = QtGui.QLabel('<h1><b>Albedo Ziemi</b></h1>', self) # # zadeklarowanie wymiarow mapy #self.map = Map(self.x, self.y) self.map = Map(600, 800) # # definicja tablicy rgb self.rgb = [] self.map.init_pixels0() # # nalozenie obrazu na mape self.map.set_pixels() self.map_item = QtGui.QLabel() self.width_map = self.screen_size()['w']-self.width_editline self.height_map = self.screen_size()['h']*self.width_editline self.map_item.setScaledContents(True) self.map_item.setPixmap(QtGui.QPixmap.fromImage(self.map.map)) # check button self.sun = QtGui.QCheckBox('słońce') self.emision = QtGui.QCheckBox('emisja') self.heat = QtGui.QCheckBox('przewodnictwo') #self.const_albedo = QtGui.QCheckBox('rodzaj albedo') self.map_world = QtGui.QCheckBox('wczytanie poprzedniej mapy') self.albedo_mode = QtGui.QComboBox() # editline self.editlines = { 'calls': QtGui.QLineEdit(self), 'albedo_land': QtGui.QLineEdit(self), 'albedo_sea': QtGui.QLineEdit(self), 'coof_reemision': QtGui.QLineEdit(self), 'coof_dyfusion': QtGui.QLineEdit(self), 'sun_const': QtGui.QLineEdit(self), 'meridian_amount': QtGui.QLineEdit(self), 'parallel_amount': QtGui.QLineEdit(self), 'land_specific_heat': QtGui.QLineEdit(self), 'sea_specific_heat': QtGui.QLineEdit(self), } # labels #self.meridian_amount = QLabel('ilość południków: '+str(0), self) #self.parallel_amount = QLabel('ilość równoleżników: '+str(0), self) #self.time = QtGui.QLabel('czas: '+str(0), self) # button self.button = {} self.button["generate"] = QtGui.QPushButton('Generuj') self.button["kill"] = QtGui.QPushButton('Zabij') self.button["test"] = QtGui.QPushButton('Testuj') # napis self.min_temp_value = QtGui.QLabel(str('n/a'), self) self.max_temp_value = QtGui.QLabel(str('n/a'), self) self.avr_temp_value = QtGui.QLabel(str('n/a'), self) self.avr_albedo_value = QtGui.QLabel(str('n/a'), self) #TODO temperatury dac na wyswietlanie w okienku self.year_value = QtGui.QLabel(str('n/a'), self) self.day_value = QtGui.QLabel(str('n/a'), self) self.time_value = QtGui.QLabel(str('n/a'), self) # utworzenie obiektu pod wywolanie symulatora if check_system() == 'linux': self.wywolanie = Calling(self.path.path['simulator'], self, self.main) elif check_system() == 'windows': self.wywolanie = Calling(self.path.path['simulator_win'], self, self.main) #ustawienia self.albedo_mode.setEditable(True) self.albedo_mode.addItems(['1', '2', '3', '4']) self.albedo_mode.setMaximumWidth(100) for key in self.editlines: self.editlines[key].setMaximumWidth(self.width_editline) self.editlines['calls'].setText(str(self.wywolanie.calls_parameters['ilosc_wywolan'])) self.editlines['meridian_amount'].setText(str(self.wywolanie.calls_parameters['ilosc_poludnikow'])) self.editlines['parallel_amount'].setText(str(self.wywolanie.calls_parameters['ilosc_rownoleznikow'])) self.editlines['albedo_land'].setText(str(self.wywolanie.calls_parameters['albedo_parametr_lad'])) self.editlines['albedo_sea'].setText(str(self.wywolanie.calls_parameters['albedo_parametr_morze'])) self.editlines['coof_reemision'].setText(str(self.wywolanie.calls_parameters['wspulczynnik_reemisji'])) self.editlines['coof_dyfusion'].setText(str(self.wywolanie.calls_parameters['wsp_dyf'])) self.editlines['sun_const'].setText(str(self.wywolanie.calls_parameters['stala_sloneczna'])) self.editlines['land_specific_heat'].setText(str(self.wywolanie.calls_parameters['cieplo_wlasciwe_lad'])) self.editlines['sea_specific_heat'].setText(str(self.wywolanie.calls_parameters['cieplo_wlasciwe_morze'])) self.sun.setChecked(True) self.emision.setChecked(True) self.heat.setChecked(True) #self.const_albedo.setChecked(True) self.map_world.setChecked(True) self.initUI()
def generate_map(self): # definiowanie parametrow calls_temp = self.editlines['calls'].text() if calls_temp != '': self.wywolanie.calls_parameters['ilosc_wywolan'] = calls_temp meridian_amount_temp = self.editlines['meridian_amount'].text() if meridian_amount_temp != '': self.wywolanie.calls_parameters['ilosc_poludnikow'] = meridian_amount_temp parallel_amount_temp = self.editlines['parallel_amount'].text() if parallel_amount_temp != '': self.wywolanie.calls_parameters['ilosc_rownoleznikow'] = parallel_amount_temp albedo_sea_temp = self.editlines['albedo_sea'].text() if albedo_sea_temp != '': self.wywolanie.calls_parameters['albedo_parametr_morze'] = albedo_sea_temp albedo_land_temp = self.editlines['albedo_land'].text() if albedo_land_temp != '': self.wywolanie.calls_parameters['albedo_parametr_lad'] = albedo_land_temp coof_reem = self.editlines['coof_reemision'].text() if coof_reem != '': self.wywolanie.calls_parameters['wspulczynnik_reemisji'] = coof_reem coof_dyf = self.editlines['coof_dyfusion'].text() if coof_dyf != '': self.wywolanie.calls_parameters['wsp_dyf'] = coof_dyf sun_const = self.editlines['sun_const'].text() if sun_const != '': self.wywolanie.calls_parameters['stala_sloneczna'] = sun_const sun = self.sun.isChecked() emis = self.emision.isChecked() heat = self.heat.isChecked() #c_albedo = self.const_albedo.isChecked() world = self.map_world.isChecked() if sun: self.wywolanie.calls_parameters['fun_slonce'] = 1 else: self.wywolanie.calls_parameters['fun_slonce'] = 0 if emis: self.wywolanie.calls_parameters['fun_emisja'] = 1 else: self.wywolanie.calls_parameters['fun_emisja'] = 0 if heat: self.wywolanie.calls_parameters['fun_wymiana_ciepla'] = 1 else: self.wywolanie.calls_parameters['fun_wymiana_ciepla'] = 0 albedo_mode = self.albedo_mode.currentText() if albedo_mode == '1': self.wywolanie.calls_parameters['albedo_rodzaj'] = 1 elif albedo_mode == '2': self.wywolanie.calls_parameters['albedo_rodzaj'] = 2 elif albedo_mode == '3': self.wywolanie.calls_parameters['albedo_rodzaj'] = 3 elif albedo_mode == '4': self.wywolanie.calls_parameters['albedo_rodzaj'] = 4 else: print('zadne albedo_mode nie zostalo wybrane') # if c_albedo: # self.wywolanie.calls_parameters['albedo_rodzaj'] = 1 # else: # self.wywolanie.calls_parameters['albedo_rodzaj'] = 0 if world: self.wywolanie.calls_parameters['czyt_mape_swiata'] = 1 else: self.wywolanie.calls_parameters['czyt_mape_swiata'] = 0 self.wywolanie.run() #tymczasowo przerwanie funkcji return # tutaj ustawianie wartosci # # odczyt pliku self.map_data = None if check_system() == 'linux': self.map_data = DataStorage(self.path.path['simulator'] + 'temperatura_0.txt') elif check_system() == 'windows': self.map_data = DataStorage(self.path.path['simulator_win'] + 'temperatura_0.txt') self.x = self.map_data.rows self.y = self.map_data.columns print('x map', self.x) print('y map', self.y) self.min_temp = float('inf') self.max_temp = 0 map_old = self.map self.map = Map(self.x, self.y) #del map_old self.temp_to_rgb() #print('rgb:\n', self.rgb) #zmieniam recznie max, min #self.min_temp = 300 #self.max_temp = 400 # # definicja obrazu mapy self.range_temp = self.max_temp-self.min_temp print('x rgb', len(self.rgb)) print('y rgb', len(self.rgb[0])) self.map.init_pixels(self.rgb, self.min_temp, self.range_temp) # # nalozenie obrazu na mape self.map.set_pixels() # # przypiecie obrazu self.map_item.setPixmap(QtGui.QPixmap.fromImage(self.map.map))
class GameManager(object): def __init__(self,level): super(GameManager, self).__init__() self.observers = [] # keep observers #set game options self.level = level self.map = Map('resources/maps/game_map.tmx') EnemyBrain() EnemyBrain.instance.set_map(self.map) self.count_of_available_player_tanks = 2 self.standart_tanks_count = 3 self.fast_tanks_count = 3 self.heavy_tanks_count = 3 self.count_of_max_enemy_tanks_on_map = 2 self.spawn_index = 0 self.tanks = [] self.bullets = [] self.bonuses = [] self.add_base() self.timeout = 500 self.enemy_way_nodes = [] def update(self): self.move_bullets() self.move_tanks() self.save() pass def updateSpawnTanks(self): self.check_if_need_add_tanks_to_map() def check_if_need_add_tanks_to_map(self): is_player_tank_on_map = hasattr(self,'player_tank') count_of_enemy_tanks_on_map = len(self.tanks) - 1 if is_player_tank_on_map else 0 if (count_of_enemy_tanks_on_map < self.count_of_max_enemy_tanks_on_map): self.add_enemy_tank_to_map() if not is_player_tank_on_map: self.add_player_tank_to_map() def draw_enemy_moved_path(self, way_nodes): for node in self.enemy_way_nodes: node.kill() self.enemy_way_nodes = [] for node in way_nodes: test_node = cocos.sprite.Sprite('resources/maps/test_marker2.png') test_node.position = node.position.x, node.position.y self.map.add(test_node,z = 100) self.enemy_way_nodes.append(test_node) def add_enemy_tank_to_map(self): tank_type = self.get_available_tank_type() if tank_type == -1: return enemy_tank = TankBase(tank_type) enemy_tank.attach(self) self.tanks.append(enemy_tank) count_of_spawn_point = len(self.map.enemy_spawn_points) if count_of_spawn_point > 0: enemy_tank.setPosition(self.map.enemy_spawn_points[self.spawn_index].position) if self.spawn_index + 1 == count_of_spawn_point: self.spawn_index = 0 else: self.spawn_index += 1 else: enemy_tank.setPosition(20, 200) self.map.add(enemy_tank) def add_player_tank_to_map(self,tankType = 3): if self.count_of_available_player_tanks == 0: return self.count_of_available_player_tanks -= 1 self.player_tank = TankBase(tankType,isEnemy = False) self.player_tank.attach(self) self.player_tank.attach(EnemyBrain.instance) self.tanks.append(self.player_tank) count_of_spawn_point = len(self.map.player_spawn_points) if count_of_spawn_point > 0: randPointIndex = randint(0,count_of_spawn_point-1) self.player_tank.setPosition(self.map.player_spawn_points[randPointIndex].position) else: self.player_tank.setPosition(self.map.player_spawn_points[randPointIndex].position) self.map.add(self.player_tank) def add_base(self): self.base = cocos.sprite.Sprite('resources/base/base.png') self.base.position = self.map.base_spawn_point.position self.map.add(self.base) EnemyBrain.instance.set_player_base_position(self.base.position) #--------------------base system --------------- def is_rect_hit_base(self,rect): if self.base: base_rect = self.base.get_rect() return base_rect.intersect(rect) def destroy_base(self): if self.base: self.base.kill() self.base = None self.player_loose() ###################################################### ## Bonus system def add_bonus_to_map(self): x = randint(1,24)*20 y = randint(1,24)*20 self.bonus = Bonus(randint(0,3),position=(x,y)) self.bonus.attach(self) self.map.add(self.bonus, z = 5) self.bonuses.append(self.bonus) def check_if_bonus_need(self): if len(self.bonuses) == 0: self.add_bonus_to_map() def check_if_tank_get_bonus(self): is_player_tank_on_map = hasattr(self,'player_tank') if is_player_tank_on_map: tank_rect = self.player_tank.get_rect() for bonus in self.bonuses: bonus_rect = bonus.get_rect() if tank_rect.intersects(bonus_rect): bonus.tank_took_it() self.reward(bonus.get_bonus_type()) def updateBonus(self): if self.timeout <= 0: self.check_if_bonus_need() self.timeout = 500 self.check_if_tank_get_bonus() self.timeout -= 1 def removeBonus(self,bonus): if bonus in self.bonuses: self.bonuses.remove(bonus) def reward(self,bonusType): if bonusType == 0: # make tank more powerfull self.upgrade_tank() elif bonusType == 1: # slow down enemy tank self.slow_down_all_enemy_tanks() else: # destroy all enemy tanks self.destroy_all_enemy_tanks() def slow_down_all_enemy_tanks(self): for tank in self.tanks: if tank.isEnemy: tank.slowDown() def destroy_all_enemy_tanks(self): # destroy all enemy tanks on the map for tank in self.tanks: if tank.isEnemy: self.tankDestroyed(tank) tank.destroy() def upgrade_tank(self): if self.player_tank.getPower() == 3: #self.player_tank.setPath("resources/tanks/tank_player_heavy.png") for tank in self.tanks: if not tank.isEnemy: self.player_tank.image = pyglet.resource.image("resources/tanks/neon_tank_player_heavy.png") #self.tanks.remove(tank) #x,y = self.player_tank.getPosition() #direction = self.player_tank.getDirection() #self.player_tank.destroy() #self.add_player_tank_to_map(4,direction,position=(x,y)) #self.player_tank.setDirection(direction) #self.player_tank.setPosition(position=(x,y)) ############################################################ ## Bonus system end ## def move_bullets(self): self.remove_bullets_that_intersects() for bullet in self.bullets: if not self.is_rect_inside_map(bullet.get_rect()): bullet.destroy() self.bullets.remove(bullet) elif self.is_bullet_hit_some_block(bullet) or self.is_bullet_hit_some_tank(bullet): bullet.destroy() self.bullets.remove(bullet) elif self.is_rect_hit_base(bullet.get_rect()): bullet.destroy() self.bullets.remove(bullet) self.destroy_base() elif not bullet.isMoving: bullet.move() def move_tanks(self): for tank in self.tanks: if not tank.isMoving: if self.is_rect_inside_map(tank.get_next_step_rect()): if not self.is_tank_will_hit_some_tank(tank): if not self.is_tank_will_hit_some_block(tank): if not self.is_rect_hit_base(tank.get_next_step_rect()): tank.move() ################################################### ## HELPERS def is_rect_inside_map(self,rect): mapRect = cocos.rect.Rect(0,0,520,520) bottom_left_corner_inside = mapRect.contains(rect.x,rect.y) top_right_corner_inside = mapRect.contains(rect.topright[0],rect.topright[1]) return bottom_left_corner_inside and top_right_corner_inside def is_tank_will_hit_some_tank(self,tank): tank_rect = tank.get_next_step_rect() for tmp_tank in self.tanks: if tmp_tank != tank: tmp_tank_rect = tmp_tank.get_rect() if tank_rect.intersect(tmp_tank_rect): return True return False def is_tank_will_hit_some_block(self,tank): rect = tank.get_next_step_rect() rect.x += 1 rect.y += 1 rect.width -= 2 rect.height -= 2 tank_position = rect.x + rect.width/2, rect.y + rect.height/2 return not self.map.isTankCanMoveInRect(rect) def is_bullet_hit_some_block(self,bullet): return not self.map.isBulletCanMove(bullet) def is_bullet_hit_some_tank(self,bullet): is_bullet_hit_tank = False for tank in self.tanks: if tank.isEnemy != bullet.isEnemy: tank_rect = tank.get_rect() bullet_rect = bullet.get_rect() if tank_rect.intersects(bullet_rect): tank.damage(bullet.power) if is_bullet_hit_tank == False: is_bullet_hit_tank = True return is_bullet_hit_tank def remove_bullets_that_intersects(self): for bullet1 in self.bullets: for bullet2 in self.bullets: if bullet1 != bullet2: bullet1_rect = bullet1.get_rect() bullet2_rect = bullet2.get_rect() if bullet1_rect.intersects(bullet2_rect): bullet1.destroy() bullet2.destroy() self.bullets.remove(bullet1) self.bullets.remove(bullet2) def get_available_tank_type(self): type_list = [self.standart_tanks_count,self.fast_tanks_count,self.heavy_tanks_count] if (type_list[0] + type_list[1] + type_list[2] == 0): return -1 while True: tank_type = randint(0,2) if type_list[tank_type] > 0: if tank_type == 0: self.standart_tanks_count -= 1 elif tank_type == 1: self.fast_tanks_count -= 1 elif tank_type == 2: self.heavy_tanks_count -= 1 return tank_type #################################################### ## Observers methods def attach(self,observer): #attach observer self.observers.append(observer) self.update_info_for_observers() def update_info_for_observers(self): for observer in self.observers: if hasattr(observer,'update_info'): info = {} info["heavy_tanks_count"] = self.heavy_tanks_count info["standart_tanks_count"] = self.standart_tanks_count info["fast_tanks_count"] = self.fast_tanks_count info["count_of_available_player_tanks"] = self.count_of_available_player_tanks observer.update_info(info) #################################################### ## TANK Observers methods def __call__(self, *arg): #print "observer call ",arg pass def tankShoot(self,bullet): self.bullets.append(bullet) self.map.add(bullet,z=2) def tankDestroyed(self,tank): if tank in self.tanks: self.tanks.remove(tank) self.update_info_for_observers() if tank == self.player_tank: del(self.player_tank) if self.count_of_available_player_tanks == 0: self.player_loose() if len(self.tanks) == 1 and self.standart_tanks_count == 0 and self.fast_tanks_count == 0 and self.heavy_tanks_count == 0: self.player_win() ###################################################### ### SAVE & LOAD def save(self): root = ET.Element('game') root.attrib = {'level':str(self.level)} for tank in self.tanks: tank.getXmlWithParrentNode(root) for bullet in self.bullets: bulletNode = bullet.getXmlWithParrentNode(root) self.map.getXmlWithParrentNode(root) xmlData = ET.tostring(root, encoding="utf-8") xmlFile = open('resources/saves/test.xml','wb') xmlFile.write(xmlData) xmlFile.close() ''' root = ET.Element('root') root.attrib = {'ID':'FILES_INFO'} files = self.getFilesFromResources() i = 0 for tmpFile in files: nodeFile = ET.SubElement(root,'file') nodeFileId = ET.SubElement(nodeFile,'id') nodeFileId.text = str(i) nodeFileName = ET.SubElement(nodeFile,'name') nodeFileName.text = tmpFile.split('/')[-1] nodeFilePath = ET.SubElement(nodeFile,'path') nodeFilePath.text = tmpFile nodeFilePath = ET.SubElement(nodeFile,'description') nodeFilePath.text = "default description" i += 1 xmlData = ET.tostring(root, encoding="utf-8") xmlFile = open(self.resourcesXML,'wb') xmlFile.write(xmlData) xmlFile.close() ''' def load(self): pass ###################################################### ### GAME ENDED def player_win(self): winner = cocos.scene.Scene(WinnerScreen()) cocos.director.director.push(winner) def player_loose(self): loser = cocos.scene.Scene(LoserScreen()) cocos.director.director.push(loser)