Esempio n. 1
0
    def __init__(self, x_max, y_max, is_displayed, player1, player2):
        self.x_max = x_max
        self.y_max = y_max
        self.zones_x = 20
        self.zones_y = 20

        self.tank1 = Tank(5, randint(0, x_max), randint(0, y_max),
                          randint(0, 359), 10, 0)
        self.tank2 = Tank(5, randint(0, x_max), randint(0, y_max),
                          randint(0, 359), 10, 1)

        self.player1 = player1
        self.player2 = player2

        self.is_displayed = is_displayed

        if self.is_displayed:
            self.master = tk.Tk()
            canvas_width, canvas_height = 800, 800
            screen_width, screen_height = self.master.winfo_screenwidth(
            ), self.master.winfo_screenheight()
            x, y = (screen_width / 2) - (canvas_width / 2), (
                screen_height / 2) - (canvas_height / 2)
            self.master.geometry('%dx%d+%d+%d' %
                                 (canvas_width, canvas_height, x, y))
            self.visual_playground = tk.Canvas(self.master,
                                               width=canvas_width,
                                               height=canvas_height)
            self.hp = tk.Label(master=self.master, text="Hp: ")
            self.hp.pack()
Esempio n. 2
0
    def start(self):
        self.wn = turtle.Screen()
        self.wn.bgcolor("white")
        self.wn.setup(width=800, height=600)

        self.wn.title('Tank Battle')

        teams = ["User", "Computer"]

        for team in teams:
            self.wn.register_shape(f'Assets/{team}/tank.gif')
            self.wn.register_shape(f'Assets/{team}/tankright.gif')
            self.wn.register_shape(f'Assets/{team}/tankleft.gif')
            self.wn.register_shape(f'Assets/{team}/tankdown.gif')

        user_tank = Tank(start_pos=(-349, 0), direction="R")
        computer_tank = Tank(team="Computer",
                             start_pos=(349, 0),
                             direction="L")

        self.wn.listen()
        self.wn.onkeypress(user_tank.move_up, "w")
        self.wn.onkeypress(user_tank.move_down, 's')
        self.wn.onkeypress(user_tank.move_right, 'd')
        self.wn.onkeypress(user_tank.move_left, 'a')
        self.wn.onkeypress(user_tank.rotate_right, 'e')
        self.wn.onkeypress(user_tank.rotate_left, 'q')

        while True:
            self.wn.update()
Esempio n. 3
0
def start_as_guest(sock):
    data = ""
    while True:
        pack = sock.recv(1024).decode('utf8')
        data += pack
        if "$" in pack:
            break
    data = data.replace("$", "").split(";")
    pygame.display.init()
    pygame.font.init()
    resX = int(data[0].replace('\'(', '').replace('\')', ''))
    resY = int(data[1].replace('\'(', '').replace('\')', ''))
    color_l = ast.literal_eval(data[2])
    color_t1 = ast.literal_eval(data[4])
    color_t2 = ast.literal_eval(data[5])
    screen = pygame.display.set_mode((resX, resY))
    pygame.display.set_caption("GUEST")
    point_dict = ast.literal_eval(data[3])
    land = Land(screen, color_l, resX, resY)
    land.road_map = point_dict
    tank1 = Tank(screen, color_t1, land=land, weapon_list=load_weapons())
    tank2 = Tank(screen, color_t2, land=land, weapon_list=load_weapons())
    tank2.angle = 180
    player1 = Player(tank1, land, screen, tank2)
    player2 = Player(tank2, land, screen, tank1)
    return player1, player2
Esempio n. 4
0
    def __init__(self):
        self.window = pygame.display.set_mode((1280, 1024))
        self.surface = pygame.display.get_surface()
        self.entitylist = []

        self.clock = pygame.time.Clock()
        self.clock.tick(200)
        self.time = 0
        self.generation = 1
        self.abs_highscore = 0

        pygame.display.set_caption("Evolution v1")

        try:
            text = open("data.evo", "r")
            best_brains = pickle.load(text)
            self.generation = best_brains.pop(0)
            text.close
        except:
            best_brains = []

        self.text_renderer = pygame.font.Font(None, 25)

        for i in range(self.NUM_OF_FOOD):
            self.createfood()

        for i in range(self.NUM_OF_TANKS):
            x = random.randint(0, self.surface.get_width())
            y = random.randint(0, self.surface.get_height())
            if len(best_brains) == 0:
                tank = Tank(self, x, y)
            else:
                tank = Tank(self, x, y, random.choice(best_brains)[:])
Esempio n. 5
0
 def draw_tanks_on_field(self):
     size = 10
     scale_x, scale_y = self.visual_playground.winfo_width(
     ) / self.x_max, self.visual_playground.winfo_height() / self.y_max
     x1, y1, dir1, x2, y2, dir2 = self.tank1.x * scale_x, self.tank1.y * scale_y, self.tank1.direction, self.tank2.x * scale_x, self.tank2.y * scale_y, self.tank2.direction
     points_tank1, points_tank2, delta_x, delta_y = [], [], [
         -size, size, size, -size
     ], [size, size, -size, -size]
     for i in range(0, 4, 1):
         rot_x1, rot_y1 = x1 + (delta_x[i] * cos(dir1) - delta_y[i] *
                                sin(dir1)), y1 + (delta_x[i] * sin(dir1) +
                                                  delta_y[i] * cos(dir1))
         rot_x2, rot_y2 = x2 + (delta_x[i] * cos(dir2) - delta_y[i] *
                                sin(dir2)), y2 + (delta_x[i] * sin(dir2) +
                                                  delta_y[i] * cos(dir2))
         points_tank1.append(rot_x1)
         points_tank1.append(rot_y1)
         points_tank2.append(rot_x2)
         points_tank2.append(rot_y2)
     self.visual_playground.create_polygon(points_tank1, fill='blue')
     self.visual_playground.create_polygon(points_tank2, fill='red')
     self.tank1 = Tank(0.1, randint(0, self.x_max), randint(0, self.y_max),
                       randint(0, 359), 0)
     self.tank2 = Tank(0.1, randint(0, self.x_max), randint(0, self.y_max),
                       randint(0, 359), 1)
Esempio n. 6
0
def run_game():
    # 进行 pygame 设置和屏幕初始化
    pygame.init()
    pygame.mixer.init()
    
    # 键盘检测的重复检测 比如一直按着某个键也会重复读取该键的操作 未开启:一直按着w 只会检测一次 按下w的操作.  而开启后 一直按着w 会检测到 很多次 按下w的操作
    # pygame.key.set_repeat(1, 10)
    ai_setting = Settings()
    # 屏幕初始化
    screen = pygame.display.set_mode(
        (ai_setting.screen_width, ai_setting.screen_height))
    # 标题名字设置
    pygame.display.set_caption("tank_fight")
    # 开始动画
    sc.main_menu(ai_setting, screen)
    # 音乐初始化
    gf.music_player()
    end_theme = End_theme(screen, ai_setting)
    # 创建两个坦克
    tank_1 = Tank(ai_setting, screen, ai_setting.player_1_key, pygame.image.load("./picture/tank.jpeg"),
                  ai_setting.tank_1_pos)
    tank_2 = Tank(ai_setting, screen, ai_setting.player_2_key, pygame.image.load("./picture/tank2.jpeg"),
                  ai_setting.tank_2_pos)
    scoreboard = Scoreboard(ai_setting, screen)
    bricks = Group()
    iron_bricks = Group()
    # 坦克加速道具
    prop_tank = Group()
    prop_bullet = Group()
    gf.gen_brick(bricks, ai_setting, screen)
    gf.gen_Ibrick(iron_bricks, ai_setting, screen)

    # 进入游戏主循环
    while True:
        # 刷新道具
        gf.gen_prop(prop_tank, prop_bullet, ai_setting, screen)
        # 监视键盘和鼠标事件
        gf.check_event(tank_1, tank_2, ai_setting, screen, tank_1.bullet, tank_2.bullet)
        # 更新坦克的位置设置
        gf.update_tanks(tank_1, bricks, tank_2, iron_bricks, prop_tank, prop_bullet, ai_setting, screen, 1)
        gf.update_tanks(tank_2, bricks, tank_1, iron_bricks, prop_tank, prop_bullet, ai_setting, screen, 2)
        # 更新子弹的位置设置
        gf.update_bullets(tank_1.bullet, tank_2.bullet, tank_1, tank_2, bricks, iron_bricks, ai_setting, scoreboard)
        # 负责屏幕显示
        gf.update_screen(ai_setting, screen, tank_1, tank_2, tank_1.bullet, tank_2.bullet, bricks, iron_bricks,
                         prop_tank, prop_bullet, scoreboard)
        if scoreboard.score_1 <= 0:
            gf.show_end_theme(screen, ai_setting, end_theme, 2)
            scoreboard.score_1 = scoreboard.score_2 = 3
            tank_1.reset(ai_setting)
            tank_2.reset(ai_setting)
            gf.gen_brick(bricks, ai_setting, screen)

        elif scoreboard.score_2 <= 0:
            gf.show_end_theme(screen, ai_setting, end_theme, 1)
            scoreboard.score_1 = scoreboard.score_2 = 3
            tank_1.reset(ai_setting)
            tank_2.reset(ai_setting)
            gf.gen_brick(bricks, ai_setting, screen)
Esempio n. 7
0
class Board :
    walls = [
            [0,0,0,0,0,0,0],
            [0,0,1,1,1,0,0],
            [0,0,0,0,0,0,0],
            [1,1,0,1,0,1,1],
            [0,0,0,0,0,0,0],
            [0,0,1,1,1,0,0],
            [0,0,0,0,0,0,0],
    ];
    eagles = [Eagle(3,0,Side.TOP), Eagle(3,6,Side.BOTTOM)];
    tanks = [Tank(2,0,Side.TOP), Tank(4,0,Side.TOP), Tank(2,6,Side.BOTTOM), Tank(4,6,Side.BOTTOM)]
    bullets = []
    
    def toLayeredMap(self, tank) :
        result = np.zeros((10,7,7));
        #walls
        result[0] = self.walls;
        #eagles
            #ally
            for eagle in eagles :
                result[tank.side.value 
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
Esempio n. 8
0
 def __set_tile(self, x, y, character):
     if character in ("1", "2"):
         if character == "1":
             self.player1 = Tank(1, x, y, self.tile_size, "down")
         else:
             self.player2 = Tank(2, x, y, self.tile_size, "up")
     else:
         tile_name = self.__char_to_tile(character)
         if tile_name != "":
             self.map[y * self.dim + x] = tile_name
Esempio n. 9
0
 def testShoot(self):
     game = Game(1, 13)
     tank = Tank(1, [2, 2], game)
     game.addTank(tank)
     self.assertEqual(tank.shootFlag, False)
     game.shoot(1)
     self.assertEqual(tank.shootFlag, True)
Esempio n. 10
0
 def testMoveTank(self):
     game = Game(1, 13)
     tank = Tank(1, [2, 2], game)
     game.addTank(tank)
     self.assertEqual(tank.moveDir, "")
     game.moveTank(1, "left")
     self.assertEqual(tank.moveDir, "left")
Esempio n. 11
0
    def __init__(self):
        self.state = 0

        # We have a plant:
        self.plant = Plant(strain="Tomato", ph=7)

        # Mixer to mix the components
        self.mixer = Mixer(step_pin=8, direction_pin=9, enable_pin=10)
        # PH measurements:
        self.ph = PHMeter(pin=1)
        # The main tank pumps:
        self.main_container_pump_in = Pump("Main container pump (in)", pin=4)
        self.main_container_pump_out = Pump("Main container pump (out)", pin=5)
        self.water_level = WaterLevel(pin=0)
        # The tanks with the components:
        self.main_tank = Tank(max_level=0.9,
                              water_level_sensor=self.water_level,
                              pump_in=self.main_container_pump_in,
                              pump_out=self.main_container_pump_out,
                              ph=self.ph,
                              mixer=self.mixer)
        # 4 Pumps for each of the containers:
        self.water_pump = Pump("Water pump", pin=0)
        self.acid_pump = Pump("Acid pump", pin=1)
        self.alkali_pump = Pump("Alkali pump", pin=2)
        self.fertilizer_pump = Pump("Fertilizer pump", pin=3)
        return
Esempio n. 12
0
 def testRemoveBullet(self):
     map = Game(1, 13)
     tank = Tank(1, [1, 2], map)
     bullet = tank.createBullet()
     self.assertNotEqual(tank.bullets, [])
     tank.removeBullet(bullet)
     self.assertEqual(tank.bullets, [])
Esempio n. 13
0
 def testMoveBullet(self):
     map = Game(1, 13)
     tank = Tank(1, [1, 2], map)
     bullet = tank.createBullet()
     self.assertEqual(bullet.currPos, [1, 1])
     tank.moveBullet(bullet)
     self.assertEqual(bullet.currPos, [1, 0])
Esempio n. 14
0
    def restartmatch(self):
        highscores = self.get_highscores()

        for tank in highscores:
            highscores[highscores.index(tank)] = tank.brain.weights

        num_of_entities = len(self.entitylist)  # Destroy everything
        for i in range(num_of_entities):
            entity = self.entitylist.pop(0)
            entity.destroy(self)

        for i in range(self.NUM_OF_TANKS):
            weightlist = []
            for weight in random.choice(
                    highscores):  # Take a brain from a random winner
                if random.random() * 100 <= self.MUTATION_RATE:
                    weight += 1 - (random.random() * 2)
                weightlist.append(weight)

            x = random.randint(0, self.surface.get_width())
            y = random.randint(0, self.surface.get_height())
            tank = Tank(self, x, y, weightlist)

        self.time = 0
        self.generation += 1

        text = open("data.evo", "w")
        pickle.dump([self.generation] + highscores, text)
        text.close()
Esempio n. 15
0
 def add_tank(self, sprite_pos, x, y, angle, max_ad, mag_size, start_ammo,
              player_type):
     tank = Tank(sprite_pos, x, y, angle, max_ad, mag_size, start_ammo,
                 player_type, self.tanks)
     if player_type == Enums.PlayerType.PLAYER1:
         self.player1_tank = tank
     self.tanks.append(tank)
Esempio n. 16
0
 def __init__(self,
              tank_init=[1, 1],
              injector_init=[1, 1],
              cc_init=[1, 1],
              nozzle_init=[1, 1]):
     self.Tank = Tank(tank_init)
     self.Injector = Injector(injector_init)
     self.cc = CombustionChamber(cc_init)
Esempio n. 17
0
 def testBonus(self):
     map = Game(1, 13)
     tank = Tank(1, [1, 2], map)
     self.assertEqual(tank.bonuses, [])
     bonus = Bonus(0, [3, 3])
     tank.addBonus(bonus)
     self.assertNotEqual(tank.bonuses, [])
     tank.removeBonus(bonus)
     self.assertEqual(tank.bonuses, [])
Esempio n. 18
0
 def testUpgradeTank(self):
     map = Game(1, 13)
     tank = Tank(1, [2, 3], map)
     bonus = VestBonus(0, [2, 2])
     self.assertEqual(tank.getMaxBullets(), 1)
     bonus.upgradeTank(tank)
     self.assertEqual(tank.getMaxBullets(), 2)
     bonus.downgradeTank(tank)
     self.assertEqual(tank.getMaxBullets(), 1)
Esempio n. 19
0
 def test_create_tank(self):
     """Should be able to define position and orientation as list or tuple
     or array and all numeric types should be converted to floats."""
     for n in [0, 0.]:
         for m in [[n, n], (n, n), np.array([n, n])]:
             msg = 'Failed to properly interpret a {} of {}s.'.format(type(m), type(n))
             T = Tank('LaserTankController', (0, 0, 0), m, m)
             self.assertTrue(np.all(T.position == np.array([0., 0.])), msg)
             self.assertTrue(np.all(T.orientation == np.array([0., 0.])), msg)
Esempio n. 20
0
def start_as_host(sock):
    resX = 800
    resY = 600
    pygame.display.init()
    pygame.font.init()
    screen = pygame.display.set_mode((resX, resY))
    pygame.display.set_caption("HOST")
    color_t1 = (100, 60, 60)
    color_t2 = (60, 100, 100)
    color_l = (80, 180, 10)
    land = Land(screen, color_l, resX, resY)
    tank1 = Tank(screen, color_t1, land=land, weapon_list=load_weapons())
    tank2 = Tank(screen, color_t2, land=land, weapon_list=load_weapons())
    tank2.angle = 180
    sock.send((str(resX) + ";" + str(resY) + ";" + str(land.color) + ";" +
               str(land.road_map) + ";" + str(color_t1) + ";" + str(color_t2) +
               "$").encode('utf8'))
    player1 = Player(tank1, land, screen, tank2)
    player2 = Player(tank2, land, screen, tank1)
    return player1, player2
Esempio n. 21
0
 def testGetTank(self):
     game = Game(1, 13)
     tank = Tank(1, [2, 2], game)
     self.assertNotEqual(game.tanks, [])
     game.removeTank(game.getTank(0))
     self.assertEqual(game.tanks, [])
     game.addTank(tank)
     self.assertNotEqual(game.tanks, [])
     self.assertEqual(game.getTank(tank.id), tank)
     game.removeTank(tank)
     self.assertEqual(game.tanks, [])
Esempio n. 22
0
 def spawnUnit(self, unitType, x, y):
     if self.isBase:
         if unitType == 2:
             unit = Infantry(x, y)
         elif unitType == 3:
             unit = Tank(x, y)
         else:
             unit = Helicopter(x, y)
     else:
         unit = Infantry(x, y)
     return unit
Esempio n. 23
0
 def testAddBullet(self):
     game = Game(1, 13)
     tank = Tank(1, [2, 2], game)
     game.addTank(tank)
     self.assertEqual(tank.bullets, [])
     bullet = tank.createBullet()
     self.assertNotEqual(tank.bullets, [])
     self.assertEqual(game.bullets, [])
     game.addBullet(bullet)
     self.assertNotEqual(game.bullets, [])
     game.removeBullet(bullet)
     self.assertEqual(game.bullets, [])
     self.assertEqual(tank.bullets, [])
Esempio n. 24
0
 def newRound(self, enemyCount):
     self.enemies.clear()
     self.terrain = Terrain(self.canvasWidth, self.canvasHeight, self)
     self.terrain.genMaze(0, 0)
     for i in range(enemyCount):
         self.enemies.append(
             Tank(
                 Tank.newTankPos(self.terrain, self.canvasWidth,
                                 self.canvasHeight), self))
     self.player = self.newPlayer()
     self.playerClonePos = self.player.pos.copy()
     self.roundCount = enemyCount
     self.score += self.roundCount
Esempio n. 25
0
 def loadNextLevel(self):
     """Loads the next lexel, creates player and Bonus and Enemy Spawners"""
     self.loadMap(self.id + 1, 13)
     self.notifyMapId()
     self.notifyUpdateMap()
     self.playerTank = Tank(0, self.playerPos, self)
     self.tanks.append(self.playerTank)
     self.notifyAddTank(self.playerTank)
     self.timeToNextBonus = 5
     self.currentBonusId = 0
     self.bonusSpawner = BonusSpawner(self, self.bonusSpawnTime)
     self.enemySpawner = EnemySpawner(self, self.enemySpawnTime)
     self.bulletsToRemove = []
     self.tanksToRemove = []
Esempio n. 26
0
 def process(self):
     """Method checks wether the timer to spawn is equal to 0. If not then it decrements the timer.
     Otherwise it checks if the number of enemies has not exceeded the maximum number,
     if not a new enemy is added to the map and the timer resets."""
     if(self.spawnTimer == 0):
         if(len(self.map.tanks) < self.map.maxNoOfEnemies + 1 and len(self.map.tanks) < self.map.enemiesToKill + 1):
             tank = Tank(self.currTankId,
                         self.map.getFreeCoords(), self.map)
             self.currTankId += 1
             self.map.addTank(tank)
             self.map.tanks
             self.spawnTimer = self.timeToSpawn
         else:
             return
     else:
         self.spawnTimer -= 1
Esempio n. 27
0
    def __init__(self):
        # The order of initialisation here reflects the hierarchy we are using
        # For now, all properties are hard-coded, rather than inputs
        self.Tank = Tank()
        self.Injector = Injector()
        self.CombustionChamber = CombustionChamber()
        self.Nozzle = Nozzle()
        self.t = 0

        #self.T_tank = 0
        #self.rho_tank_liquid = 0
        self.T_cc = 0
        #self.T_post_comb = 0 #cp = combustion products
        self.P_cc = 0  #cp = combustion products

        self.m_dot_ox = 0
        self.m_dot_fuel = 0
        self.m_dot_choke = 0
Esempio n. 28
0
 def __init__(self, mapId, mapSize):
     """The constructor"""
     super(Game, self).__init__(mapId, mapSize)
     self.status = "stop"
     self.observers = []
     self.playerTank = Tank(0, self.playerPos, self)
     self.tanks.append(self.playerTank)
     self.avalMaps = []
     self.avalMaps.append(1)
     self.avalMaps.append(2)
     self.timeToNextBonus = 5
     self.currentBonusId = 0
     self.bonusSpawner = BonusSpawner(self, self.bonusSpawnTime)
     self.enemySpawner = EnemySpawner(self, self.enemySpawnTime)
     self.bulletsToRemove = []
     self.tanksToRemove = []
     self.points = 0
     self.gameOver = False
     self.gameWin = False
     self.botMovement = BotMovement(1)
Esempio n. 29
0
 def recive(self):
     while not self.event.is_set():
         data = self.clients.recv(1024)
         # logging.info(data)
         if data.strip() == b'quit':
             break
         # jsondata = '{}'.format(data.strip())
         # logging.info(jsondata)
         net_json_data = str(data.strip(), 'utf-8')
         jsonobj = None
         try:
             jsonobj = json.loads(net_json_data)
         except:
             logging.info("net_json_wrong")
         if (jsonobj):
             if (not self.tanks.get(jsonobj['id'])):
                 self.tanks[jsonobj['id']] = Tank(jsonobj['id'])
             self.tanks[jsonobj['id']].set_net_json(net_json_data)
             timestamp = int(datetime.timestamp(datetime.now()))
             self.tanks[jsonobj['id']].set_timestamp(timestamp)
Esempio n. 30
0
 def __init__(
     self,
     name,
     xPosition,
     yPosition,
     chassisTheta,
     turretTheta
 ):
     super(Player, self).__init__()
     self.name = name
     self.active = False
     self.player_pipe, self.tank_pipe = Pipe()
     self.game_pipe = None
     self.gameState = {}
     self.tank = Tank(
         self.tank_pipe,
         xPosition,
         yPosition,
         chassisTheta,
         turretTheta
     )