Exemple #1
0
def run_app():
    while HUD.execution_thread.is_alive():
        #Actualizo la hora cada 0.1 seg    
        t = time.localtime()
        #time_formated = f"{t.tm_year}/{t.tm_mon}/{t.tm_mday} - {t.tm_hour}:{t.tm_min}:{t.tm_sec}"
        time_formated = {
            "año": t.tm_year,
            "mes": t.tm_mon,
            "dia": t.tm_mday,
            "hora": t.tm_hour,
            "min": t.tm_min,
            "sec": t.tm_sec
        }
        print(time_formated)
        HUD.update_label(time_formated)

        #Actualizo el texto:
        #Para darle color a una linea debo agregar la key f"{key_origina}_color"
        time_formated = {
            "año": t.tm_year,
            "mes": t.tm_mon,
            "dia": t.tm_mday,
            "hora": t.tm_hour,
            "min": t.tm_min,
            "sec": t.tm_sec,
            "año_color": "green",
            "mes_color": "blue",
            "dia_color": "yellow",
            "hora_color": "red"
        }
        HUD.update_text(time_formated)
        time.sleep(1)
Exemple #2
0
    def __init__(self, gsm):
        self.gsm = gsm
        self.background = Background(
            os.path.join("res", "PlayState", "background.png"))
        self.camera = Camera(self)
        self.HUD = HUD(self.gsm)
        # Key handling
        self.leftKeyDown = False
        self.rightKeyDown = False
        self.upKeyDown = False

        self.spriteSheet = SpriteSheet(
            os.path.join("res", "PlayState", "Spritesheet.png"), 1)

        # Holds all the objects in the game
        self.allObjectList = pygame.sprite.Group()
        self.activeObjectList = pygame.sprite.Group()
        self.terrainList = pygame.sprite.Group()
        self.interactableList = pygame.sprite.Group()
        self.enemyList = pygame.sprite.Group()
        self.enemyAIList = pygame.sprite.Group()
        self.player = None

        self.level = currentLevel  # Sets the current level
        self.loadLevel(self.level)  # Loads the level
Exemple #3
0
    def __init__(self, world):
        #화면 크기
        self.width = 800
        self.height = 600
        #센서 종류
        self.actor_list = []
        self.extra_list = []
        self.extra_controller_list = []
        self.player = None
        self.camera_rgb = None
        self.camera_semseg = None
        self.lane_invasion_sensor = None
        self.collision_sensor = None
        self.gnss_sensor = None
        self.waypoint = None
        self.path = []

        self.world = world
        self.map = world.get_map()
        self.spectator = self.world.get_spectator()
        self.hud = HUD(self.width, self.height)
        self.waypoints = self.map.generate_waypoints(3.0)
        ## visualize all waypoints ##
        # for n, p in enumerate(self.waypoints):
        # if n>1000:
        #     break
        # world.debug.draw_string(p.transform.location, 'o', draw_shadow=True,
        #                         color=carla.Color(r=255, g=255, b=255), life_time=30)

        self.extra_num = 5
        self.control_mode = None

        self.restart()
        self.main()
Exemple #4
0
    def __init__(self, nw_tile, nh_tile):
        self.nw_tile = nw_tile  # Set number of tile in x
        self.nh_tile = nh_tile  # Set number of tile in y

        self.number_body = 3  # Set number of snake's body
        self.score = 0  # Set score of sanke

        self.db_save_size = 6  # Column size of data base
        self.id = 0  # index of database's column
        self.type = 1
        self.x = 2
        self.y = 3
        self.s = 4
        self.t = 5

        self.enemy_dict = {}  # Enemy snake dictionary
        self.client_state_dict = {
            'OK': 0,
            'notNStart': 1,
            'notNExit': 2
        }  # KList state of client
        self.client_state = self.client_state_dict[
            'notNStart']  # State of cleint
        self.play_state = False  # Playing state
        self.game_time = 0  # time of game

        self.tile_mng = TileManager(width, height, self.nw_tile,
                                    self.nh_tile)  # Set TileManager
        self.snake = Snake(1, 1, self.tile_mng, green, SNAKE,
                           raw_input("Enter : "),
                           self.number_body)  # Set my sanke
        self.apple = Apple(0, 0, self.tile_mng, red, 0)  # Set apple
        self.hud = HUD()  # Set HUD
    def __init__(self, world):
        #화면 크기
        n_iters = 100
        self.width = 800
        self.height = 600
        #센서 종류
        self.actor_list = []
        self.extra_list = []
        self.extra_list = []
        self.extra_controller_list = []
        self.extra_dl_list = []
        self.extra_dl_list = []
        self.player = None
        self.camera_rgb = None
        self.camera_semseg = None
        self.lane_invasion_sensor = None
        self.collision_sensor = None
        self.gnss_sensor = None
        self.waypoint = None
        self.path = []
        self.save_dir = None
        self.world = world
        self.map = world.get_map()
        self.spectator = self.world.get_spectator()
        self.hud = HUD(self.width, self.height)
        self.waypoints = self.map.generate_waypoints(3.0)
        self.lane_change_time = time.time()
        self.max_Lane_num = 4
        self.ego_Lane = 2
        self.agent = None
        self.controller = None
        self.is_first_time = True
        self.decision = None
        self.simul_time = time.time()
        self.accumulated_reward = 0
        self.end_point = 0
        self.ROI_length = 1000  #(meters)

        ## visualize all waypoints ##
        # for n, p in enumerate(self.waypoints):
        #     world.debug.draw_string(p.transform.location, 'o', draw_shadow=True,
        #                             color=carla.Color(r=255, g=255, b=255), life_time=999)

        settings = self.world.get_settings()
        # settings.no_rendering_mode = True
        # settings.synchronous_mode = True
        settings.fixed_delta_seconds = 0.02
        self.world.apply_settings(settings)
        self.extra_num = 30
        self.section = 0
        self.lane_distance_between_start = None
        self.lane_distance_between_end = None
        self.lane_change_point = None
        self.episode_start = None
        self.index = 0
        self.pre_max_Lane_num = self.max_Lane_num

        self.restart()
        self.main()
Exemple #6
0
def update_text(texto, type="json"):
    if type == "json":
        try:
            json_para_actualizar = json.loads(texto)
            HUD.update_text(json_para_actualizar)
            return 'ok. texto actualizado con json'
        except:
            return f'Hubo un error. Revisá que en la url estés usando comillas dobles (") en vez de simples (\'): {sys.exc_info()[0]}'

    if type == "text":
        HUD.update_text(texto)
        return 'ok. texto actualizado'

    return 'type no válido'
Exemple #7
0
    def __init__(self, gsm):
        self.gsm = gsm
        self.HUD = HUD(self.gsm)
        global currentLevel
        global highestLevelComplete

        # If you beat all the levels
        if highestLevelComplete == 5:
            self.gsm.setState(self.gsm.VICTORYSTATE)

        # Level Images
        self.levelImgRed = pygame.image.load(
            os.path.join("res", "MapState", "map level red.png"))
        self.levelImgRed = pygame.transform.scale(self.levelImgRed, (50, 50))

        self.levelImgBlue = pygame.image.load(
            os.path.join("res", "MapState", "map level blue.png"))
        self.levelImgBlue = pygame.transform.scale(self.levelImgBlue, (50, 50))

        self.levelImgGray = pygame.image.load(
            os.path.join("res", "MapState", "map level gray.png"))
        self.levelImgGray = pygame.transform.scale(self.levelImgGray, (50, 50))

        # Level Locations
        # Level1
        self.level1X = 100
        self.level1Y = 500

        # Level2
        self.level2X = 450
        self.level2Y = 425

        # Level 3
        self.level3X = 275
        self.level3Y = 325

        # Level 4
        self.level4X = 600
        self.level4Y = 250

        # Level 5
        self.level5X = 350
        self.level5Y = 125

        # Player boat (navigator)

        self.player = pygame.image.load(
            os.path.join("res", "MapState", "menu boat.png"))
        self.playerX = 90
        self.playerY = 450
def get_newgame():
    """returns the game scene"""

    scene = Scene()
    background_layer = BackgroundLayer()

    # model
    model = GameModel(background_layer)

    # controller
    ctrl = GameCtrl(model)

    # view
    hud = HUD()
    view = GameView(model, hud)

    # set controller in model
    model.set_controller(ctrl)

    # add controller
    scene.add(ctrl, z=1, name="controller")

    # add view
    scene.add(hud, z=3, name="hud")

    scene.add(background_layer, z=0, name="background")
    scene.add(view, z=2, name="view")

    return scene
    def __init__(self):
        #window setup
        pygame.display.set_caption('Necromonster')
        path = ['rec', 'misc', 'icon.png']
        os.path.sep.join(path)
        pygame.display.set_icon(pygame.image.load(os.path.sep.join(path)))
        #pygame.display.set_icon(pygame.image.load('rec\\misc\\icon.png'))
        self.main_path = os.getcwd()

        # initiate the clock and screen
        self.clock = pygame.time.Clock()
        self.last_tick = pygame.time.get_ticks()
        self.screen_res = [900, 650]
        self.screen = pygame.display.set_mode(self.screen_res, pygame.HWSURFACE, 32)
        self.DEBUG = 1

        #Init custom game classes
        self.Player = Player(self)
        self.Monsters = Monster(self)
        self.ItemHandler = Item(self)
        self.Invent = Invent(self)
        self.HUD = HUD(self)

        # load fonts, create font list
        self.text_list = []
        self.default_font = pygame.font.SysFont(None, 20)

        # get the map that you are on
        self.blit_list = mapLoader.load('home', self)

        self.Monsters.create('goop', [300, 300], 2, 'neutral')

        while 1:
            self.Loop()
Exemple #10
0
    def give_score(player: Player):
        last_player = HistoryKeeper.get_last("player")
        if last_player.x_coordinate > player.x_coordinate:
            last_player.x_coordinate = player.x_coordinate
            ScoreKeeper.current_distance -= VelocityCalculator.calc_distance(player.running_velocity)

        is_moving_right = player.x_coordinate > last_player.x_coordinate
        if is_moving_right or player.game_is_sidescrolling:
            last_player.x_coordinate = player.x_coordinate
            ScoreKeeper.current_distance += VelocityCalculator.calc_distance(player.running_velocity)

        if ScoreKeeper.current_distance > ScoreKeeper.distance_traveled:
            difference = ScoreKeeper.current_distance - ScoreKeeper.distance_traveled
            ScoreKeeper.score += difference / 10
            ScoreKeeper.distance_traveled = ScoreKeeper.current_distance

        HUD.show_score(ScoreKeeper.score // 1)
Exemple #11
0
    def __init__(self, proxy_map, startup_check=False):
        super(SpecificWorker, self).__init__(proxy_map)

        self.width = 1280
        self.height = 720

        pygame.init()
        pygame.font.init()

        self.display = pygame.display.set_mode(
            (self.width, self.height), pygame.HWSURFACE | pygame.DOUBLEBUF)

        self.camera_manager = CameraManager(self.width, self.height)
        self.gnss_sensor = GNSSSensor()
        self.imu_sensor = IMUSensor()
        self.hud = HUD(self.width, self.height, self.gnss_sensor,
                       self.imu_sensor)
        self.controller = None
        self.clock = pygame.time.Clock()

        data_to_save = {
            'control': [
                'Time', 'Throttle', 'Steer', 'Brake', 'Gear', 'Handbrake',
                'Reverse', 'Manualgear'
            ],
            'communication': ['Time', 'CommunicationTime']
        }
        self.logger = Logger(self.melexlogger_proxy, 'carlaRemoteControl',
                             data_to_save)
        self.logger_signal.connect(self.logger.publish_to_logger)

        self.Period = 0

        self.previousLat = None
        self.previousLong = None

        self.currentLat = None
        self.currentLong = None

        if startup_check:
            self.startup_check()
        else:
            self.timer.timeout.connect(self.compute)
            self.timer.start(self.Period)
 def _init_game(self):
     self.hud = HUD()
     self.entities = []
     self.spawn_player()
     self.exhaust = ParticleSpawner(
         self.player.pos.getCopy(),
         self.player.angle + math.pi,
         math.pi / 4, .01,
         ParticleFactory(speed=20, color=(255, 0, 0)),
         True)
     self.entities.append(self.exhaust)
    def TEST_createViewport(self,world,manager):

        scrollLoc = (0,0)
        viewportPos = (0,0)
        viewportSize = (1024,768)
        testViewport = Viewport(world,manager,scrollLoc,viewportPos,viewportSize,self.clientID)
        self.viewport = testViewport

        self.hud=HUD(manager,self.clientID)
        self.viewport.hud=self.hud
        self.hud.viewport=self.viewport
Exemple #14
0
def init():
    #game
    pygame.init()
    screen = pygame.display.set_mode((val.width + val.l_width, val.height))
    clock = pygame.time.Clock()
    pygame.font.init()
    pygame.display.set_caption(val.title)
    font = pygame.font.SysFont('Comic Sans MS', 20)
    #HUD
    hud = HUD(font, pygame, screen)
    return (screen, pygame, clock, font, hud)
Exemple #15
0
    def __init__(self, width, height):
        self.windowWidth = width
        self.windowHeight = height
        self.widthNumber = 0
        self.heightNumber = 0

        self.map = []  # Contains all the cells that make up the map
        self.path = [
        ]  # Ordered list of cells that make up the path for the enemies
        self.walls = []  # List containing all the cells that make up the walls
        self.enemies = []  # List of all enemies currently on the field
        self.level = 0  # Incrementing level variable, increases difficulty
        self.towers = []  # List of all towers currently on the map
        self.bullets = []  # List of all bullets

        self.start = 0
        self.end = 0
        self.startCell = None
        self.endCell = None

        self.hud = HUD(width, height)
    def game_is_paused():
        pause_clicked = HUD.pause_clicked()
        # TODO can_pause? Isn't this used to pause and unpause?
        can_pause = not GameRunner.pause_is_held_down and pause_clicked

        if pause_clicked:
            GameRunner.pause_is_held_down = True

        else:
            GameRunner.pause_is_held_down = False
        if can_pause:
            GameRunner.game_paused = not GameRunner.game_paused
        return GameRunner.game_paused
Exemple #17
0
def get_newgame():
    scene = Scene()
    model = GameModel()
    controller = GameController(model)
    # 视图
    hud = HUD()
    view = GameView(model, hud)

    # 模型中的控制器
    model.set_controller(controller)

    # 添加控制器
    scene.add(controller, z=1, name="controller")
    scene.add(hud, z=3, name="hud")
    scene.add(view, z=2, name="view")

    return scene
Exemple #18
0
def get_newgame():
    scene = Scene()
    model = GameModel()
    controller = GameController(model)
    # view
    hud = HUD()
    view = GameView(model, hud)

    # set controller in model
    model.set_controller(controller)

    # add controller
    scene.add(controller, z=1, name="controller")
    scene.add(hud, z=3, name="hud")
    scene.add(view, z=2, name="view")

    return scene
    def __init__(self):
        #window setup
        pygame.display.set_caption('Necromonster')
        pygame.display.set_icon(pygame.image.load(os.path.join('rec', 'misc', 'icon.png')))
        self.main_path = os.getcwd()

        # initiate the clock and screen
        self.clock = pygame.time.Clock()
        self.last_tick = pygame.time.get_ticks()
        self.screen_res = [900, 650]
        self.center_point = [470., 350.]
        self.screen = pygame.display.set_mode(self.screen_res, pygame.HWSURFACE, 32)

        #DEBUG values
        self.DEBUG = 1
        self.RECT_DEBUG = 0

        #Init custom game classe(s)
        self.EntityHandler = EntityHandler(self)
        self.Scheduler = Schedule(self)
        self.Projectile = Projectile
        self.Monster = Monster
        self.Item = Item
        self.Invent = Invent(self)
        self.Weapon = Weapon
        self.Garment = Garment
        self.Player = Player(self)
        self.HUD = HUD(self)

        # Init entity manager vars
        self.entities = []

        # load fonts, create font list
        self.text_list = []
        self.default_font = pygame.font.SysFont(None, 20)

        # get the map that you are on
        self.blit_list = mapLoader.load('home', self)

        self.Item(self, 'Mythril', [350, 400], world=1)

        while 1:
            self.Loop()
Exemple #20
0
def get_newgame(level = 1):
    status.score = 0
    status.level = level

    scene = Scene()
    model = GameModel(hud_offset=director.window.get_size()[0]-800) #MAGIC original width
    controller = GameController(model)
    # view
    hud = HUD()
    view = GameView(model, hud)

    # set controller in model
    model.set_controller(controller)

    # add controller
    scene.add(controller, z=1, name="controller")
    scene.add(hud, z=3, name="hud")
    scene.add(view, z=2, name="view")

    return scene
Exemple #21
0
    def __init__(self, window, scene, menu):
        self.u = (2./3, -1./3.5)
        self.v = (-2./3, -1./3.5)
        self.w = (0, -15)

        self._window = window
        self._scene = scene
        self._hud = HUD(self)
        self._grid = Grid(self)
        self._players = pygame.sprite.Group()
        player1 = PlayerSprite(scene.getPlayer(0), menu)
        self._playerG1 = pygame.sprite.Group()
        self._playerG1.add(player1)
        player2 = PlayerSprite(scene.getPlayer(1), menu)
        self._playerG2 = pygame.sprite.Group()
        self._playerG2.add(player2)
        self._players.add(player1)
        self._players.add(player2)
        self._shadows = pygame.sprite.Group()
        self._shadows.add(ShadowSprite(scene.getPlayer(0)))
        self._shadows.add(ShadowSprite(scene.getPlayer(1)))
        self._weaponGroup = pygame.sprite.Group()
        self._weaponList = [WeaponSprite(scene.getPlayer(0).weapon()),
                WeaponSprite(scene.getPlayer(1).weapon())]
    def draw_everything(player: Player, enemies, platforms, game_is_paused):
        player.draw()
        player.item.render()
        player.shield.render()
        for x in range(len(enemies)):
            enemy = enemies[x]
            enemy.name = f"enemy{x}"
            HistoryKeeper.add(enemy, enemy.name, True)

            if enemy.is_within_screen and enemy.current_health > 0:
                enemy.player = player
                enemy.draw()
                enemy.item.render()
                enemy.shield.render()
                HUD.show_enemy_health(enemy)

            if HistoryKeeper.get_last(
                    enemy.name
            ).current_health > 0 and enemy.current_health <= 0:
                UtilityFunctions.draw_font("+100",
                                           pygame.font.Font(
                                               'freesansbold.ttf', 10),
                                           x_coordinate=enemy.x_coordinate,
                                           y_coordinate=enemy.y_coordinate)
                ScoreKeeper.score += 100

        for x in range(len(platforms)):
            platform = platforms[x]
            if platform.is_within_screen:
                platform.name = f"platform{x}"
                HistoryKeeper.add(platform, platform.name, True)
                platform.draw()

        HistoryKeeper.add(player, "player", True)
        HUD.render_pause_button(game_is_paused)
        HUD.show_character_health(player)
        ScoreKeeper.give_score(player)
Exemple #23
0
class PlayState():
    def __init__(self, gsm):
        self.gsm = gsm
        self.background = Background(
            os.path.join("res", "PlayState", "background.png"))
        self.camera = Camera(self)
        self.HUD = HUD(self.gsm)
        # Key handling
        self.leftKeyDown = False
        self.rightKeyDown = False
        self.upKeyDown = False

        self.spriteSheet = SpriteSheet(
            os.path.join("res", "PlayState", "Spritesheet.png"), 1)

        # Holds all the objects in the game
        self.allObjectList = pygame.sprite.Group()
        self.activeObjectList = pygame.sprite.Group()
        self.terrainList = pygame.sprite.Group()
        self.interactableList = pygame.sprite.Group()
        self.enemyList = pygame.sprite.Group()
        self.enemyAIList = pygame.sprite.Group()
        self.player = None

        self.level = currentLevel  # Sets the current level
        self.loadLevel(self.level)  # Loads the level

    def update(self):
        # Fixes the bug where if you instantly switch directions you will stop moving

        if self.leftKeyDown:
            self.player.moveLeft()
        if self.rightKeyDown:
            self.player.moveRight()
        self.camera.update(self.player)
        self.HUD.update()

        # PERFORMANCE FIX
        # This block  makes it so that only the objects that are within a  certain range of the player will it update it and draw it.
        # Runs through all the objects in the game and if it is within the range of the camera then add it to the active objects list.
        for object in self.allObjectList:
            if object.rect.right > -160 and object.rect.left < 960:
                self.activeObjectList.add(object)
            else:
                self.activeObjectList.remove(object)
        self.activeObjectList.update()  # Updates all the active objects
        self.background.update()

    def draw(self, window):
        window.fill(Color.CYAN)
        self.background.draw(window)
        self.activeObjectList.draw(window)  # Draws all the active objects
        self.HUD.draw(window)

    def keyHandler(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    self.leftKeyDown = True

                if event.key == pygame.K_RIGHT:
                    self.rightKeyDown = True

                if event.key == pygame.K_UP:
                    self.player.jump(9.5)

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT:
                    self.player.stopMoving()
                    self.leftKeyDown = False

                if event.key == pygame.K_RIGHT:
                    self.player.stopMoving()
                    self.rightKeyDown = False

    def loadLevel(
        self, level
    ):  # Reads the pixels of an image for their RGB Values and depending on these values, create a object at that position
        if level == 1:
            mapData = Image.open(
                os.path.join("res", "PlayState",
                             "Level1Map(sand).png"))  # Loads level1
        elif level == 2:
            mapData = Image.open(
                os.path.join("res", "PlayState", "Level2Map(sand).png"))
        elif level == 3:
            mapData = Image.open(
                os.path.join("res", "PlayState", "Level3Map.png"))
        elif level == 4:
            mapData = Image.open(
                os.path.join("res", "PlayState", "Level4Map.png"))
        elif level == 5:
            mapData = Image.open(
                os.path.join("res", "PlayState", "Level5Map.png"))
        mapWidth, mapHeight = mapData.size  # Gets the width and height of the image

        print("WIDTH: " + str(mapWidth) + " HEIGHT: " +
              str(mapHeight))  # For debugging
        for x in range(mapWidth):  # Runs through all the colomns
            for y in range(mapHeight):  # Runs through all the rows

                currentPixel = mapData.getpixel((x, y))
                red = currentPixel[0]  # RED VALUE
                green = currentPixel[1]  # GREEN VALUE
                blue = currentPixel[2]  # BLUE VALUE
                alpha = currentPixel[3]  # ALPHA VALUE

                # Checks for player spawner
                if red == 255 and green == 0 and blue == 255 and alpha == 255:
                    self.player = Player(
                        x * 32,
                        y * 32,
                        self,
                        self.gsm,
                        self.spriteSheet,
                    )
                    self.allObjectList.add(self.player)

                # Check for Grass blocks
                if red == 0 and green == 255 and blue == 0 and alpha == 255:
                    self.terrainList.add(
                        Grass(x * 32, y * 32, self.spriteSheet))

                # Checks for dirt blocks
                if red == 222 and green == 144 and blue == 61 and alpha == 255:
                    self.terrainList.add(Dirt(x * 32, y * 32,
                                              self.spriteSheet))

                # Checks for sand blocks
                if red == 243 and green == 225 and blue == 179 and alpha == 255:
                    self.terrainList.add(Sand(x * 32, y * 32,
                                              self.spriteSheet))

                # Check for coin blocks
                if red == 255 and green == 255 and blue == 0 and alpha == 255:
                    self.interactableList.add(
                        Coin(x * 32, y * 32, self.spriteSheet))

                # Checks for enemy AI detection
                if red == 0 and green == 0 and blue == 0 and alpha == 255:
                    self.enemyAIList.add(EnemyAIBox(x * 32, y * 32, self))

                # Checks for Crab enemy
                if red == 255 and green == 0 and blue == 0 and alpha == 255:
                    self.enemyList.add(
                        Crab(x * 32, y * 32, self, self.spriteSheet))

                # Checks for map piece
                if red == 0 and green == 0 and blue == 255 and alpha == 255:
                    self.interactableList.add(
                        Map(x * 32, y * 32, self.spriteSheet))

                if red == 0 and green == 255 and blue == 255 and alpha == 255:
                    self.interactableList.add(
                        Chest(x * 32, y * 32, self, self.spriteSheet))
                    print("Chest addded")

        # Adds all the groups into one master group
        self.allObjectList.add(self.terrainList)
        self.allObjectList.add(self.interactableList)
        self.allObjectList.add(self.enemyList)
        self.allObjectList.add(self.enemyAIList)

    def removeObject(self, object):
        # Removes a game object from the game
        self.allObjectList.remove(object)
        self.activeObjectList.remove(object)

    def nextLevel(self):
        global highestLevelComplete
        global currentLevel

        # This makes it so that if you play a level you already beat, it doesn't unlock a new level
        if currentLevel > highestLevelComplete:
            highestLevelComplete += 1

    def reset(self):
        global highestLevelComplete
        global currentLevel

        highestLevelComplete = 0
        currentLevel = 1
        self.HUD.reset()
class StateManager(object):
    def __init__(self):
        self.quit = False
        self._init_window()
        self._init_game()
        self.mode = "SPLASH"
        # Prevent bouncing on switching game modes
        self.debounce_timer = DEBOUNCE 
        

# Create a window for the game
    def _init_window(self):
# Window object represents the game's window
        self.window = pyglet.window.Window(WIDTH, HEIGHT)
# Keys holds a handler that keeps track of keyboard state, part of pyglet
        self.keys = pyglet.window.key.KeyStateHandler()
        self.window.push_handlers(self.keys)


    # Stage the game or return it to its initial state
    def _init_game(self):
        self.hud = HUD()
        self.entities = []
        self.spawn_player()
        self.exhaust = ParticleSpawner(
            self.player.pos.getCopy(),
            self.player.angle + math.pi,
            math.pi / 4, .01,
            ParticleFactory(speed=20, color=(255, 0, 0)),
            True)
        self.entities.append(self.exhaust)

    #Create a new instance of the Player class at the center of the screen
    def spawn_player(self):
        self.player = Player(Vect2(x=self.window.width/2, y=self.window.height/2))
        self.entities.append(self.player)

    # This function runs when the look is in game mode, and has all the updating/drawing logic
    def game_loop(self, dt):
        #Clear frame before looping
        self.window.clear()

        #print(pyglet.gl.get_current_context())
        # On a proper engine the controller would probably be its own class.
        # That level of abstraction makes it easier to use keyboards, mice, and
        # other controllers the user may have
        controller = {
            'acc': self.keys[key.W],
            'left': self.keys[key.A],
            'right': self.keys[key.D],
            'fire': self.keys[key.SPACE],
            'quit': self.keys[key.ESCAPE],
            'pause': self.keys[key.P]
        }
        self.quit = controller['quit']
        if controller['pause'] and self.debounce_timer <= 0:
            self.mode = "PAUSE"
            self.debounce_timer = DEBOUNCE
        self.player.input(controller)
        #turn on thrust effect if ship is accelerating
        self.exhaust.active = controller['acc']
        self.exhaust.angle = (self.player.angle + math.pi)
        self.exhaust.pos = self.player.pos.getCopy()

        self.spawn_bullets()
        self.spawn_asteroids()
        self.detect_collisions()

        for e in self.entities:
            e.update(dt)

        #for e in self.entities:
        #    print(e)
        batch = pyglet.graphics.Batch()
        for e in self.entities:
            # batch.add expects a series of arguments
            # most easily delivered as a tuple.
            # * is the untuple argument.
            batch.add(*e.draw())

        # Filter out any dead objects
        self.entities[:] = [e for e in self.entities if e.isAlive()]
        # Draw objects to the frame
        batch.draw()
        self.hud.drawHUD()

    # Determine if a bullet should be spawned, and then spawns a bullet
    def spawn_bullets(self):
        if self.player.isFiring():
                self.entities.append(
                    Bullet(
                        self.player.pos.getCopy(), 
                        self.player.angle
                    )
                )

    # Maintain a minimum asteroid population
    def spawn_asteroids(self):
        # Asteroid Spawning
        asteroids = [e for e in self.entities if isinstance(e, Asteroid)]
        if len(asteroids) < targetNo:
                newAsteroid = Asteroid(3, Vect2(0, 0))
                self.entities.append(newAsteroid)

    # This function determines if any objects are colliding in a meaningful way for the game 
    def detect_collisions(self):
        asteroids = [e for e in self.entities if isinstance(e, Asteroid)]
        for asteroid in asteroids:
                if self.player.overlaps(asteroid.hit_radius, asteroid.pos.getCopy()):
                        self.player.kill()
                        # Check if player is actually dead, it may be in invuln
                        # period
                        if (self.player.isAlive() != True):
                            if (self.hud.has_lives()):
                                self.spawn_player()
                                self.hud.kill()
                            else: self.mode = "GAMEOVER"
        # Process asteroid/bullet collisions
        for bullet in [e for e in self.entities if isinstance(e, Bullet)]:
                for asteroid in asteroids:
                        if bullet.overlaps(
                                asteroid.hit_radius,
                                asteroid.pos.getCopy()):
                                asteroid.kill()
                                self.entities.append(
                                    AsteroidDebris(
                                        asteroid.pos.getCopy()))
                                if asteroid.size > 1:
                                        # add two baby asteroids!
                                        self.entities.append(
                                                   Asteroid(
                                                       asteroid.size - 1,
                                                       asteroid.pos.getCopy()))
                                        self.entities.append(
                                                   Asteroid(
                                                       asteroid.size - 1,
                                                       asteroid.pos.getCopy()))
                                # Remove bullet
                                bullet.kill()
                                # Log the points
                                self.hud.hit()

    # Inform the main function if the player requested to quit
    def is_quit(self):
        return self.quit

    # Dispatch loop to the right function
    def loop(self, dt):
        if self.debounce_timer > 0:
            self.debounce_timer -= dt
        if self.mode == "GAME":
            self.game_loop(dt)
        elif self.mode == "PAUSE":
            self.pause_loop(dt)
        elif self.mode == "SPLASH":
            self.splash_loop(dt)
        elif self.mode == "GAMEOVER":
            self.game_over_loop(dt)
        else:
            self.quit == True
            print("Error: Debug: state.mode == Invalid state!")
        

    # Pause screen
    def pause_loop(self, dt):
        self.window.clear()
        label = pyglet.text.Label("Game Paused: Press p to unpause, or ESC to quit", font_size=24, 
            x=WIDTH//2, y=HEIGHT//2, anchor_x = 'center', anchor_y = 'center')
        label.draw()
        if self.keys[key.P] and self.debounce_timer <= 0:
            self.mode = "GAME"
            self.debounce_timer = DEBOUNCE
        elif self.keys[key.ESCAPE]: self.quit = True

# Splash screen
    def splash_loop(self, dt):
        label = pyglet.text.Label("Rocks in Space: Press s to start", font_size=38, 
            x=WIDTH//2, y=HEIGHT//2, anchor_x = 'center', anchor_y = 'center')
        label.draw()
        if self.keys[key.S]: self.mode = "GAME"
        elif self.keys[key.ESCAPE]: self.quit = True

# Game over screen
    def game_over_loop(self, dt):
        self.window.clear()
        label = pyglet.text.Label("Game over! Press S to restart, or ESC to quit", font_size=24, 
            x=WIDTH//2, y=HEIGHT//2, anchor_x = 'center', anchor_y = 'center')
        label.draw()
        if self.keys[key.S]:
            self.mode = "GAME"
            self._init_game()
        elif self.keys[key.ESCAPE]: self.quit = True
Exemple #25
0
class MapState:
    global amountOfLevels
    global highestLevelComplete
    global currentLevel
    amountOfLevels = 5
    highestLevelComplete = 0
    currentLevel = 4

    def __init__(self, gsm):
        self.gsm = gsm
        self.HUD = HUD(self.gsm)
        global currentLevel
        global highestLevelComplete

        # If you beat all the levels
        if highestLevelComplete == 5:
            self.gsm.setState(self.gsm.VICTORYSTATE)

        # Level Images
        self.levelImgRed = pygame.image.load(
            os.path.join("res", "MapState", "map level red.png"))
        self.levelImgRed = pygame.transform.scale(self.levelImgRed, (50, 50))

        self.levelImgBlue = pygame.image.load(
            os.path.join("res", "MapState", "map level blue.png"))
        self.levelImgBlue = pygame.transform.scale(self.levelImgBlue, (50, 50))

        self.levelImgGray = pygame.image.load(
            os.path.join("res", "MapState", "map level gray.png"))
        self.levelImgGray = pygame.transform.scale(self.levelImgGray, (50, 50))

        # Level Locations
        # Level1
        self.level1X = 100
        self.level1Y = 500

        # Level2
        self.level2X = 450
        self.level2Y = 425

        # Level 3
        self.level3X = 275
        self.level3Y = 325

        # Level 4
        self.level4X = 600
        self.level4Y = 250

        # Level 5
        self.level5X = 350
        self.level5Y = 125

        # Player boat (navigator)

        self.player = pygame.image.load(
            os.path.join("res", "MapState", "menu boat.png"))
        self.playerX = 90
        self.playerY = 450

    def update(self):
        if currentLevel == 1:
            self.playerX = self.level1X
            self.playerY = self.level1Y
        elif currentLevel == 2:
            self.playerX = self.level2X
            self.playerY = self.level2Y
        elif currentLevel == 3:
            self.playerX = self.level3X
            self.playerY = self.level3Y
        elif currentLevel == 4:
            self.playerX = self.level4X
            self.playerY = self.level4Y
        elif currentLevel == 5:
            self.playerX = self.level5X
            self.playerY = self.level5Y

    def draw(self, window):

        window.fill(Color.TEAL)

        # Levels
        # Level 1
        if highestLevelComplete == 0:  # if you have not completed any level
            window.blit(self.levelImgRed, (self.level1X, self.level1Y))
        elif highestLevelComplete > 0:  # if you have the level
            window.blit(self.levelImgBlue, (self.level1X, self.level1Y))
        else:
            window.blit(self.levelImgGray, (self.level1X, self.level1Y))

        # Level 2
        if highestLevelComplete == 1:  # if you have beat level 1
            window.blit(self.levelImgRed, (self.level2X, self.level2Y))
        elif highestLevelComplete > 1:  # if you have beat the level
            window.blit(self.levelImgBlue, (self.level2X, self.level2Y))
        else:
            window.blit(self.levelImgGray, (self.level2X, self.level2Y))

        # Level 3
        if highestLevelComplete == 2:  # if you have beat level 2
            window.blit(self.levelImgRed, (self.level3X, self.level3Y))
        elif highestLevelComplete > 2:  # if you have beat the level
            window.blit(self.levelImgBlue, (self.level3X, self.level3Y))
        else:
            window.blit(self.levelImgGray, (self.level3X, self.level3Y))

        # Level 4
        if highestLevelComplete == 3:  # if you have beat level 3
            window.blit(self.levelImgRed, (self.level4X, self.level4Y))
        elif highestLevelComplete > 2:  # if you have beat the level
            window.blit(self.levelImgBlue, (self.level4X, self.level4Y))
        else:
            window.blit(self.levelImgGray, (self.level4X, self.level4Y))

        # Level 5
        if highestLevelComplete == 4:  # if you have beat level 4
            window.blit(self.levelImgRed, (self.level5X, self.level5Y))
        elif highestLevelComplete > 3:  # if you have beat the level
            window.blit(self.levelImgBlue, (self.level5X, self.level5Y))
        else:
            window.blit(self.levelImgGray, (self.level5X, self.level5Y))

        # Draw Lines
        pygame.draw.line(window, Color.RED,
                         (self.level1X + 50, self.level1Y + 25),
                         (self.level2X, self.level2Y + 25))
        pygame.draw.line(window, Color.RED, (self.level2X, self.level2Y + 25),
                         (self.level3X + 50, self.level3Y + 25))
        pygame.draw.line(window, Color.RED,
                         (self.level3X + 50, self.level3Y + 25),
                         (self.level4X, self.level4Y + 25))
        pygame.draw.line(window, Color.RED, (self.level4X, self.level4Y + 25),
                         (self.level5X + 50, self.level5Y + 25))

        # Player
        window.blit(self.player, (self.playerX, self.playerY))
        self.HUD.draw(window)

    def keyHandler(self):
        for event in pygame.event.get():

            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

            if event.type == pygame.KEYDOWN:

                if event.key == pygame.K_ESCAPE:
                    self.gsm.setState(self.gsm.MENUSTATE)

                if event.key == pygame.K_UP:
                    self.moveUp()

                if event.key == pygame.K_DOWN:
                    self.moveDown()

                if event.key == pygame.K_RETURN:
                    self.gsm.setState(self.gsm.PLAYSTATE)

    def moveUp(self):
        global currentLevel
        if currentLevel <= highestLevelComplete:
            currentLevel += 1

    def moveDown(self):
        global currentLevel
        if currentLevel > 1:
            currentLevel -= 1

    def nextLevel(self):
        global highestLevelComplete
        highestLevelComplete += 1
Exemple #26
0
class CarlaEnv():
    pygame.init()
    font = pygame.font.init()

    def __init__(self, world):
        #화면 크기
        self.width = 800
        self.height = 600
        #센서 종류
        self.actor_list = []
        self.extra_list = []
        self.extra_controller_list = []
        self.player = None
        self.camera_rgb = None
        self.camera_semseg = None
        self.lane_invasion_sensor = None
        self.collision_sensor = None
        self.gnss_sensor = None
        self.waypoint = None
        self.path = []

        self.world = world
        self.map = world.get_map()
        self.spectator = self.world.get_spectator()
        self.hud = HUD(self.width, self.height)
        self.waypoints = self.map.generate_waypoints(3.0)
        ## visualize all waypoints ##
        # for n, p in enumerate(self.waypoints):
        # if n>1000:
        #     break
        # world.debug.draw_string(p.transform.location, 'o', draw_shadow=True,
        #                         color=carla.Color(r=255, g=255, b=255), life_time=30)

        self.extra_num = 5
        self.control_mode = None

        self.restart()
        self.main()

    def restart(self):
        blueprint_library = world.get_blueprint_library()
        # start_pose = random.choice(self.map.get_spawn_points())
        start_pose = self.map.get_spawn_points()[102]

        ##spawn points 시뮬레이션 상 출력##
        # print(start_pose)
        # for n, x in enumerate(self.map.get_spawn_points()):
        #     world.debug.draw_string(x.location, 'o', draw_shadow=True,
        #                             color=carla.Color(r=0, g=255, b=255), life_time=30)

        # self.load_traj()

        self.waypoint = self.map.get_waypoint(start_pose.location,
                                              lane_type=carla.LaneType.Driving)
        # print(self.waypoint.transform)
        ## Ego vehicle의 global Route 출력##
        # world.debug.draw_string(self.waypoint.transform.location, 'o', draw_shadow=True,
        #                         color=carla.Color(r=0, g=255, b=255), life_time=100)

        # print(start_pose)
        # print(self.waypoint.transform)

        # self.controller = MPCController.Controller

        self.spectator.set_transform(
            carla.Transform(start_pose.location + carla.Location(z=50),
                            carla.Rotation(pitch=-90)))

        self.player = world.spawn_actor(
            random.choice(blueprint_library.filter('vehicle.bmw.grandtourer')),
            start_pose)
        self.actor_list.append(self.player)
        # vehicle.set_simulate_physics(False)

        self.camera_rgb = RGBSensor(self.player, self.hud)
        self.actor_list.append(self.camera_rgb.sensor)

        self.camera_semseg = SegmentationCamera(self.player, self.hud)
        self.actor_list.append(self.camera_semseg.sensor)

        self.collision_sensor = CollisionSensor(self.player,
                                                self.hud)  # 충돌 여부 판단하는 센서
        self.actor_list.append(self.collision_sensor.sensor)

        self.lane_invasion_sensor = LaneInvasionSensor(
            self.player, self.hud)  # lane 침입 여부 확인하는 센서
        self.actor_list.append(self.lane_invasion_sensor.sensor)

        self.gnss_sensor = GnssSensor(self.player)
        self.actor_list.append(self.gnss_sensor.sensor)

        # --------------
        # Spawn Surrounding vehicles
        # --------------

        # spawn_points = carla.Transform(start_pose.location+carla.Location(0,10,0),start_pose.rotation)  #world.get_map().get_spawn_points()
        # spawn_points = self.map.get_waypoint(spawn_points.location,lane_type=carla.LaneType.Driving)
        spawn_points = world.get_map().get_spawn_points()[85:]
        number_of_spawn_points = len(
            world.get_map().get_spawn_points())  #len(spawn_points)

        if self.extra_num <= number_of_spawn_points:
            # random.shuffle(spawn_points)
            pass
        elif self.extra_num > number_of_spawn_points:
            msg = 'requested %d vehicles, but could only find %d spawn points'
            print(msg)
            # logging.warning(msg, self.extra_num, number_of_spawn_points)
            self.extra_num = number_of_spawn_points

        blueprints = world.get_blueprint_library().filter('vehicle.*')
        blueprints = [
            x for x in blueprints
            if int(x.get_attribute('number_of_wheels')) == 4
        ]
        # blueprints = [x for x in blueprints if not x.id.endswith('isetta')]
        # blueprints = [x for x in blueprints if not x.id.endswith('carlacola')]

        # print(number_of_spawn_points)
        for n, transform in enumerate(spawn_points):

            ## surrounding vehicle 차량 spawn 지점 visualize
            #     world.debug.draw_string(transform.location, 'o', draw_shadow=True,
            #                             color=carla.Color(r=255, g=255, b=255), life_time=30)

            if n >= self.extra_num:
                break
            if transform == start_pose:
                continue
            blueprint = random.choice(blueprints)
            if blueprint.has_attribute('color'):
                color = random.choice(
                    blueprint.get_attribute('color').recommended_values)
                blueprint.set_attribute('color', color)
            if blueprint.has_attribute('driver_id'):
                driver_id = random.choice(
                    blueprint.get_attribute('driver_id').recommended_values)
                blueprint.set_attribute('driver_id', driver_id)
            # blueprint.set_attribute('role_name', 'autopilot')
            # batch.append(SpawnActor(blueprint, transform).then(SetAutopilot(FutureActor, True)))

            extra = world.spawn_actor(
                random.choice(
                    blueprint_library.filter('vehicle.bmw.grandtourer')),
                transform)
            extra_pose = self.map.get_waypoint(
                transform.location, lane_type=carla.LaneType.Driving)
            self.extra_controller_list.append(
                Pure_puresuit_controller(extra, extra_pose, None, 30))  # km/h
            # extra.set_autopilot(True)
            self.extra_list.append(extra)

        # for response in client.apply_batch_sync(batch):
        #     if response.error:
        #         logging.error(response.error)
        #     else:
        #         self.extra_list.append(response.actor_id)

    def draw_image(self, surface, image, blend=False):
        array = np.frombuffer(image.raw_data, dtype=np.dtype("uint8"))
        array = np.reshape(array, (image.height, image.width, 4))
        array = array[:, :, :3]
        array = array[:, :, ::-1]
        image_surface = pygame.surfarray.make_surface(array.swapaxes(0, 1))
        if blend:
            image_surface.set_alpha(100)
        surface.blit(image_surface, (0, 0))

    def save_traj(self, current_location):
        f = open('route.txt', 'a')
        f.write(str(current_location.transform.location.x) + " ")
        f.write(str(current_location.transform.location.y) + " ")
        f.write(str(current_location.transform.location.z))
        f.write("\n")
        f.close()

    def load_traj(self):
        f = open("route.txt", 'r')
        while True:
            line = f.readline()
            if not line: break
            _list = line.split(' ')
            _list = list(map(float, _list))
            point = carla.Transform()
            point.location.x = _list[0]
            point.location.y = _list[1]
            point.location.z = _list[2]
            self.path.append(point)
        #trajectory visualize
        # for n, x in enumerate(self.path):
        #     world.debug.draw_string(x.location, 'o', draw_shadow=True,
        #                             color=carla.Color(r=255, g=255, b=255), life_time=30)
        f.close()

    def get_gray_segimg(self, image_semseg):
        image_size = 96
        array = np.frombuffer(image_semseg.raw_data, dtype=np.dtype("uint8"))
        array = array.reshape((self.height, self.width, 4))
        array = array[:, :, :3]
        array = array[:, :, ::-1]
        array = cv2.cvtColor(array, cv2.COLOR_BGR2GRAY)

        cv2.imshow("camera.semantic_segmentation", array)
        cv2.resizeWindow('Resized Window', 100, 100)
        cv2.waitKey(1)

        array = np.reshape([cv2.resize(array, (image_size, image_size))],
                           (1, image_size, image_size))  # (1, 96, 96)

        return array

    def main(self):

        clock = pygame.time.Clock()
        display = pygame.display.set_mode((self.width, self.height),
                                          pygame.HWSURFACE | pygame.DOUBLEBUF)
        controller = Pure_puresuit_controller(self.player, self.waypoint,
                                              self.extra_list, 50)  # km/h
        Keyboardcontrol = KeyboardControl(self, False)
        # controller = VehicleControl(self, True)
        # self.player.apply_control(carla.Vehicle
        # Control(throttle=1.0, steer=0.0, brake=0.0))
        vehicles = self.world.get_actors().filter('vehicle.*')
        # for i in vehicles:
        #     print(i.id)
        cnt = 0
        decision = None
        try:
            # Create a synchronous mode context.
            with CarlaSyncMode(world,
                               self.camera_rgb.sensor,
                               self.camera_semseg.sensor,
                               fps=40) as sync_mode:
                while True:
                    if Keyboardcontrol.parse_events(client, self, clock):
                        return
                    clock.tick()

                    cnt += 1
                    if cnt == 1000:
                        print('수해유 ㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠ')
                        decision = 1
                        aa = controller.apply_control(decision)
                    else:
                        aa = controller.apply_control()

                    for i in range(len(self.extra_controller_list)):
                        self.extra_controller_list[i].apply_control()

                    # world.debug.draw_string(aa, 'o', draw_shadow=True,
                    #                         color=carla.Color(r=255, g=255, b=255), life_time=-1)
                    # print(self.waypoint.transform)
                    # print(self.player.get_transform())
                    # print(dist)

                    self.hud.tick(self, clock)
                    # print( clock.get_fps())
                    # Advance the simulation and wait for the data.
                    snapshot, image_rgb, image_semseg = sync_mode.tick(
                        timeout=0.1)

                    # Choose the next waypoint and update the car location.
                    # self.waypoint = random.choice(self.waypoint.next(1.5))
                    # self.player.set_transform(self.waypoint.transform)
                    # self.world.debug.draw_point(self.waypoint.transform.location,size=0.1,color=carla.Color(r=255, g=255, b=255),life_time=1)

                    ## player trajactory history visualize ## -> project_to_road = false 시 차량의 궤적, True 시 차선센터 출력
                    # curent_location=self.map.get_waypoint(self.player.get_transform().location,project_to_road=True)
                    # world.debug.draw_string(curent_location.transform.location, 'o', draw_shadow=True,
                    #                         color=carla.Color(r=0, g=255, b=255), life_time=100)
                    ##이동 궤적 저장
                    # self.save_traj(curent_location)

                    # self.world.debug.draw_point(ww.transform.location,size=0.1,color=carla.Color(r=255, g=255, b=255),life_time=1)

                    self.spectator.set_transform(
                        carla.Transform(
                            self.player.get_transform().location +
                            carla.Location(z=100), carla.Rotation(pitch=-90)))

                    image_semseg.convert(
                        carla.ColorConverter.CityScapesPalette)
                    gray_image = self.get_gray_segimg(image_semseg)
                    # fps = round(1.0 / snapshot.timestamp.delta_seconds)

                    # Draw the display.
                    self.draw_image(display, image_rgb)
                    # self.draw_image(display, image_semseg, blend=False)
                    # pygame.gfxdraw.filled_circle(display,int(self.waypoint.transform.location.x),int(self.waypoint.transform.location.y),5,(255,255,255))
                    self.hud.render(display)

                    pygame.display.flip()

        finally:
            print('\ndestroying %d vehicles' % len(self.extra_list))
            # client.apply_batch([carla.command.DestroyActor(x) for x in self.extra_list])

            print('destroying actors.')
            for actor in self.actor_list:
                actor.destroy()
            for extra in self.extra_list:
                extra.destroy()

            pygame.quit()
            print('done.')
Exemple #27
0
class BoardManager():
    def __init__(self, nw_tile, nh_tile):
        self.nw_tile = nw_tile  # Set number of tile in x
        self.nh_tile = nh_tile  # Set number of tile in y

        self.number_body = 3  # Set number of snake's body
        self.score = 0  # Set score of sanke

        self.db_save_size = 6  # Column size of data base
        self.id = 0  # index of database's column
        self.type = 1
        self.x = 2
        self.y = 3
        self.s = 4
        self.t = 5

        self.enemy_dict = {}  # Enemy snake dictionary
        self.client_state_dict = {
            'OK': 0,
            'notNStart': 1,
            'notNExit': 2
        }  # KList state of client
        self.client_state = self.client_state_dict[
            'notNStart']  # State of cleint
        self.play_state = False  # Playing state
        self.game_time = 0  # time of game

        self.tile_mng = TileManager(width, height, self.nw_tile,
                                    self.nh_tile)  # Set TileManager
        self.snake = Snake(1, 1, self.tile_mng, green, SNAKE,
                           raw_input("Enter : "),
                           self.number_body)  # Set my sanke
        self.apple = Apple(0, 0, self.tile_mng, red, 0)  # Set apple
        self.hud = HUD()  # Set HUD

    # Update board
    def update(self):
        for event in pygame.event.get():  # Check all event
            if event.type == pygame.QUIT:  # Click Quit to quit program
                pygame.quit()  # quit programe
                quit()
            if event.type == pygame.KEYDOWN:  # If pressed keyboard
                if event.key == pygame.K_LEFT and not self.snake.get_move_list(
                        'right'):  # Pressed left and not go right
                    self.snake.set_left()  # Go left
                elif event.key == pygame.K_RIGHT and not self.snake.get_move_list(
                        'left'):  # Pressed right and not go left
                    self.snake.set_right()  # Go right
                elif event.key == pygame.K_UP and not self.snake.get_move_list(
                        'down'):  # Pressed up and not go down
                    self.snake.set_up()  # Go up
                elif event.key == pygame.K_DOWN and not self.snake.get_move_list(
                        'up'):  # Pressed down and not go up
                    self.snake.set_down()  # Go down
                elif event.key == pygame.K_x:  # Press x
                    self.snake.snake_slide(self.snake.get_move(),
                                           self.apple)  # Use slide snake skill
                elif event.key == pygame.K_c:  # Press c
                    self.snake.snake_running()  # Use running snake skill

        x_pos_ls = [
            int(self.snake.get_x_pos()[i] / self.tile_mng.get_sizew_tile())
            for i in range(self.snake.get_number_body())
        ]  # set x's list
        y_pos_ls = [
            int(self.snake.get_y_pos()[i] / self.tile_mng.get_sizeh_tile())
            for i in range(self.snake.get_number_body())
        ]  # set y's list
        x_pos_n = self.client.pos_pattern(
            x_pos_ls)  # save in string in postion pattern (x, y)
        y_pos_n = self.client.pos_pattern(y_pos_ls)
        pattern = self.client.set_pattern(self.snake.get_id(), [
            self.snake.get_type(), x_pos_n, y_pos_n,
            self.snake.get_score(), 0
        ])  # set pattern of all data
        # id,type,xs,ys,score,time

        if self.client_state == self.client_state_dict[
                'OK']:  # Client state is "OK"
            self.snake.snake_eat_apple(
                self.apple)  # Check does snake eat apple ?
            self.snake.update()  # Update snake
            if self.apple.get_eaten():  # Apple is eaten by snake
                pattern = "eaten"  # pattern is "eaten"
                self.apple.set_eaten(False)  # Apple is not eaten
        self.client.send(pattern)  # Send pattern to client

        data, addr = self.client.recv()  # Receive data from server
        if data == None:  # Data is none => exit method
            return
        if data == "notNStart":  # data is notNStart => set client state
            self.client_state = self.client_state_dict['notNStart']
        elif data == "notNExit":  # data is notNExit => set client state
            self.client_state = self.client_state_dict['notNExit']
        else:  # otherwise
            self.client_state = self.client_state_dict[
                'OK']  # Set client state to "OK"
            split_list = self.client.split(data)  # Split data
            for ls in split_list:
                self.game_time = int(ls[self.t])  # set time
                if ls[self.id] == "*":  # See id of apple
                    self.apple = Apple(int(ls[self.x]), int(ls[self.y]),
                                       self.tile_mng, red, str(ls[self.type]))
                elif ls[self.id] != self.snake.get_id() and ls[
                        self.id] != "*":  # See enemy snake's id
                    self.enemy_dict[ls[self.id]] = Snake(
                        0, 0, self.tile_mng, blue, ls[self.type], ls[self.id],
                        0)  # Save in dictionary of enemy snake
                    x_pos = self.client.pos_split(ls[self.x])
                    y_pos = self.client.pos_split(ls[self.y])
                    x_list = [
                        int(x_pos[i] * self.tile_mng.get_sizew_tile())
                        for i in range(len(x_pos))
                    ]
                    y_list = [
                        int(y_pos[i] * self.tile_mng.get_sizeh_tile())
                        for i in range(len(y_pos))
                    ]
                    self.enemy_dict[ls[self.id]].set_pos(
                        x_list, y_list)  # Set postion enemy snake

    # Render board
    def render(self):  # Render board
        game_display.fill(white)  # Background
        if self.client_state == self.client_state_dict[
                'OK']:  # Client state is OK
            if self.snake.state == 'dead':  # If dead
                # Draw dead HUD
                self.hud.dead_hud(game_display, self.snake.get_dead_ellapse(),
                                  self.snake.get_dead_delay(), width / 2,
                                  height / 2, width / 3, height / 3)
            else:
                self.apple.render(game_display)  # Render Apple
                self.snake.render(game_display,
                                  self.snake.get_number_body() -
                                  1)  # render snake
                for key in self.enemy_dict:  # Render enemy snake
                    self.enemy_dict[key].render(
                        game_display,
                        self.enemy_dict[key].get_number_body() - 1)
                # Draw time's hud, score' hud, gauge's hud
                self.hud.time_hud(game_display, self.game_time, width / 2,
                                  height * 0.05)
                self.hud.score_hud(game_display, self.snake.get_score(),
                                   width * 0.8, height * 0.05)
                self.hud.gauge_hud(
                    game_display,
                    min(
                        self.snake.get_slide_ellapse() /
                        self.snake.get_slide_delay(), 1), 0.6 * width,
                    0.95 * height, 0.4 * width, 0.02 * height)
                self.hud.gauge_hud(
                    game_display,
                    min(
                        self.snake.get_run_use_ellapse() /
                        self.snake.get_run_use_delay(), 1), 0.6 * width,
                    0.97 * height, 0.4 * width, 0.02 * height)
        pygame.display.update()  # Update display

    def loop(self):  # Loop to play always
        self.ip = raw_input("IP : ")  # Get IP
        self.client = ClientManager(self.ip, 8000)  # Set client
        packet = str(
            "tile:" + str(width) + "," + str(height) + "," +
            str(self.nw_tile) + "," + str(self.nh_tile)
        )  # Set pattern : width, height program and number of tile program
        self.client.send(packet)  # Send data to server
        self.client.close()  # Disconnnet socket
        while True:
            try:
                self.client = ClientManager(self.ip, 8000)  # Set client
                self.update()  # Update program
                self.render()  # Render program
                self.client.close()  # Disconnect from socket
            except KeyboardInterrupt:
                pygame.quit()  # Quit program
                quit()
        pygame.quit()  # Quit program
        quit()
Exemple #28
0
class Screen:

    def __init__(self, window, scene, menu):
        self.u = (2./3, -1./3.5)
        self.v = (-2./3, -1./3.5)
        self.w = (0, -15)

        self._window = window
        self._scene = scene
        self._hud = HUD(self)
        self._grid = Grid(self)
        self._players = pygame.sprite.Group()
        player1 = PlayerSprite(scene.getPlayer(0), menu)
        self._playerG1 = pygame.sprite.Group()
        self._playerG1.add(player1)
        player2 = PlayerSprite(scene.getPlayer(1), menu)
        self._playerG2 = pygame.sprite.Group()
        self._playerG2.add(player2)
        self._players.add(player1)
        self._players.add(player2)
        self._shadows = pygame.sprite.Group()
        self._shadows.add(ShadowSprite(scene.getPlayer(0)))
        self._shadows.add(ShadowSprite(scene.getPlayer(1)))
        self._weaponGroup = pygame.sprite.Group()
        self._weaponList = [WeaponSprite(scene.getPlayer(0).weapon()),
                WeaponSprite(scene.getPlayer(1).weapon())]

    def calcPos(self, vector):
        return (
            vector[0]*self.u[0] + vector[1]*self.v[0] + vector[2]*self.w[0] +
                self._window.get_width()/2,
            vector[0]*self.u[1] + vector[1]*self.v[1] + vector[2]*self.w[1] +
                self._window.get_height()/2
        )

    def calcPosZ(self, vector):
        return vector[0] + vector[1]

    def calcVec(self, vector):
        return (
            vector[0]*self.u[0] + vector[1]*self.v[0],
            vector[0]*self.u[1] + vector[1]*self.v[1]
        )

    def draw(self):
        self._players.update(self._scene, self)
        self._shadows.update(self._scene, self)
        self._window.fill(pygame.Color(255,255,255))    

        for w in self._weaponList:
            if w.weapon().active():
                self._weaponGroup.add(w)
            else:
                self._weaponGroup.remove(w)

        self._weaponGroup.update()

        self._grid.draw()
        self._shadows.draw(self._window)

        if self.calcPosZ(self._scene.getPlayer(0).position()) > self.calcPosZ(self._scene.getPlayer(1).position()):
            self._playerG1.draw(self._window);
            self._playerG2.draw(self._window);
        else:
            self._playerG2.draw(self._window);
            self._playerG1.draw(self._window);

        self._weaponGroup.draw(self._window)

        self._grid.afterDraw()

        self._hud.draw()

        pygame.display.flip()
class CarlaEnv():
    pygame.init()
    font = pygame.font.init()

    def __init__(self, world):
        #화면 크기
        n_iters = 100
        self.width = 800
        self.height = 600
        #센서 종류
        self.actor_list = []
        self.extra_list = []
        self.extra_list = []
        self.extra_controller_list = []
        self.extra_dl_list = []
        self.extra_dl_list = []
        self.player = None
        self.camera_rgb = None
        self.camera_semseg = None
        self.lane_invasion_sensor = None
        self.collision_sensor = None
        self.gnss_sensor = None
        self.waypoint = None
        self.path = []
        self.save_dir = None
        self.world = world
        self.map = world.get_map()
        self.spectator = self.world.get_spectator()
        self.hud = HUD(self.width, self.height)
        self.waypoints = self.map.generate_waypoints(3.0)
        self.lane_change_time = time.time()
        self.max_Lane_num = 4
        self.ego_Lane = 2
        self.agent = None
        self.controller = None
        self.is_first_time = True
        self.decision = None
        self.simul_time = time.time()
        self.accumulated_reward = 0
        self.end_point = 0
        self.ROI_length = 1000  #(meters)

        ## visualize all waypoints ##
        # for n, p in enumerate(self.waypoints):
        #     world.debug.draw_string(p.transform.location, 'o', draw_shadow=True,
        #                             color=carla.Color(r=255, g=255, b=255), life_time=999)

        settings = self.world.get_settings()
        # settings.no_rendering_mode = True
        # settings.synchronous_mode = True
        settings.fixed_delta_seconds = 0.02
        self.world.apply_settings(settings)
        self.extra_num = 30
        self.section = 0
        self.lane_distance_between_start = None
        self.lane_distance_between_end = None
        self.lane_change_point = None
        self.episode_start = None
        self.index = 0
        self.pre_max_Lane_num = self.max_Lane_num

        self.restart()
        self.main()

    def restart(self):
        self.decision = None
        self.simul_time = time.time()
        self.lane_change_time = time.time()
        self.max_Lane_num = 4
        self.ego_Lane = 2
        self.controller = None
        self.accumulated_reward = 0
        self.section = 0
        self.episode_start = time.time()
        self.pre_max_Lane_num = self.max_Lane_num
        self.index = 0
        print('start destroying actors.')

        if len(self.actor_list) != 0:
            # print('destroying actors.')
            # print("actor 제거 :", self.actor_list)

            for actor in self.actor_list:
                # print("finally 에서 actor 제거 :", self.actor_list)
                if actor.is_alive:
                    actor.destroy()
            print("finshed actor destroy")
            # for x in self.actor_list:
            #     try:
            #         client.apply_batch([carla.command.DestroyActors(x.id)])
            #     except:
            #         continue
        if len(self.extra_list) != 0:
            # client.apply_batch([carla.command.DestoryActors(x.id) for x in self.extra_list])
            # print("extra 제거 :", self.extra_list)
            for x in self.extra_list:
                try:
                    client.apply_batch([carla.command.DestroyActor(x.id)])
                except:
                    continue
            # for extra in self.extra_list:
            #     # print("finally 에서 actor 제거 :", self.extra_list)
            #     print(extra.is_alive)
            #     if extra.is_alive:
            #         extra.destroy()
            print("finshed extra destroy")

            # for x in self.extra_list:
            #     try:
            #         client.apply_batch([carla.command.DestroyActor(x.id)])
            #     except:
            #         continue
        print('finished destroying actors.')

        self.actor_list = []
        self.extra_list = []
        self.ROI_extra_list = []
        self.extra_controller_list = []
        self.extra_dl_list = []
        self.ROI_extra_dl_list = []
        blueprint_library = self.world.get_blueprint_library()
        # start_pose = random.choice(self.map.get_spawn_points())
        start_pose = self.map.get_spawn_points()[102]

        ##spawn points 시뮬레이션 상 출력##
        # print(start_pose)
        # for n, x in enumerate(self.map.get_spawn_points()):
        #     world.debug.draw_string(x.location, 'o', draw_shadow=True,
        #                             color=carla.Color(r=0, g=255, b=255), life_time=30)

        # self.load_traj()

        self.waypoint = self.map.get_waypoint(start_pose.location,
                                              lane_type=carla.LaneType.Driving)
        self.end_point = self.waypoint.next(400)[0].transform.location
        # print(self.waypoint.transform)
        ## Ego vehicle의 global Route 출력##
        world.debug.draw_string(self.waypoint.next(400)[0].transform.location,
                                'o',
                                draw_shadow=True,
                                color=carla.Color(r=0, g=255, b=255),
                                life_time=100)

        # print(start_pose)
        # print(self.waypoint.transform)

        # self.controller = MPCController.Controller

        self.player = world.spawn_actor(
            random.choice(blueprint_library.filter('vehicle.bmw.grandtourer')),
            start_pose)
        # print(self.player.bounding_box) # ego vehicle length

        self.actor_list.append(self.player)

        self.camera_rgb = RGBSensor(self.player, self.hud)
        self.actor_list.append(self.camera_rgb.sensor)

        # self.camera_depth =DepthCamera(self.player, self.hud)
        # self.actor_list.append(self.camera_depth.sensor)

        # self.camera_semseg = SegmentationCamera(self.player,self.hud)
        # self.actor_list.append(self.camera_semseg.sensor)

        self.collision_sensor = CollisionSensor(self.player,
                                                self.hud)  # 충돌 여부 판단하는 센서
        self.actor_list.append(self.collision_sensor.sensor)

        self.lane_invasion_sensor = LaneInvasionSensor(
            self.player, self.hud)  # lane 침입 여부 확인하는 센서
        self.actor_list.append(self.lane_invasion_sensor.sensor)

        self.gnss_sensor = GnssSensor(self.player)
        self.actor_list.append(self.gnss_sensor.sensor)

        # --------------
        # Spawn Surrounding vehicles
        # --------------

        print("Generate Extra")
        spawn_points = []
        blueprints = self.world.get_blueprint_library().filter('vehicle.*')
        blueprints = [
            x for x in blueprints
            if int(x.get_attribute('number_of_wheels')) == 4
        ]
        # print(*blueprints)
        for i in range(10, 10 * (self.extra_num) + 1, 10):
            dl = random.choice([-1, 0, 1])
            self.extra_dl_list.append(dl)
            spawn_point = None
            if dl == -1:
                spawn_point = self.waypoint.next(
                    i)[0].get_left_lane().transform
            elif dl == 0:
                spawn_point = self.waypoint.next(i)[0].transform
            elif dl == 1:
                spawn_point = self.waypoint.next(
                    i)[0].get_right_lane().transform
            else:
                print("Except ")
            spawn_point = carla.Transform(
                (spawn_point.location + carla.Location(z=1)),
                spawn_point.rotation)
            spawn_points.append(spawn_point)
            # print(blueprint_library.filter('vehicle.bmw.grandtourer'))
            # blueprint = random.choice(blueprint_library.filter('vehicle.bmw.grandtourer'))

            blueprint = random.choice(blueprints)
            # print(blueprint.has_attribute('color'))
            if blueprint.has_attribute('color'):
                # color = random.choice(blueprint.get_attribute('color').recommended_values)
                # print(blueprint.get_attribute('color').recommended_values)
                color = '255,255,255'
                blueprint.set_attribute('color', color)
            extra = self.world.spawn_actor(blueprint, spawn_point)
            self.extra_list.append(extra)
        print('Extra Genration Finished')

        self.spectator.set_transform(
            carla.Transform(
                self.player.get_transform().location + carla.Location(z=100),
                carla.Rotation(pitch=-90)))

        ROI = 1000
        # extra_target_velocity = 10
        port = 8000
        traffic_manager = client.get_trafficmanager(port)
        traffic_manager.set_global_distance_to_leading_vehicle(100.0)
        # traffic_manager.set_synchronous_mode(True) # for std::out_of_range eeror
        tm_port = traffic_manager.get_port()
        for extra in self.extra_list:
            extra.set_autopilot(True, tm_port)
            # Pure_puresuit_controller(extra, self.waypoint, None, 50)  # km/h
            # target_velocity = 30 #random.randrange(10, 40) # km/h
            # extra.enable_constant_velocity(extra.get_trzansform().get_right_vector() * target_velocity/3.6)
            traffic_manager.auto_lane_change(extra, False)
        # self.player.set_autopilot(True,tm_port)
        # traffic_manager.auto_lane_change(self.player, False)
        self.controller = Pure_puresuit_controller(self.player, self.waypoint,
                                                   self.extra_list, 70)  # km/h

        # target_velocity = 60 / 3.6
        # forward_vec = self.player.get_transform().get_forward_vector()
        # print(forward_vec)
        # velocity_vec =  target_velocity*forward_vec
        # self.player.set_target_velocity(velocity_vec)
        # print(velocity_vec)

        # print(velocity_vec)
        # client.get_trafficmanager.auto_lane_change(extra, False)
        ###Test####
        # clock = pygame.time.Clock()
        # Keyboardcontrol = KeyboardControl(self, False)
        # display = pygame.display.set_mode(
        #     (self.width, self.height),
        #     pygame.HWSURFACE | pygame.DOUBLEBUF)
        # while True:
        #     if Keyboardcontrol.parse_events(client, self, clock):
        #         return
        #     self.spectator.set_transform(
        #         carla.Transform(self.player.get_transform().location + carla.Location(z=50),
        #                         carla.Rotation(pitch=-90)))
        #     self.camera_rgb.render(display)
        #     self.hud.render(display)
        #     pygame.display.flip()
        #
        #     self.controller.apply_control()
        #     # self.world.wait_for_tick(10.0)
        #     clock.tick(30)
        #
        #     self.hud.tick(self, clock)

        #### Test Finished #####
        #### Test2 #####
        # cnt=0
        # clock = pygame.time.Clock()
        # while True:
        #     # print(self.waypoint.lane_id)
        #     self.spectator.set_transform(
        #         carla.Transform(self.player.get_transform().location + carla.Location(z=100),
        #                         carla.Rotation(pitch=-90)))
        #     cnt += 1
        #     if cnt == 100:
        #         print('수해유 ㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠㅠ')
        #         decision = 1
        #         self.controller.apply_control(decision)
        #     else:
        #        self.controller.apply_control()
        #     clock.tick(30)
        #### Test2 Finished #####

        # self.input_size = (self.extra_num)*4 + 1
        self.input_size = 4  #dr dv da dl
        self.output_size = 3

        # for response in client.apply_batch_sync(batch):
        #     if response.error:
        #         logging.error(response.error)
        #     else:
        #         self.extra_list.append(response.actor_id)
        print(5)

    def step(self, decision):
        SECONDS_PER_EPISODE = 1000
        plc = 10
        # decision = None
        '''
        # Simple Action (action number: 3)
        action_test = action -1
        self.vehicle.apply_control(carla.VehicleControl(throttle=1.0, steer=action_test*self.STEER_AMT))
        '''

        # Complex Action
        if decision == 0:  # LK
            plc = 0
        # elif action == -1:  # left
        #     plc += 10
        #     decision = -1
        # elif action == 1:  # right
        #     plc += 10
        #     decision = 1
        '''
        if len(self.collision_hist) != 0:
            done = True
            reward = -200 + (time.time()-self.episode_start)*15/SECONDS_PER_EPISODE
        else:
            done = False
            reward = 1
        '''
        end_length = math.sqrt(
            (self.end_point.x - self.player.get_location().x)**2 +
            (self.end_point.y - self.player.get_location().y)**2)

        done = False
        if len(self.collision_sensor.history) != 0:
            done = True
            reward = -100
        elif end_length < 15:
            done = True
            reward = 1
        elif self.max_Lane_num < self.ego_Lane:
            done = True
            reward = -100
        else:
            reward = 1 - (self.controller.desired_vel - self.controller.
                          velocity) / self.controller.desired_vel - plc
        # print(reward)
        self.accumulated_reward += reward

        if time.time() > self.episode_start + SECONDS_PER_EPISODE:
            done = True

        #state length = 4 * num of extra vehicles + 1

        state, x_static = self.get_next_state(decision)  #get now state

        # if len(state) == 29:
        #     print(" ")
        return state, x_static, decision, reward, None, None, done
        # Next State 표현 필요
    def get_next_state(self, decision=None):
        """
        dl : relative lane num after ching the lane
        dr, dv, da : now state
        """
        state = []
        for x, extra in enumerate(self.extra_list):

            if decision == 1:
                self.extra_dl_list[x] = self.extra_dl_list[x] + 1
                # self.ROI_extra_dl_list[x] =self.ROI_extra_dl_list[x]+1

            elif decision == -1:
                self.extra_dl_list[x] = self.extra_dl_list[x] - 1
                # self.ROI_extra_dl_list[x] = self.ROI_extra_dl_list[x]-1

            else:
                pass

            extra_pos = extra.get_transform().location
            extra_vel = extra.get_velocity()
            extra_acel = extra.get_acceleration()
            dr = ((extra_pos.x - self.player.get_transform().location.x)**2 +
                  (extra_pos.y - self.player.get_transform().location.y)**2 +
                  ((extra_pos.z - self.player.get_transform().location.z)**
                   2))**0.5 - abs(self.waypoint.lane_width *
                                  (self.extra_dl_list[x]))
            if isinstance(dr, complex):
                print("complex")
            dv = (self.player.get_velocity().x**2 +
                  self.player.get_velocity().y**2 +
                  self.player.get_velocity().z**2)**0.5 - (
                      extra_vel.x**2 + extra_vel.y**2 + extra_vel.z**2)**0.5

            length = 2 * extra.bounding_box.extent.x / 10  # length of extra vehicle

            # da = ((extra_acel.x - self.player.get_acceleration().x) ** 2 + (
            #         extra_acel.y - self.player.get_acceleration().y) ** 2 +
            #       (extra_acel.z - self.player.get_acceleration().z) ** 2) ** 0.5

            state_dyn = [dr, dv, length, self.extra_dl_list[x]]
            state.append(state_dyn)
            # state.append(dr)

            # state.append(dv)
            # state.append(da)
            # state.append(self.extra_dl_list[x])

        if decision == 1:
            self.ego_Lane += 1
        elif decision == -1:
            self.ego_Lane += -1
        else:
            pass
        x_static = []
        x_static.append([
            self.ego_Lane, self.controller.velocity,
            self.search_distance_valid() / self.ROI_length
        ])

        # state.append(x_static)

        # state.append(self.ego_Lane)
        out = [state, x_static]
        return out

    def search_distance_valid(self):
        # index= 4-self.ego_Lane
        # print("index :", index)
        last_lane_waypoint = self.map.get_waypoint(
            self.player.get_transform().location,
            lane_type=carla.LaneType.Driving)  #self.controller.waypoint
        search_raidus = 5
        distance = 9999
        # pre_distance = 0
        i = 0.01
        self.world.debug.draw_string(
            self.controller.waypoint.transform.location,
            'o',
            draw_shadow=True,
            color=carla.Color(r=0, g=0, b=255),
            life_time=1)
        try:
            while last_lane_waypoint.lane_id > -4:  # get waypoint of forth's lane
                last_lane_waypoint = last_lane_waypoint.get_right_lane()
            # print("lane id : ", last_lane_waypoint.lane_id)
        except:
            print("4-th lane not found")

        # self.world.debug.draw_string(last_lane_waypoint.transform.location,
        #                                  '4', draw_shadow=True,
        #                                  color=carla.Color(r=0, g=255, b=255), life_time=9999)

        # print(self.ego_Lane)
        # if self.max_Lane_num ==3:
        #     print("e")
        if self.max_Lane_num != self.pre_max_Lane_num:
            self.index += 1
            self.pre_max_Lane_num = self.max_Lane_num
        # print(self.index)
        if self.index % 2 == 0:
            while search_raidus <= distance:
                # pre_distance = distance
                distance = (
                    (last_lane_waypoint.next(i)[0].transform.location.x -
                     self.lane_change_point[self.index].x)**2 +
                    (last_lane_waypoint.next(i)[0].transform.location.y -
                     self.lane_change_point[self.index].y)**2 +
                    (last_lane_waypoint.next(i)[0].transform.location.z -
                     self.lane_change_point[self.index].z)**2)**0.5
                # if pre_distance <= distance:
                #     print("wrong")
                #     return distance + i
                if round(distance - search_raidus) > 0:
                    i += round(distance - search_raidus)
                    # break
                else:
                    return distance + i
        else:
            distance = math.hypot(
                last_lane_waypoint.transform.location.x -
                self.lane_change_point[self.index].x,
                last_lane_waypoint.transform.location.y -
                self.lane_change_point[self.index].y)
            return -distance

        # if self.max_Lane_num ==4:
        #         while search_raidus <= distance:
        #             pre_distance = distance
        #             # distance = ((last_lane_waypoint.next(i)[0].x-self.lane_start_point.x)**2+(last_lane_waypoint.next(i)[0].y-self.lane_start_point.y)**2+(last_lane_waypoint.next(i)[0].z-self.lane_start_point.z)**2)**0.5
        #             distance = ((last_lane_waypoint.next(i)[0].transform.location.x-self.lane_start_point[self.section].x)**2+(last_lane_waypoint.next(i)[0].transform.location.y-self.lane_start_point[self.section].y)**2+(last_lane_waypoint.next(i)[0].transform.location.z-self.lane_start_point[self.section].z)**2)**0.5
        #
        #             # print("distance :",distance , "i :", i)
        #             if pre_distance <= distance:
        #                 print("pre_distance <= distance error")
        #                 break
        #             elif round(distance - search_raidus) > 0:
        #                 i += round(distance - search_raidus)
        #             else:
        #                 return min(distance + i, self.ROI_length)
        #             # print("i updated :", i)
        #         # self.max_Lane_num =3
        # elif self.max_Lane_num == 3:
        #     while search_raidus <= distance:
        #         distance = ((last_lane_waypoint.next(i)[0].transform.location.x - self.lane_finished_point[
        #             self.section].x) ** 2 + (last_lane_waypoint.next(i)[0].transform.location.y -
        #                                      self.lane_finished_point[self.section].y) ** 2 + (
        #                             last_lane_waypoint.next(i)[0].transform.location.z -
        #                             self.lane_finished_point[self.section].z) ** 2) ** 0.5
        #         self.world.debug.draw_string(last_lane_waypoint.next(i)[0].transform.location,
        #                                      'o', draw_shadow=True,
        #                                      color=carla.Color(r=255, g=255, b=0), life_time=9999)
        #         if pre_distance <= distance:
        #             print("pre_distance <= distance error")
        #             break
        #         elif round(distance - search_raidus) > 0:
        #             i += round(distance - search_raidus)
        #         else:
        #             return min(distance + i, self.ROI_length)
        #
        #         if round(distance - search_raidus) > 0:
        #             i += round(distance - search_raidus)
        #         else:
        #             return max(-(distance + i), -self.ROI_length)

    def safety_check(self, decision, safe_lane_change_again_time=5):
        # print("method : ", self.agent.selection_method)
        # if decision==-1 and self.ego_Lane ==1:
        #     print("here")
        # elif decision ==1 and self.ego_Lane ==self.max_Lane_num:
        #     print("here")
        if decision != 0 and decision != None:
            if (time.time() -
                    self.lane_change_time) <= safe_lane_change_again_time:
                return 0  #즉 직진
            elif self.agent.selection_method == 'random' and decision == 1 and self.ego_Lane == self.max_Lane_num:
                action = random.randrange(-1, 1)
                return action
            elif self.agent.selection_method == 'random' and decision == -1 and self.ego_Lane == 1:
                action = random.randrange(0, 2)
                return action
            elif self.ego_Lane == self.max_Lane_num and decision == 1:
                return int(self.agent.q_value[0][0:2].argmax().item()) - 1
            elif self.ego_Lane == 1 and decision == -1:
                return int(self.agent.q_value[0]
                           [1:3].argmax().item())  #not max exception
            elif decision == 1 and self.ego_Lane != self.max_Lane_num:
                self.lane_change_time = time.time()
                return decision
            elif decision == -1 and self.ego_Lane != 1:
                self.lane_change_time = time.time()
                return decision
            else:  #3차선에서 우 차도 판단, 1차선에서 좌차선 판단
                if self.agent.selection_method == 'random' and decision == 1 and self.ego_Lane == self.max_Lane_num:
                    action = random.randrange(-1, 1)
                    return action
                elif self.agent.selection_method == 'random' and decision == -1 and self.ego_Lane == 1:
                    action = random.randrange(0, 2)
                    return action
                elif self.ego_Lane == self.max_Lane_num and decision == 1:
                    return int(self.agent.q_value[0][0:2].argmax().item()) - 1
                elif self.ego_Lane == 1 and decision == -1:
                    return int(self.agent.q_value[0][1:3].argmax().item())
        else:
            return decision

    # def safety_check_between_vehicles(self):
    #     if extra_lists

    def main_test(self):
        restart_time = time.time()
        PATH = "/home/a/RL_decision/trained_info.tar"
        print(torch.cuda.get_device_name())
        clock = pygame.time.Clock()
        Keyboardcontrol = KeyboardControl(self, False)
        display = pygame.display.set_mode((self.width, self.height),
                                          pygame.HWSURFACE | pygame.DOUBLEBUF)

        self.lane_start_point = [
            carla.Location(x=14.905815, y=-135.747452, z=0.000000),
            carla.Location(x=172.745468, y=-364.531799, z=0.000000),
            carla.Location(x=382.441040, y=-212.488907, z=0.000000)
        ]
        self.lane_finished_point = [
            carla.Location(x=14.631096, y=-205.746918, z=0.000000),
            carla.Location(x=232.962860, y=-364.149139, z=0.000000),
            carla.Location(x=376.542816, y=-10.352980, z=0.000000)
        ]
        self.lane_change_point = [
            carla.Location(x=14.905815, y=-135.747452, z=0.000000),
            carla.Location(x=14.631096, y=-205.746918, z=0.000000),
            carla.Location(x=172.745468, y=-364.531799, z=0.000000),
            carla.Location(x=232.962860, y=-364.149139, z=0.000000),
            carla.Location(x=382.441040, y=-212.488907, z=0.000000),
            carla.Location(x=376.542816, y=-10.352980, z=0.000000)
        ]

        self.world.debug.draw_string(carla.Location(x=14.905815,
                                                    y=-135.747452,
                                                    z=0.000000),
                                     'o',
                                     draw_shadow=True,
                                     color=carla.Color(r=0, g=255, b=0),
                                     life_time=9999)
        self.world.debug.draw_string(carla.Location(x=14.631096,
                                                    y=-205.746918,
                                                    z=0.000000),
                                     'o',
                                     draw_shadow=True,
                                     color=carla.Color(r=0, g=255, b=0),
                                     life_time=9999)
        # ---------------------------#

        self.world.debug.draw_string(carla.Location(x=172.745468,
                                                    y=-364.531799,
                                                    z=0.000000),
                                     'o',
                                     draw_shadow=True,
                                     color=carla.Color(r=0, g=255, b=0),
                                     life_time=9999)
        self.world.debug.draw_string(carla.Location(x=232.962860,
                                                    y=-364.149139,
                                                    z=0.000000),
                                     'o',
                                     draw_shadow=True,
                                     color=carla.Color(r=0, g=255, b=0),
                                     life_time=9999)
        # ---------------------------#
        self.world.debug.draw_string(carla.Location(x=382.441040,
                                                    y=-212.488907,
                                                    z=0.000000),
                                     'o',
                                     draw_shadow=True,
                                     color=carla.Color(r=0, g=255, b=0),
                                     life_time=9999)
        self.world.debug.draw_string(carla.Location(x=376.542816,
                                                    y=-10.352980,
                                                    z=0.000000),
                                     'o',
                                     draw_shadow=True,
                                     color=carla.Color(r=0, g=255, b=0),
                                     life_time=9999)

        lane_distance_between_points = []
        for i in range(len(self.lane_finished_point)):
            lane_distance_between_points.append(
                ((self.lane_start_point[i].x - self.lane_finished_point[i].x)**
                 2 + (self.lane_start_point[i].y -
                      self.lane_finished_point[i].y)**2 +
                 (self.lane_start_point[i].z - self.lane_finished_point[i].z)**
                 2)**0.5)

        pre_decision = None
        while True:
            # if time.time()-restart_time > 10:
            #     print("restart")
            #     self.restart()
            if Keyboardcontrol.parse_events(client, self, clock):
                return
            self.spectator.set_transform(
                carla.Transform(
                    self.player.get_transform().location +
                    carla.Location(z=50), carla.Rotation(pitch=-90)))
            self.camera_rgb.render(display)
            self.hud.render(display)
            pygame.display.flip()

            ## Get max lane ##
            # print("start get lane")
            if self.section < len(lane_distance_between_points):

                self.lane_distance_between_start = (
                    (self.player.get_transform().location.x -
                     self.lane_start_point[self.section].x)**2 +
                    (self.player.get_transform().location.y -
                     self.lane_start_point[self.section].y)**2)**0.5
                self.lane_distance_between_end = (
                    (self.player.get_transform().location.x -
                     self.lane_finished_point[self.section].x)**2 +
                    (self.player.get_transform().location.y -
                     self.lane_finished_point[self.section].y)**2)**0.5

                # print("self.lane_distance_between_start : ",self.lane_distance_between_start,"self.lane_distance_between_end :",self.lane_distance_between_end, "lane_distance_between_points[section]",lane_distance_between_points[self.section],"section :", self.section)
                if max(lane_distance_between_points[self.section], self.lane_distance_between_start, self.lane_distance_between_end) == \
                        lane_distance_between_points[self.section]:
                    self.max_Lane_num = 3
                    # world.debug.draw_string(self.player.get_transform().location, 'o', draw_shadow = True,
                    #                                 color = carla.Color(r=255, g=255, b=0), life_time = 999)

                elif max(lane_distance_between_points[self.section], self.lane_distance_between_start, self.lane_distance_between_end) == \
                        self.lane_distance_between_start and self.max_Lane_num ==3:
                    self.section += 1
                    self.max_Lane_num = 4
                    if self.section >= len(lane_distance_between_points
                                           ):  # when, section_num = 3
                        self.section = 0
            ## finished get max lane ##
            # print("finished get lane")

            self.search_distance_valid()
            # print("distance :" ,,"max_lane_num : ", self.max_Lane_num)

            if self.max_Lane_num == 3:
                self.world.debug.draw_string(
                    self.player.get_transform().location,
                    'o',
                    draw_shadow=True,
                    color=carla.Color(r=255, g=255, b=0),
                    life_time=9999)
            if time.time() - self.lane_change_time > 10:
                self.lane_change_time = time.time()
                if pre_decision is None:
                    self.decision = 1
                    self.ego_Lane += 1
                    pre_decision = 1

                elif pre_decision == 1:
                    pre_decision = -1
                    self.ego_Lane += -1
                    self.decision = -1

                elif pre_decision == -1:
                    self.decision = 1
                    self.ego_Lane += 1
                    pre_decision = 1

            else:
                self.decision = 0

            self.controller.apply_control(self.decision)
            # self.world.wait_for_tick(10.0)
            clock.tick(30)

            self.hud.tick(self, clock)

    def main(self):
        PATH = "/home/a/RL_decision/trained_info.tar"
        print(torch.cuda.get_device_name())
        clock = pygame.time.Clock()
        Keyboardcontrol = KeyboardControl(self, False)
        display = pygame.display.set_mode((self.width, self.height),
                                          pygame.HWSURFACE | pygame.DOUBLEBUF)
        self.agent = decision_driving_Agent(self.input_size, self.output_size,
                                            True, 1000, self.extra_num)
        self.lane_start_point = [
            carla.Location(x=14.905815, y=-135.747452, z=0.000000),
            carla.Location(x=172.745468, y=-364.531799, z=0.000000),
            carla.Location(x=382.441040, y=-212.488907, z=0.000000)
        ]
        self.lane_finished_point = [
            carla.Location(x=14.631096, y=-205.746918, z=0.000000),
            carla.Location(x=232.962860, y=-364.149139, z=0.000000),
            carla.Location(x=376.542816, y=-10.352980, z=0.000000)
        ]
        self.lane_change_point = [
            carla.Location(x=14.905815, y=-135.747452, z=0.000000),
            carla.Location(x=14.631096, y=-205.746918, z=0.000000),
            carla.Location(x=172.745468, y=-364.531799, z=0.000000),
            carla.Location(x=232.962860, y=-364.149139, z=0.000000),
            carla.Location(x=382.441040, y=-212.488907, z=0.000000),
            carla.Location(x=376.542816, y=-10.352980, z=0.000000)
        ]

        self.world.debug.draw_string(carla.Location(x=14.905815,
                                                    y=-135.747452,
                                                    z=0.000000),
                                     'o',
                                     draw_shadow=True,
                                     color=carla.Color(r=0, g=255, b=0),
                                     life_time=9999)
        self.world.debug.draw_string(carla.Location(x=14.631096,
                                                    y=-205.746918,
                                                    z=0.000000),
                                     'o',
                                     draw_shadow=True,
                                     color=carla.Color(r=0, g=255, b=0),
                                     life_time=9999)
        # ---------------------------#

        self.world.debug.draw_string(carla.Location(x=172.745468,
                                                    y=-364.531799,
                                                    z=0.000000),
                                     'o',
                                     draw_shadow=True,
                                     color=carla.Color(r=0, g=255, b=0),
                                     life_time=9999)
        self.world.debug.draw_string(carla.Location(x=232.962860,
                                                    y=-364.149139,
                                                    z=0.000000),
                                     'o',
                                     draw_shadow=True,
                                     color=carla.Color(r=0, g=255, b=0),
                                     life_time=9999)
        # ---------------------------#
        self.world.debug.draw_string(carla.Location(x=376.542816,
                                                    y=-10.352980,
                                                    z=0.000000),
                                     'o',
                                     draw_shadow=True,
                                     color=carla.Color(r=0, g=255, b=0),
                                     life_time=9999)
        self.world.debug.draw_string(carla.Location(x=382.441040,
                                                    y=-212.488907,
                                                    z=0.000000),
                                     'o',
                                     draw_shadow=True,
                                     color=carla.Color(r=0, g=255, b=0),
                                     life_time=9999)
        lane_distance_between_points = []
        for i in range(len(self.lane_finished_point)):
            lane_distance_between_points.append(
                (self.lane_start_point[i].x -
                 self.lane_finished_point[i].x)**2 +
                (self.lane_start_point[i].y -
                 self.lane_finished_point[i].y)**2 +
                (self.lane_start_point[i].z -
                 self.lane_finished_point[i].z)**2)

        epoch_init = 0
        # if(os.path.exists(PATH)):
        #     print("저장된 가중치 불러옴")
        #     checkpoint = torch.load(PATH)
        #
        #     self.agent.model.load_state_dict(checkpoint['model_state_dict'])
        #     device = torch.device('cuda')
        #     self.agent.model.to(device)
        #     self.agent.optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
        #     self.agent.buffer = checkpoint['memorybuffer']
        #     epoch_init = checkpoint['epoch']

        # self.agent.buffer.load_state_dict(self.save_dir['memorybuffer'])

        # self.is_first_time = False
        # controller = VehicleControl(self, True)
        # self.player.apply_control(carla.Vehicle
        # Control(throttle=1.0, steer=0.0, brake=0.0))
        # vehicles = self.world.get_actors().filter('vehicle.*')
        # for i in vehicles:
        #     print(i.id)
        try:
            n_iters = 150
            is_error = 0

            for epoch in range(epoch_init, n_iters):
                # cnt = 0
                first_time_print = True

                [state, x_static] = self.get_next_state()  #초기 상태 s0 초기화
                while (True):
                    if Keyboardcontrol.parse_events(client, self, clock):
                        return

                    self.camera_rgb.render(display)
                    self.hud.render(display)
                    pygame.display.flip()

                    self.spectator.set_transform(
                        carla.Transform(
                            self.player.get_transform().location +
                            carla.Location(z=100), carla.Rotation(pitch=-90)))

                    ## Get max lane ##
                    if self.section < len(lane_distance_between_points):
                        self.lane_distance_between_start = (
                            (self.player.get_transform().location.x -
                             self.lane_start_point[self.section].x)**2 +
                            (self.player.get_transform().location.y -
                             self.lane_start_point[self.section].y)**2)
                        self.lane_distance_between_end = (
                            (self.player.get_transform().location.x -
                             self.lane_finished_point[self.section].x)**2 +
                            (self.player.get_transform().location.y -
                             self.lane_finished_point[self.section].y)**2)

                        # print("self.lane_distance_between_start : ",self.lane_distance_between_start,"self.lane_distance_between_end :",self.lane_distance_between_end, "lane_distance_between_points[self.section]",lane_distance_between_points[self.section],"self.section :", self.section)
                        if max(lane_distance_between_points[self.section], self.lane_distance_between_start,
                               self.lane_distance_between_end) == \
                                lane_distance_between_points[self.section]:
                            self.max_Lane_num = 3
                            # world.debug.draw_string(self.player.get_transform().location, 'o', draw_shadow = True,
                            #                                 color = carla.Color(r=255, g=255, b=0), life_time = 999)

                        elif max(lane_distance_between_points[self.section], self.lane_distance_between_start,
                                 self.lane_distance_between_end) == \
                                self.lane_distance_between_start and self.max_Lane_num == 3:
                            self.section += 1
                            self.max_Lane_num = 4
                            if self.section >= len(lane_distance_between_points
                                                   ):  # when, section_num = 3
                                self.section = 0
                    ## finished get max lane ##
                    ##visualize when, max lane ==3 ##
                    if self.max_Lane_num == 3:
                        self.world.debug.draw_string(
                            self.waypoint.transform.location,
                            'o',
                            draw_shadow=True,
                            color=carla.Color(r=255, g=255, b=255),
                            life_time=9999)
                    # [self.extra_list, self.extra_dl_list] = self.agent.search_extra_in_ROI(self.extra_list,self.player,self.extra_dl_list)

                    ## finished to visualize ##

                    if self.agent.is_training:
                        ##dqn 과정##
                        # 가중치 초기화 (pytroch 내부)
                        # 입실론-그리디 행동 탐색 (act function)
                        # 메모리 버퍼에 MDP 튜플 얻기   ㅡ (step function)
                        # 메모리 버퍼에 MDP 튜플 저장   ㅡ
                        # optimal Q 추정             ㅡ   (learning function)
                        # Loss 계산                  ㅡ
                        # 가중치 업데이트              ㅡ

                        if epoch % 10 == 0:
                            # [w, b] = self.agent.model.parameters()  # unpack parameters
                            self.save_dir = torch.save(
                                {
                                    'epoch':
                                    epoch,
                                    'model_state_dict':
                                    self.agent.model.state_dict(),
                                    'optimizer_state_dict':
                                    self.agent.optimizer.state_dict(),
                                    'memorybuffer':
                                    self.agent.buffer
                                }, PATH)
                        # print(clock.get_fps())
                        # if  time.time() - self.simul_time >10 and clock.get_fps()  < 15:
                        #     self.restart()
                        #     time.sleep(3)
                        #     continue
                        if self.decision is not None:
                            [next_state, next_x_static] = self.get_next_state()
                            sample = [
                                state, x_static, self.decision, reward,
                                next_state, next_x_static, done
                            ]
                            self.agent.buffer.append(sample)

                        # print("befor act")
                        self.decision = self.agent.act(state, x_static)
                        # print("after act")

                        # print(decision)
                        # if self.decision ==1 and self.max_Lane_num==self.ego_Lane:
                        #     print( " ")
                        # print("befroe safte check/ 판단 :", self.decision, "최대 차선 :", self.max_Lane_num, "ego lane :",self.ego_Lane)

                        self.decision = self.safety_check(self.decision)
                        # print("판단 :", self.decision, "최대 차선 :", self.max_Lane_num, "ego lane :",self.ego_Lane)

                        # print("before")
                        is_error = self.controller.apply_control(self.decision)
                        # print("after")

                        # print("extra_controller 개수 :", len(self.extra_controller_list))
                        # for i in range(len(self.extra_controller_list)):
                        #     self.extra_controller_list[i].apply_control()

                        # print("before step")
                        [state, x_static, decision, reward, __, _,
                         done] = self.step(self.decision)
                        # print("after step")

                        if done:
                            print("epsilon :", self.agent.epsilon)
                            print("epoch : ", epoch, "누적 보상 : ",
                                  self.accumulated_reward)
                            writer.add_scalar('누적 보상 ',
                                              self.accumulated_reward, epoch)
                            if len(self.agent.buffer.size()
                                   ) > self.agent.batch_size:
                                # print("start learning")
                                for i in range(300):
                                    self.agent.learning()
                            # print("finished learning")
                            client.set_timeout(10)
                            self.restart()
                            break

                    else:
                        self.agent.act(state, x_static)

                    clock.tick(40)
                    self.hud.tick(self, clock)

        finally:
            print('\ndestroying %d vehicles' % len(self.extra_list))
            # client.apply_batch([carla.command.DestroyActor(x) for x in self.extra_list])

            print('destroying actors.')
            # client.apply_batch([carla.command.DestroyActors(x.id) for x in self.actor_list])
            # client.apply_batch([carla.command.DestroyActors(x.id) for x in self.extra_list])
            for actor in self.actor_list:
                # print("finally 에서 actor 제거 :", self.actor_list)
                if actor.is_alive:
                    actor.destroy()
            for extra in self.extra_list:
                # print("finally 에서 actor 제거 :", self.extra_list)
                if extra.is_alive:
                    extra.destroy()

            # pygame.quit()
            print('done.')
Exemple #30
0
    def __init__(self):
        """
        Main game class initialization. All other class references point to this class as "game"
        """
        # window setup
        pygame.display.set_caption('Necromonster')
        pygame.display.set_icon(
            pygame.image.load(os.path.join('rec', 'misc', 'icon.png')))
        self.main_path = os.getcwd()

        # initiate the clock and screen object
        self.clock = pygame.time.Clock()
        self.FPS = 50
        self.last_tick = pygame.time.get_ticks()
        self.screen_res = [900, 650]
        self.center_point = [470, 350]
        self.screen = pygame.display.set_mode(self.screen_res,
                                              pygame.HWSURFACE, 32)

        #DEBUG values
        self.DEBUG = 1
        self.RECT_DEBUG = 0
        self.angle = 0

        #Init and assign custom game class(es)
        self.EntityHandler = EntityHandler(self)
        self.ParticleManager = ParticleManager(self)
        self.Scheduler = Schedule(self)
        self.Entity = Entity
        self.Projectile = Projectile
        self.Monster = Monster
        self.NPC = NPC
        self.NPCText = NPCText
        self.Item = Item
        self.Inventory = Invent
        self.Invent = self.Inventory(self)
        self.Weapon = Weapon
        self.Garment = Garment
        self.Player = Player(self)
        self.HUD = HUD(self)

        # Init entity manager vars
        self.entities = []
        self.shadows = []

        # load fonts, create font list
        # do not use pygame.font.SysFont!
        self.text_list = []
        self.default_font = pygame.font.Font(
            os.path.join('rec', 'font', 'freesansbold.ttf'), 15)
        self.speak_font = pygame.font.Font(
            os.path.join('rec', 'font', 'freesansbold.ttf'), 30)

        # load the map that player is on
        self.INSIDE = 0
        self.blit_list = mapLoader.load('home', self)

        # spawn initial map items/entities
        self.Item(self, 'Mythril', [350, 400], world=1)
        self.NPC(self, "blacksmith", [400, 400], 100, 'still')
        for i in xrange(4):
            self.Monster(self, 'chicken', [200 + (i * 50), 650], 1, 'neutral')
        self.Monster(self, "goop", [100, 100], 1, 'aggressive')

        # begin main game loop
        while 1:
            self.Loop()
Exemple #31
0
class Necro():
    def __init__(self):
        """
        Main game class initialization. All other class references point to this class as "game"
        """
        # window setup
        pygame.display.set_caption('Necromonster')
        pygame.display.set_icon(
            pygame.image.load(os.path.join('rec', 'misc', 'icon.png')))
        self.main_path = os.getcwd()

        # initiate the clock and screen object
        self.clock = pygame.time.Clock()
        self.FPS = 50
        self.last_tick = pygame.time.get_ticks()
        self.screen_res = [900, 650]
        self.center_point = [470, 350]
        self.screen = pygame.display.set_mode(self.screen_res,
                                              pygame.HWSURFACE, 32)

        #DEBUG values
        self.DEBUG = 1
        self.RECT_DEBUG = 0
        self.angle = 0

        #Init and assign custom game class(es)
        self.EntityHandler = EntityHandler(self)
        self.ParticleManager = ParticleManager(self)
        self.Scheduler = Schedule(self)
        self.Entity = Entity
        self.Projectile = Projectile
        self.Monster = Monster
        self.NPC = NPC
        self.NPCText = NPCText
        self.Item = Item
        self.Inventory = Invent
        self.Invent = self.Inventory(self)
        self.Weapon = Weapon
        self.Garment = Garment
        self.Player = Player(self)
        self.HUD = HUD(self)

        # Init entity manager vars
        self.entities = []
        self.shadows = []

        # load fonts, create font list
        # do not use pygame.font.SysFont!
        self.text_list = []
        self.default_font = pygame.font.Font(
            os.path.join('rec', 'font', 'freesansbold.ttf'), 15)
        self.speak_font = pygame.font.Font(
            os.path.join('rec', 'font', 'freesansbold.ttf'), 30)

        # load the map that player is on
        self.INSIDE = 0
        self.blit_list = mapLoader.load('home', self)

        # spawn initial map items/entities
        self.Item(self, 'Mythril', [350, 400], world=1)
        self.NPC(self, "blacksmith", [400, 400], 100, 'still')
        for i in xrange(4):
            self.Monster(self, 'chicken', [200 + (i * 50), 650], 1, 'neutral')
        self.Monster(self, "goop", [100, 100], 1, 'aggressive')

        # begin main game loop
        while 1:
            self.Loop()

    def Loop(self):
        """
        Main loop of the game. Calls tick, draw, and event processing
        functions. Tick and draw are only called every 20 milliseconds
        """
        self.eventLoop()
        self.Tick()
        self.Draw()
        pygame.display.update()

    def eventLoop(self):
        """
        Uses pygame event handling to process keypresses and mouse clicks.
        Used for chat, interacting with objects, and inventory management
        """
        for event in pygame.event.get():
            event  # prevents exit button freeze up
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN:
                # toggle chat bar active
                if not self.HUD.chat_active:
                    if event.key == K_e:
                        self.Invent.toggleView()
                    if event.key == K_t:
                        #activate the chat bar
                        self.HUD.chat_message = ''
                        self.HUD.chat_active = 1
                        self.Player.can_move = 0
                        return 0
                # process chat messages. Remove or add characters while chat box is open
                if event.key == K_ESCAPE or event.key == K_RETURN:
                    self.HUD.processCommand(self.HUD.chat_message)
                    self.HUD.chat_active = 0
                    self.Player.can_move = 1
                    self.HUD.chat_message = ''
                elif event.key == K_BACKSPACE:
                    self.HUD.chat_message = self.HUD.chat_message[:-1]
                elif event.key <= 255:
                    char = chr(event.key)
                    if self.keys_pressed[K_LSHIFT] or self.keys_pressed[
                            K_RSHIFT]:
                        char = char.upper()
                    self.HUD.chat_message += char
                # interaction with entities on space bar press
                if event.key == K_SPACE:
                    for monster in self.EntityHandler.monsters:
                        if monster.NPC:
                            if monster.isPlayerClose(
                                    75) and monster.interacting == False:
                                monster.interacting = True
                            elif not monster.isPlayerClose(
                                    75) or monster.interacting == True:
                                monster.interacting = False
                                self.HUD.delPrompt()
            # inventory management, checks for item throws, and placement in slots.
            elif event.type == MOUSEBUTTONDOWN:
                self.Invent.last_click = pygame.mouse.get_pos()
                if self.Invent.in_hand:
                    self.Invent.testThrow(self.Invent.last_click)
                if self.Invent.shown:
                    self.Invent.inventClick(self.Invent.last_click)
                elif pygame.mouse.get_pressed()[0]:
                    self.Player.attack(pygame.mouse.get_pos())

    def Tick(self):
        """
        Updates all game math and entity states. No drawing is done.
        """
        ttime = self.clock.tick(self.FPS)
        self.keys_pressed = pygame.key.get_pressed()
        if self.keys_pressed[K_EQUALS]:
            self.HUD.daytime_start -= 3
        if self.keys_pressed[K_MINUS]:
            self.HUD.daytime_start += 3
        self.Scheduler.update()
        self.EntityHandler.updateAll(ttime)

        self.Invent.update()
        self.HUD.updateDay()
        for index, text in enumerate(self.text_list):
            if text[2]:
                raise DeprecationWarning
        self.last_tick = pygame.time.get_ticks()

    def off(self, coords):
        """
        Offsets image coordinates to appear correct from the view of the player.
        Should be called on all surface coordinates before blitting.
        """
        newx = coords[0] - self.Player.player_r.x + 450
        newy = coords[1] - self.Player.player_r.y + 325
        return [newx, newy]

    def unoff(self, coords):
        """
        Removes the offset created by the off() function.
        """
        newx = coords[0] + self.Player.player_r.x - 450
        newy = coords[1] + self.Player.player_r.y - 325
        return [newx, newy]

    def getCenterBlit(self, surface, pos):
        pos[0] = pos[0] + surface.get_width() / 2
        pos[1] = pos[1] + surface.get_height() / 2
        return pos

    def rotopoint(self, surface, angle, pos):
        size = surface.get_size()
        if pos[0] > size[0] / 2 or pos[1] > size[1] / 2:
            print 'BIG ASS HONKEY'
        new_surf_size = [(size[0] - pos[0]) * 2, (size[1] - pos[1]) * 2]
        new_surf_blit_pos = [
            new_surf_size[0] - size[0], new_surf_size[1] - size[1]
        ]
        new_surf = pygame.Surface(new_surf_size, pygame.SRCALPHA, 32)
        new_surf.blit(surface, new_surf_blit_pos)
        return pygame.transform.rotate(new_surf, angle)

    def testrot(self, image, angle):
        loc = image.get_rect().center
        new_rot = pygame.transform.rotate(image, angle)
        new_rot.get_rect(center=loc)
        return new_rot, new_rot.get_rect()

    def Draw(self):
        """
        Completes all blitting to the screend object, includes HUD updates.
        """
        tile_width = self.tile[1][0]
        tile_height = self.tile[1][1]
        tile_extrax = self.Player.player_r.x % tile_width
        tile_extray = self.Player.player_r.y % tile_height
        y = 0

        for i in xrange(self.screen_res[1] / tile_height + 3):
            for i in xrange(self.screen_res[0] / tile_width + 3):
                self.screen.blit(self.tile[0], [
                    i * tile_width - tile_width - tile_extrax,
                    y - tile_height - tile_extray
                ])
            y += self.tile[1][1]
        if self.shadows:
            for s in self.shadows:
                s.update(self.screen)
        for surf in self.blit_list:
            if 'player' in surf:
                self.EntityHandler.blitAll()
            else:
                self.screen.blit(surf[0], self.off(surf[1]))
        for text in self.text_list:
            self.screen.blit(text[0], text[1])
        if self.Invent.shown:
            self.Invent.draw()
        if self.DEBUG:
            self.screen.blit(
                self.default_font.render(str(round(self.clock.get_fps())),
                                         True, (255, 255, 255)), [0, 0])
            self.screen.blit(
                self.default_font.render(
                    str('%s, %s' %
                        (self.Player.player_r.x, self.Player.player_r.y)),
                    True, (255, 255, 255)), [0, 12])
            self.screen.blit(
                self.default_font.render(str(pygame.mouse.get_pos()), True,
                                         (255, 255, 255)), [0, 24])
        if self.RECT_DEBUG:
            ps = pygame.Surface(self.Player.player_dims)
            ps.fill([255, 0, 0])
            self.screen.blit(
                ps, self.off([self.Player.player_r.x, self.Player.player_r.y]))
        #Draws player and head text if it exists
        if self.Player.head_drawn:
            if self.Player.head_drawn[3]:
                self.screen.blit(self.Player.head_drawn[0],
                                 self.Player.head_drawn[1])
            else:
                self.Player.game.screen.blit(
                    self.Player.head_drawn[0],
                    self.off(self.Player.head_drawn[1]))
        self.ParticleManager.update()
        if self.Player.map_change:
            self.HUD.updateMapTrans()
        self.HUD.blitHUD()
Exemple #32
0
def core_game_loop(DISPLAYSURF, DISPLAYWIDTH, DISPLAYHEIGHT):

    ranlevel = randint(1, 2)
    if ranlevel == 1:
        lvl_type_choice = "t"
    if ranlevel == 2:
        lvl_type_choice = "f"

    if lvl_type_choice == "t":
        t_or_f_level = 1
        scroll_speed = 140
    if lvl_type_choice == "f":
        t_or_f_level = 2
        scroll_speed = 210

    tile_list = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    minion_list = []
    striker_list = []
    turret_list = []
    player_list = []

    minion_kill_list = []
    striker_kill_list = []
    turret_kill_list = []
    player_kill_list = []

    wait_control = 0
    calc_control = 1
    level_end_in = LEVEL_LENGTH_CONTROL * 60

    tile_make_in = 0
    minion_make_in = 0
    striker_make_in = 0
    turret_make_in = 0
    asteroid_make_in = 0

    minion_make_in_max = 5 * 60
    striker_make_in_max = 3 * 60
    turret_make_in_max = 4 * 60

    minions_killed = 0
    strikers_killed = 0
    turrets_killed = 0
    asteroids_killed = 0

    if lvl_type_choice == "t":
        tile_make_in_max = 60
        tile_list_clear_max = 600
        pcmaxhp = 150
        pccurhp = 150
    if lvl_type_choice == "f":
        tile_make_in_max = 43
        tile_list_clear_max = 430
        ## For some reason this is the number needed to make the tiles line up.
        pcmaxhp = 80
        pccurhp = 80
    tile_num = 11
    print(lvl_type_choice)

    start_tile1 = tileFactory(scroll_speed, t_or_f_level, 1, 0)
    start_tile2 = tileFactory(scroll_speed, t_or_f_level, 1, 140)
    start_tile3 = tileFactory(scroll_speed, t_or_f_level, 1, 280)
    start_tile4 = tileFactory(scroll_speed, t_or_f_level, 1, 420)
    start_tile5 = tileFactory(scroll_speed, t_or_f_level, 1, 560)
    start_tile6 = tileFactory(scroll_speed, t_or_f_level, 1, 700)
    start_tile7 = tileFactory(scroll_speed, t_or_f_level, 1, 840)
    start_tile8 = tileFactory(scroll_speed, t_or_f_level, 1, 980)
    start_tile9 = tileFactory(scroll_speed, t_or_f_level, 1, 1120)
    start_tile10 = tileFactory(scroll_speed, t_or_f_level, 1, 1260)

    past_row = 1
    prev_row = 1
    cur_row = 1
    if t_or_f_level == 1:
        temp_row = tile_gen_tank(past_row, prev_row, cur_row)
    if t_or_f_level == 2:
        temp_row = tile_gen_fight(past_row, prev_row, cur_row)
    cur_row = temp_row
    start_tile11 = tileFactory(scroll_speed, t_or_f_level, temp_row)

    tile_list[0] = start_tile1
    tile_list[1] = start_tile2
    tile_list[2] = start_tile3
    tile_list[3] = start_tile4
    tile_list[4] = start_tile5
    tile_list[5] = start_tile6
    tile_list[6] = start_tile7
    tile_list[7] = start_tile8
    tile_list[8] = start_tile9
    tile_list[9] = start_tile10
    tile_list[10] = start_tile11

    timer_font = pygame.font.Font("Fixedsys.ttf", 30)

    HUD_display = HUD(DISPLAYSURF, DISPLAYWIDTH, DISPLAYHEIGHT, timer_font,
                      pcmaxhp)
    great_asteroid = asteroidTestClass(
        (randint(8, 12) * 300, randint(70, 440)), DISPLAYHEIGHT)

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

        if wait_control == 0 or wait_control == 1:
            wait_amount = 17
            wait_control += 1
        else:
            wait_amount = 16
            wait_control = 0

        if calc_control == 1 or calc_control == 2 or calc_control == 3:
            wait_amount = wait_amount - 4
        if calc_control == 4:
            wait_amount = wait_amount - 3
        if calc_control == 5:
            wait_amount = wait_amount - 3
            calc_control = 0

        pygame.time.wait(wait_amount)
        calc_control += 1

        if tile_make_in == tile_make_in_max:
            if level_end_in <= 600 and lvl_type_choice == "t":
                tile_list.append(0)
                tile_list[tile_num] = tileFactory(scroll_speed, t_or_f_level,
                                                  1)
                temp_list = []
                for index in range(len(tile_list) - 1):
                    temp_list.append(tile_list[index + 1])
                tile_list = temp_list
                tile_make_in = 0
            ## Tells the loop to generate tiles only on row 1 as the level will
            ## end in ten seconds.
            elif level_end_in > 600:
                if t_or_f_level == 1:
                    temp_row = tile_gen_tank(past_row, prev_row, cur_row)
                if t_or_f_level == 2:
                    temp_row = tile_gen_fight(past_row, prev_row, cur_row)
                past_row = prev_row
                prev_row = cur_row
                cur_row = temp_row
                tile_list.append(0)
                tile_list[tile_num] = tileFactory(scroll_speed, t_or_f_level,
                                                  temp_row)
                temp_list = []
                for index in range(len(tile_list) - 1):
                    temp_list.append(tile_list[index + 1])
                    ## Change "index + 1" into "len(tile_list) - 1" for a
                    ## hilarious bug.
                tile_list = temp_list
                tile_make_in = 0
                if turret_make_in >= turret_make_in_max and level_end_in > 600:
                    turret_gen(turret_list, turret_kill_list, temp_row,
                               t_or_f_level)
                    turret_make_in = 0
            elif level_end_in <= 600 and lvl_type_choice == "f":
                temp_list = []
                for index in range(len(tile_list) - 1):
                    temp_list.append(tile_list[index + 1])
            ## Tells the loop to stop generating tiles if it's a fighter level,
            ## since the level will end in ten seconds.

        if minion_make_in == minion_make_in_max and level_end_in > 600:
            minion_gen(minion_list, minion_kill_list, DISPLAYWIDTH,
                       DISPLAYHEIGHT)
            minion_make_in = 0
        if striker_make_in == striker_make_in_max and level_end_in > 600:
            striker_gen(striker_list, striker_kill_list, DISPLAYWIDTH,
                        DISPLAYHEIGHT)
            striker_make_in = 0

        ## Generate enemies here and supply classes with their indicies.

        tile_make_in += 1
        minion_make_in += 1
        striker_make_in += 1
        turret_make_in += 1
        level_end_in -= 1

        if len(minion_list) > 0:
            for x in range(len(minion_list)):
                minion_list[x].index_update(x)
                minion_list[x].pos_change()
        if len(striker_list) > 0:
            for x in range(len(striker_list)):
                striker_list[x].index_update(x)
                striker_list[x].pos_change()
        if len(turret_list) > 0:
            for x in range(len(turret_list)):
                turret_list[x].index_update(x)
                turret_list[x].pos_change()
        great_asteroid.pos_change()

        ## check for collision and enemy death here

        if len(minion_kill_list) > 0:
            for index in minion_kill_list:
                DISPLAYSURF.blit(minion_list[index].MINSURF,
                                 (DISPLAYWIDTH + 1, DISPLAYHEIGHT + 1))
                minion_list[index] = 0
            minion_kill_list = []

        if len(striker_kill_list) > 0:
            for index in striker_kill_list:
                DISPLAYSURF.blit(striker_list[index].STRISURF,
                                 (DISPLAYWIDTH + 1, DISPLAYHEIGHT + 1))
                striker_list[index] = 0
            striker_kill_list = []

        if len(turret_kill_list) > 0:
            for index in turret_kill_list:
                DISPLAYSURF.blit(turret_list[index].TURSURF,
                                 (DISPLAYWIDTH + 1, DISPLAYHEIGHT + 1))
                turret_list[index] = 0
            turret_kill_list = []

        ## Removes a sprite class from their sprite list at the index stored in
        ## their kill list (which should always be accurate at this point) and
        ## replaces it with a 0. (Does not directly remove them from the list
        ## as that would make the rest of the indicies in the kill list
        ## inaccurate due to list length being changed.)
        ##
        ## The DISPLAYSURF.blit is strictly for moving them offscreen first
        ## so they don't remain and interact with other entites. Will not work
        ## at this moment.

##        for minion in minion_list:
##            minion.update()
##        for striker in striker_list:
##            striker.update()
##        for turret in turret_list:
##            turret.update()

        if 0 in minion_list:
            temp_list = []
            for x in range(len(minion_list)):
                if not minion_list[x] == 0:
                    temp_list.append(minion_list[x])
            minion_list = temp_list
            for x in range(len(minion_list)):
                minion_list[x].index_update(x)

        if 0 in striker_list:
            temp_list = []
            for x in range(len(striker_list)):
                if not striker_list[x] == 0:
                    temp_list.append(striker_list[x])
            striker_list = temp_list
            for x in range(len(striker_list)):
                striker_list[x].index_update(x)

        if 0 in turret_list:
            temp_list = []
            for x in range(len(turret_list)):
                if not turret_list[x] == 0:
                    temp_list.append(turret_list[x])
            turret_list = temp_list
            for x in range(len(turret_list)):
                turret_list[x].index_update(x)

        for tile in tile_list:
            tile.pos_change()
        DISPLAYSURF.fill(BLACK)
        for tile in tile_list:
            DISPLAYSURF.blit(tile.TILESURF, tile.pos)
        for minion in minion_list:
            DISPLAYSURF.blit(minion.MINSURF, minion.pos)
        for striker in striker_list:
            DISPLAYSURF.blit(striker.STRISURF, striker.pos)
        for turret in turret_list:
            DISPLAYSURF.blit(turret.TURSURF, turret.pos)
        DISPLAYSURF.blit(great_asteroid.ASTSURF, great_asteroid.pos)
        HUD_display.timer_display(level_end_in)
        HUD_display.health_display(pccurhp)

        if level_end_in % 60 == 0:
            if pccurhp > 0:
                pccurhp -= 1

        if level_end_in == 0:
            level_end(DISPLAYSURF, DISPLAYWIDTH, DISPLAYHEIGHT, tile_list,
                      lvl_type_choice, minions_killed, strikers_killed,
                      turrets_killed, asteroids_killed)

        pygame.display.update()
class Necro():
    def __init__(self):
        #window setup
        pygame.display.set_caption('Necromonster')
        pygame.display.set_icon(pygame.image.load(os.path.join('rec', 'misc', 'icon.png')))
        self.main_path = os.getcwd()

        # initiate the clock and screen
        self.clock = pygame.time.Clock()
        self.last_tick = pygame.time.get_ticks()
        self.screen_res = [900, 650]
        self.center_point = [470., 350.]
        self.screen = pygame.display.set_mode(self.screen_res, pygame.HWSURFACE, 32)

        #DEBUG values
        self.DEBUG = 1
        self.RECT_DEBUG = 0

        #Init custom game classe(s)
        self.EntityHandler = EntityHandler(self)
        self.Scheduler = Schedule(self)
        self.Projectile = Projectile
        self.Monster = Monster
        self.Item = Item
        self.Invent = Invent(self)
        self.Weapon = Weapon
        self.Garment = Garment
        self.Player = Player(self)
        self.HUD = HUD(self)

        # Init entity manager vars
        self.entities = []

        # load fonts, create font list
        self.text_list = []
        self.default_font = pygame.font.SysFont(None, 20)

        # get the map that you are on
        self.blit_list = mapLoader.load('home', self)

        self.Item(self, 'Mythril', [350, 400], world=1)

        while 1:
            self.Loop()

    def Loop(self):
        # main game loop
        self.eventLoop()
        if pygame.time.get_ticks() - self.last_tick > 20:
            self.Tick()
            self.Draw()
        pygame.display.update()

    def eventLoop(self):
        # the main event loop, detects keypresses
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN:
                if not self.HUD.chat_active:
                    if event.key == K_e:
                        self.Invent.toggleView()
                    if event.key == K_t:
                        #activate the chat bar
                        self.HUD.chat_message = ''
                        self.HUD.chat_active = 1
                        self.Player.can_move = 0
                        return 0
                if event.key == K_ESCAPE or event.key == K_RETURN:
                    message = self.HUD.chat_message.split()
                    if len(message) >1:
                        if len(message) > 2:
                           self.HUD.command(message[0], message[1], message[2])
                        else:
                            self.HUD.command(message[0], message[1])
                    self.HUD.chat_active = 0
                    self.Player.can_move = 1
                    self.HUD.chat_message = ''
                elif event.key == K_BACKSPACE:
                    self.HUD.chat_message = self.HUD.chat_message[:-1]
                elif event.key <= 255:
                    char = chr(event.key)
                    if self.keys_pressed[K_LSHIFT] or self.keys_pressed[K_RSHIFT]:
                        char = char.upper()
                
                    
                        
                    
                    self.HUD.chat_message += char
            elif event.type == MOUSEBUTTONDOWN:
                if self.Invent.in_hand:
                    self.Invent.testThrow(pygame.mouse.get_pos())
                if self.Invent.shown:
                    self.Invent.inventClick(pygame.mouse.get_pos())
                elif pygame.mouse.get_pressed()[0]:
                    self.Player.attack(pygame.mouse.get_pos())

    def Tick(self):
        # updates to player location and animation frame
        ttime = self.clock.tick()
        self.keys_pressed = pygame.key.get_pressed()
        self.Scheduler.update()
        self.EntityHandler.updateAll(ttime)
        self.Invent.update()
        for index, text in enumerate(self.text_list):
            if text[2]:
                raise DeprecationWarning
        self.last_tick = pygame.time.get_ticks()

    def off(self, coords):
        newx = coords[0] - self.Player.player_r.x + 450
        newy = coords[1] - self.Player.player_r.y + 325
        return [newx, newy]

    def Draw(self):
        #Responsible for calling all functions that draw to the screen
        tile_width = self.tile[1][0]
        tile_height = self.tile[1][1]
        tile_extrax = self.Player.player_r.x % tile_width
        tile_extray = self.Player.player_r.y % tile_height
        y = 0

        for i in xrange(self.screen_res[1] / tile_height + 3):
            for i in xrange(self.screen_res[0] / tile_width + 3):
                self.screen.blit(self.tile[0], [i * tile_width - tile_width - tile_extrax, y - tile_height - tile_extray])
            y += self.tile[1][1]
        for surf in self.blit_list:
            if 'player' in surf:
                self.EntityHandler.blitAll()
            else:
                self.screen.blit(surf[0], self.off(surf[1]))
        for text in self.text_list:
            self.screen.blit(text[0], text[1])
        if self.Invent.shown:
            self.Invent.draw()
        if self.DEBUG:
            self.screen.blit(self.default_font.render(str(round(self.clock.get_fps())), True, (255, 255, 255)), [0, 0])
            self.screen.blit(self.default_font.render(str('%s, %s' % (self.Player.player_r.x, self.Player.player_r.y)), True, (255, 255, 255)), [0, 12])
            self.screen.blit(self.default_font.render(str(pygame.mouse.get_pos()), True, (255, 255, 255)), [0, 24])
        if self.RECT_DEBUG:
            ps = pygame.Surface(self.Player.player_dims)
            ps.fill([255, 0, 0])
            self.screen.blit(ps, self.off([self.Player.player_r.x, self.Player.player_r.y]))
        self.HUD.blitHUD()
class Necro():
    def __init__(self):
        #window setup
        pygame.display.set_caption('Necromonster')
        path = ['rec', 'misc', 'icon.png']
        os.path.sep.join(path)
        pygame.display.set_icon(pygame.image.load(os.path.sep.join(path)))
        #pygame.display.set_icon(pygame.image.load('rec\\misc\\icon.png'))
        self.main_path = os.getcwd()

        # initiate the clock and screen
        self.clock = pygame.time.Clock()
        self.last_tick = pygame.time.get_ticks()
        self.screen_res = [900, 650]
        self.screen = pygame.display.set_mode(self.screen_res, pygame.HWSURFACE, 32)
        self.DEBUG = 1

        #Init custom game classes
        self.Player = Player(self)
        self.Monsters = Monster(self)
        self.ItemHandler = Item(self)
        self.Invent = Invent(self)
        self.HUD = HUD(self)

        # load fonts, create font list
        self.text_list = []
        self.default_font = pygame.font.SysFont(None, 20)

        # get the map that you are on
        self.blit_list = mapLoader.load('home', self)

        self.Monsters.create('goop', [300, 300], 2, 'neutral')

        while 1:
            self.Loop()

    def Loop(self):
        # main game loop
        self.eventLoop()
        if pygame.time.get_ticks() - self.last_tick > 20:
            self.Tick()
            self.Draw()
        pygame.display.update()

    def eventLoop(self):
        # the main event loop, detects keypresses
        for event in pygame.event.get():
            if event.type == QUIT:
                sys.exit()
            elif event.type == KEYDOWN:
                if event.key == K_e:
                    self.Invent.toggleView()
            elif event.type == MOUSEBUTTONDOWN:
                if self.Invent.in_hand:
                    self.Invent.testThrow(pygame.mouse.get_pos())
                if self.Invent.shown:
                    self.Invent.inventClick(pygame.mouse.get_pos())

    def Tick(self):
        # updates to player location and animation frame
        self.keys_pressed = pygame.key.get_pressed()
        self.clock.tick()
        self.Player.update()
        self.Monsters.update()
        self.ItemHandler.update()
        self.Invent.update()
        for index, text in enumerate(self.text_list):
            if text[2] < time():
                self.text_list.pop(index)

        self.last_tick = pygame.time.get_ticks()

    def off(self, coords):
        newx = coords[0] - self.Player.player_r.x + 450
        newy = coords[1] - self.Player.player_r.y + 325
        return [newx, newy]

    def Draw(self):
        #Responsible for calling all functions that draw to the screen
        tile_width = self.tile[1][0]
        tile_height = self.tile[1][1]
        tile_extrax = self.Player.player_r.x % tile_width
        tile_extray = self.Player.player_r.y % tile_height
        y = 0

        for i in xrange(self.screen_res[1] / tile_height + 3):
            for i in xrange(self.screen_res[0] / tile_width + 3):
                self.screen.blit(self.tile[0], [i * tile_width - tile_width - tile_extrax, y - tile_height - tile_extray])
            y += self.tile[1][1]
        for surf in self.blit_list:
            if 'player' in surf:
                self.Player.blitPlayer()
                self.Monsters.blitMonsters()
            else:
                self.screen.blit(surf[0], self.off(surf[1]))
        for text in self.text_list:
            self.screen.blit(text[0], text[1])
        self.ItemHandler.blitItems()
        if self.Invent.shown:
            self.Invent.draw()
        if self.DEBUG:
            self.screen.blit(self.default_font.render(str(round(self.clock.get_fps())), True, (255, 255, 255)), [0, 0])
            self.screen.blit(self.default_font.render(str('%s, %s' % (self.Player.player_r.x, self.Player.player_r.y)), True, (255, 255, 255)), [0, 12])
            self.screen.blit(self.default_font.render(str(pygame.mouse.get_pos()), True, (255, 255, 255)), [0, 24])
        self.HUD.blitHUD()
Exemple #35
0
#Ejemplo de como usar HUD en otro script
import time
from HUD import HUD
HUD.thread_start()

def run_app():
    while HUD.execution_thread.is_alive():
        #Actualizo la hora cada 0.1 seg    
        t = time.localtime()
        #time_formated = f"{t.tm_year}/{t.tm_mon}/{t.tm_mday} - {t.tm_hour}:{t.tm_min}:{t.tm_sec}"
        time_formated = {
            "año": t.tm_year,
            "mes": t.tm_mon,
            "dia": t.tm_mday,
            "hora": t.tm_hour,
            "min": t.tm_min,
            "sec": t.tm_sec
        }
        print(time_formated)
        HUD.update_label(time_formated)

        #Actualizo el texto:
        #Para darle color a una linea debo agregar la key f"{key_origina}_color"
        time_formated = {
            "año": t.tm_year,
            "mes": t.tm_mon,
            "dia": t.tm_mday,
            "hora": t.tm_hour,
            "min": t.tm_min,
            "sec": t.tm_sec,
            "año_color": "green",
Exemple #36
0
class Map:
    def __init__(self, width, height):
        self.windowWidth = width
        self.windowHeight = height
        self.widthNumber = 0
        self.heightNumber = 0

        self.map = []  # Contains all the cells that make up the map
        self.path = [
        ]  # Ordered list of cells that make up the path for the enemies
        self.walls = []  # List containing all the cells that make up the walls
        self.enemies = []  # List of all enemies currently on the field
        self.level = 0  # Incrementing level variable, increases difficulty
        self.towers = []  # List of all towers currently on the map
        self.bullets = []  # List of all bullets

        self.start = 0
        self.end = 0
        self.startCell = None
        self.endCell = None

        self.hud = HUD(width, height)

    def createEnemy(self):
        enemy1 = Enemy(0, 0, self.path)
        self.enemies.append(enemy1)

    def createTower(self, cell, id):
        if (cell.id is 1):
            # The cell is a wall so create the tower
            tower1 = Tower(cell, id)
            self.towers.append(tower1)
        else:
            # The cell is not a tower, so don't create it
            print("Error: Can only build towers on a wall")

    # Generate a map of cells
    # widthNo - the number of cells in width
    # height - the number of cells in height
    # fills self.map and self.path
    def generateMap(self, widthNo, heightNo):
        # Create random start and end points
        self.widthNumber = widthNo
        self.heightNumber = heightNo

        bottomBarHeight = 100
        cellWidth = round(self.windowWidth / widthNo)
        cellHeight = round((self.windowHeight - bottomBarHeight) / heightNo)

        # Create a map of wall cells
        for i in range(0, heightNo):

            for j in range(0, widthNo):
                color = [0, 0, 0]  # HSV Array containing the cell color
                randomInt = random.randint(1, 30)
                color[0] = randomInt
                color[1] = randomInt
                color[2] = randomInt

                newCell = Cell(j * cellWidth, i * cellHeight, cellWidth,
                               cellHeight, 0, color)
                # find all the neighbors of the cell

                self.map.append(newCell)

        self.findNeighbors()

        # Defining the start and end cells
        # Start cell, top left quarter of map
        # End cell, bottom right quarter of map
        self.start = [
            random.randint(0, round(widthNo / 4)),
            random.randint(0, round(heightNo / 4))
        ]
        self.end = [
            random.randint(round(3 * widthNo / 4), widthNo),
            random.randint(round(3 * heightNo / 4), heightNo)
        ]
        # print("This is start: " + str(self.start))
        # print("This is end: " + str(self.end))

        startPosition = [
            self.start[0] * self.map[0].width,
            self.start[1] * self.map[0].height
        ]
        self.startCell = self.findCursorCell(startPosition)

        endPosition = [
            self.end[0] * self.map[0].width, self.end[1] * self.map[0].height
        ]
        self.endCell = self.findCursorCell(endPosition)

        # Debugging print statement in order to print out the current map
        # self.printArrayCellContents()

    # Create a path from the start to the end, make the path a little interesting
    def generatePath(self, widthNo, heightNo):
        path = []  # contains all the cells that make up the path

        # Create multiple different waypoints and connect them with paths
        # Waypoint for the top right quarter
        waypoint1 = [
            random.randint(round(widthNo / 4), round(3 * widthNo / 4)),
            random.randint(0, round(heightNo / 2))
        ]
        # Waypoint for the bottom left corner
        waypoint2 = [
            random.randint(0, round(widthNo / 2)),
            random.randint(round(heightNo / 4), round(3 * heightNo / 4))
        ]

        way1Position = [
            waypoint1[0] * self.map[0].width, waypoint1[1] * self.map[0].height
        ]
        self.waypoint1Cell = self.findCursorCell(way1Position)

        way2Position = [
            waypoint2[0] * self.map[0].width, waypoint2[1] * self.map[0].height
        ]
        self.waypoint2Cell = self.findCursorCell(way2Position)

        self.waypoint1Cell.id = 2
        self.waypoint2Cell.id = 2

        self.waypoint1Cell.redoColor()
        self.waypoint2Cell.redoColor()

        path1 = self.greedyBFS(self.startCell, self.waypoint1Cell)
        path2 = self.greedyBFS(self.waypoint1Cell, self.waypoint2Cell)
        path3 = self.greedyBFS(self.waypoint2Cell, self.endCell)

        for cell in path1:
            path.append(cell)
        for cell in path2:
            path.append(cell)
        for cell in path3:
            path.append(cell)

        # Find the corresponding waypoint cells
        for cell in path:
            # Update the cell ids in the path
            cell.id = 2
            cell.redoColor()

        self.path = path
        self.generateWall()
        self.createEnemy()

        self.createTower(self.walls[0], 0)

    def greedyBFS(self, startCell, endCell):
        evaluated = []

        # HEAP
        # stores tuples
        #   FIRST - fCost of the cell
        #   SECOND - cell itself
        notEvaluated = []  # Keep this as a heap with heapify
        notEvaluatedCheck = [
        ]  # Array to make sure everything stays on the same page

        # Dictionary containing the path
        previousCells = []

        # Calculate the euclidian distance to the cell
        startFCost = startCell.calcDistance(endCell)

        heapq.heappush(notEvaluated, (startFCost, startCell))
        notEvaluatedCheck.append(startCell)

        while not len(notEvaluatedCheck) <= 0:
            heapq.heapify(notEvaluated)
            currentCell = heapq.heappop(notEvaluated)[1]
            notEvaluatedCheck.remove(currentCell)

            if currentCell.isSameLocation(endCell):
                # print("Found a path")
                return previousCells

            # print("Iterated")
            evaluated.append(currentCell)
            previousCells.append(currentCell)

            for neighbor in currentCell.neighbors:

                if neighbor in evaluated or neighbor is None:
                    continue

                if not notEvaluatedCheck.__contains__(neighbor):
                    neighborFCost = neighbor.calcDistance(endCell)
                    heapq.heappush(notEvaluated, (neighborFCost, neighbor))
                    notEvaluatedCheck.append(neighbor)
                    # print("Neighbor added" + str(len(notEvaluatedCheck)))

        print("\n\nPATH NOT FOUND\n\n")

    def printArrayCellContents(self):

        for cell in self.map:
            print("X: " + str(cell.x))
            print("Y: " + str(cell.y))
            print("width: " + str(cell.width))
            print("height: " + str(cell.height))
            print("id: " + str(cell.id))
            print("color: " + str(cell.color))

    # find all the neighbors of a cell
    # cell - the cell of which the neighbors need to be found
    # @return - an array of all the neighbors
    def findNeighbors(self):

        map = self.map

        for i in range(0, len(map)):
            neighbors = []

            # Check the upper
            if i - self.widthNumber > 0:
                neighbors.append(map[i - self.widthNumber])
            else:
                neighbors.append(None)

            # Check the lower
            if i + self.widthNumber < (self.widthNumber * self.heightNumber):
                neighbors.append(map[i + self.widthNumber])
            else:
                neighbors.append(None)

            # Check the left
            if ((i) % self.widthNumber) is not 0 and i - 1 > 0:
                neighbors.append(map[i - 1])
            else:
                neighbors.append(None)

            # Check the right
            if i + 1 < (self.widthNumber * self.heightNumber) and (
                (i + 1) % self.widthNumber) is not 0:
                neighbors.append(map[i + 1])
            else:
                neighbors.append(None)

            map[i].neighbors = neighbors

    # Designate a certain number of empty cells along the path as walls which can house buildings
    def generateWall(self):
        numberPath = []
        self.walls = []

        for cell in self.path:
            numberOfWalls = random.randint(0,
                                           2)  # Create between 0 and 2 walls
            numberPath.append(numberOfWalls)

        for i in range(0, len(self.path)):
            cell = self.path[i]
            neighbors = cell.neighbors
            limitWalls = numberPath[i]
            currentWalls = 0
            for i in range(0, len(neighbors)):
                neighborCell = neighbors[i]
                if limitWalls <= currentWalls:
                    if neighborCell is not None and not neighborCell.id is 2:
                        neighborCell.id = 1
                        neighborCell.redoColor()
                        self.walls.append(neighborCell)
                        currentWalls = currentWalls + 1

    # Update each enemy position based on where it is in the path
    def update(self, screen, deltaT):

        # Draw the hud on the screen
        self.hud.drawHUD(screen)

        for tower in self.towers:
            tower.drawTower(screen)

            # Update the tower and bullets
            tower.updateTower(screen, self.enemies, self.path,
                              self.windowWidth, self.windowHeight, deltaT)

        for enemy in self.enemies:
            enemy.updatePosition()
            enemy.drawEnemy(screen)

            if enemy.goalReached:
                # The enemy has arrived at the goal
                self.enemies.remove(enemy)
                self.hud.baseHealth -= 1

    # Find the closest cell based on a position entered
    def findCursorCell(self, position):
        maxDistance = 1000000000
        xCur = position[0] - (self.windowWidth / self.widthNumber) / 2
        yCur = position[1] - (self.windowHeight / self.heightNumber) / 2
        closestCell = self.map[0]

        for i in range(0, len(self.map)):
            cell = self.map[i]
            x = (cell.x)
            y = (cell.y)
            # print("Mouse x: " + str(xCur))
            # print("Mouse x: " + str(yCur))
            # print("Cell x: " + str(x))
            # print("Cell y: " + str(y))
            distance = math.sqrt((x - xCur)**2 + (y - yCur)**2)
            # print("Distance: " + str(distance))

            if (distance <= maxDistance):
                # print("Mouse x: " + str(xCur))
                # print("Mouse x: " + str(yCur))
                # print("Cell x: " + str(x))
                # print("Cell y: " + str(y))
                # print("distance: " + str(distance))
                maxDistance = distance
                closestCell = cell

        return closestCell
Exemple #37
0
class Necro():
    def __init__(self):
        """
        Main game class initialization. All other class references point to this class as "game"
        """
        # window setup
        pygame.display.set_caption('Necromonster')
        pygame.display.set_icon(pygame.image.load(os.path.join('rec', 'misc', 'icon.png')))
        self.main_path = os.getcwd()

        # initiate the clock and screen object
        self.clock = pygame.time.Clock()
        self.FPS = 50
        self.last_tick = pygame.time.get_ticks()
        self.screen_res = [900, 650]
        self.center_point = [470, 350]
        self.screen = pygame.display.set_mode(self.screen_res, pygame.HWSURFACE, 32)

        #DEBUG values
        self.DEBUG = 1
        self.RECT_DEBUG = 0
        self.angle = 0

        #Init and assign custom game class(es)
        self.EntityHandler = EntityHandler(self)
        self.ParticleManager = ParticleManager(self)
        self.Scheduler = Schedule(self)
        self.Entity = Entity
        self.Projectile = Projectile
        self.Monster = Monster
        self.NPC = NPC
        self.NPCText = NPCText
        self.Item = Item
        self.Inventory = Invent
        self.Invent = self.Inventory(self)
        self.Weapon = Weapon
        self.Garment = Garment
        self.Player = Player(self)
        self.HUD = HUD(self)

        # Init entity manager vars
        self.entities = []
        self.shadows = []

        # load fonts, create font list
        # do not use pygame.font.SysFont!
        self.text_list = []
        self.default_font = pygame.font.Font(os.path.join('rec', 'font', 'freesansbold.ttf'), 15)
        self.speak_font = pygame.font.Font(os.path.join('rec', 'font', 'freesansbold.ttf'), 30)

        # load the map that player is on
        self.INSIDE = 0
        self.blit_list = mapLoader.load('home', self)

        # spawn initial map items/entities
        self.Item(self, 'Mythril', [350, 400], world=1)
        self.NPC(self, "blacksmith", [400, 400], 100, 'still')
        for i in xrange(4):
            self.Monster(self, 'chicken', [200+(i*50),650], 1, 'neutral')
        self.Monster(self, "goop", [100, 100], 1, 'aggressive')

        # begin main game loop
        while 1:
            self.Loop()

    def Loop(self):
        """
        Main loop of the game. Calls tick, draw, and event processing
        functions. Tick and draw are only called every 20 milliseconds
        """
        self.eventLoop()
        self.Tick()
        self.Draw()
        pygame.display.update()

    def eventLoop(self):
        """
        Uses pygame event handling to process keypresses and mouse clicks.
        Used for chat, interacting with objects, and inventory management
        """
        for event in pygame.event.get():
            event # prevents exit button freeze up
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN:
                # toggle chat bar active
                if not self.HUD.chat_active:
                    if event.key == K_e:
                        self.Invent.toggleView()
                    if event.key == K_t:
                        #activate the chat bar
                        self.HUD.chat_message = ''
                        self.HUD.chat_active = 1
                        self.Player.can_move = 0
                        return 0
                # process chat messages. Remove or add characters while chat box is open
                if event.key == K_ESCAPE or event.key == K_RETURN:
                    self.HUD.processCommand(self.HUD.chat_message)
                    self.HUD.chat_active = 0
                    self.Player.can_move = 1
                    self.HUD.chat_message = ''
                elif event.key == K_BACKSPACE:
                    self.HUD.chat_message = self.HUD.chat_message[:-1]
                elif event.key <= 255:
                    char = chr(event.key)
                    if self.keys_pressed[K_LSHIFT] or self.keys_pressed[K_RSHIFT]:
                        char = char.upper()
                    self.HUD.chat_message += char
                # interaction with entities on space bar press
                if event.key == K_SPACE:
                    for monster in self.EntityHandler.monsters:
                        if monster.NPC:
                            if monster.isPlayerClose(75) and monster.interacting == False:
                                monster.interacting = True
                            elif not monster.isPlayerClose(75) or monster.interacting == True:
                                monster.interacting = False
                                self.HUD.delPrompt()
            # inventory management, checks for item throws, and placement in slots.
            elif event.type == MOUSEBUTTONDOWN:
                self.Invent.last_click = pygame.mouse.get_pos()
                if self.Invent.in_hand:
                    self.Invent.testThrow(self.Invent.last_click)
                if self.Invent.shown:
                    self.Invent.inventClick(self.Invent.last_click)
                elif pygame.mouse.get_pressed()[0]:
                    self.Player.attack(pygame.mouse.get_pos())

    def Tick(self):
        """
        Updates all game math and entity states. No drawing is done.
        """
        ttime = self.clock.tick(self.FPS)
        self.keys_pressed = pygame.key.get_pressed()
        if self.keys_pressed[K_EQUALS]:
            self.HUD.daytime_start -= 3
        if self.keys_pressed[K_MINUS]:
            self.HUD.daytime_start += 3
        self.Scheduler.update()
        self.EntityHandler.updateAll(ttime)

        self.Invent.update()
        self.HUD.updateDay()
        for index, text in enumerate(self.text_list):
            if text[2]:
                raise DeprecationWarning
        self.last_tick = pygame.time.get_ticks()

    def off(self, coords):
        """
        Offsets image coordinates to appear correct from the view of the player.
        Should be called on all surface coordinates before blitting.
        """
        newx = coords[0] - self.Player.player_r.x + 450
        newy = coords[1] - self.Player.player_r.y + 325
        return [newx, newy]

    def unoff(self, coords):
        """
        Removes the offset created by the off() function.
        """
        newx = coords[0] + self.Player.player_r.x - 450
        newy = coords[1] + self.Player.player_r.y - 325
        return [newx, newy]

    def getCenterBlit(self, surface, pos):
        pos[0] = pos[0] + surface.get_width() / 2
        pos[1] = pos[1] + surface.get_height() / 2
        return pos

    def rotopoint(self, surface, angle, pos):
        size = surface.get_size()
        if pos[0] > size[0]/2 or pos[1] > size[1]/2:
            print 'BIG ASS HONKEY'
        new_surf_size = [(size[0] - pos[0])*2, (size[1] - pos[1])*2]
        new_surf_blit_pos = [new_surf_size[0] - size[0], new_surf_size[1] - size[1]]
        new_surf = pygame.Surface(new_surf_size, pygame.SRCALPHA, 32)
        new_surf.blit(surface, new_surf_blit_pos)
        return pygame.transform.rotate(new_surf, angle)

    def testrot(self, image, angle):
        loc = image.get_rect().center
        new_rot = pygame.transform.rotate(image, angle)
        new_rot.get_rect(center=loc)
        return new_rot, new_rot.get_rect()


    def Draw(self):
        """
        Completes all blitting to the screend object, includes HUD updates.
        """
        tile_width = self.tile[1][0]
        tile_height = self.tile[1][1]
        tile_extrax = self.Player.player_r.x % tile_width
        tile_extray = self.Player.player_r.y % tile_height
        y = 0

        for i in xrange(self.screen_res[1] / tile_height + 3):
            for i in xrange(self.screen_res[0] / tile_width + 3):
                self.screen.blit(self.tile[0], [i * tile_width - tile_width - tile_extrax, y - tile_height - tile_extray])
            y += self.tile[1][1]
        if self.shadows:
            for s in self.shadows:
                s.update(self.screen)
        for surf in self.blit_list:
            if 'player' in surf:
                self.EntityHandler.blitAll()
            else:
                self.screen.blit(surf[0], self.off(surf[1]))
        for text in self.text_list:
            self.screen.blit(text[0], text[1])
        if self.Invent.shown:
            self.Invent.draw()
        if self.DEBUG:
            self.screen.blit(self.default_font.render(str(round(self.clock.get_fps())), True, (255, 255, 255)), [0, 0])
            self.screen.blit(self.default_font.render(str('%s, %s' % (self.Player.player_r.x, self.Player.player_r.y)), True, (255, 255, 255)), [0, 12])
            self.screen.blit(self.default_font.render(str(pygame.mouse.get_pos()), True, (255, 255, 255)), [0, 24])
        if self.RECT_DEBUG:
            ps = pygame.Surface(self.Player.player_dims)
            ps.fill([255, 0, 0])
            self.screen.blit(ps, self.off([self.Player.player_r.x, self.Player.player_r.y]))
        #Draws player and head text if it exists
        if self.Player.head_drawn:
            if self.Player.head_drawn[3]:
                self.screen.blit(self.Player.head_drawn[0], self.Player.head_drawn[1])
            else:
                self.Player.game.screen.blit(self.Player.head_drawn[0], self.off(self.Player.head_drawn[1]))
        self.ParticleManager.update()
        if self.Player.map_change:
            self.HUD.updateMapTrans()
        self.HUD.blitHUD()
Exemple #38
0
'''
Created on 31 Jul 2014

@author: matt
'''
from multiprocessing import Process, Queue

from HUD import HUD

if __name__ == '__main__':
    Q = Queue(100)
    Q.put_nowait(("roll", 30))
    Q.put_nowait(("pitch", 5))
    hud = HUD(simulate=False, master=True, update_queue=Q)
    hud.run_hud()    
Exemple #39
0
    def __init__(self):
        """
        Main game class initialization. All other class references point to this class as "game"
        """
        # window setup
        pygame.display.set_caption('Necromonster')
        pygame.display.set_icon(pygame.image.load(os.path.join('rec', 'misc', 'icon.png')))
        self.main_path = os.getcwd()

        # initiate the clock and screen object
        self.clock = pygame.time.Clock()
        self.FPS = 50
        self.last_tick = pygame.time.get_ticks()
        self.screen_res = [900, 650]
        self.center_point = [470, 350]
        self.screen = pygame.display.set_mode(self.screen_res, pygame.HWSURFACE, 32)

        #DEBUG values
        self.DEBUG = 1
        self.RECT_DEBUG = 0
        self.angle = 0

        #Init and assign custom game class(es)
        self.EntityHandler = EntityHandler(self)
        self.ParticleManager = ParticleManager(self)
        self.Scheduler = Schedule(self)
        self.Entity = Entity
        self.Projectile = Projectile
        self.Monster = Monster
        self.NPC = NPC
        self.NPCText = NPCText
        self.Item = Item
        self.Inventory = Invent
        self.Invent = self.Inventory(self)
        self.Weapon = Weapon
        self.Garment = Garment
        self.Player = Player(self)
        self.HUD = HUD(self)

        # Init entity manager vars
        self.entities = []
        self.shadows = []

        # load fonts, create font list
        # do not use pygame.font.SysFont!
        self.text_list = []
        self.default_font = pygame.font.Font(os.path.join('rec', 'font', 'freesansbold.ttf'), 15)
        self.speak_font = pygame.font.Font(os.path.join('rec', 'font', 'freesansbold.ttf'), 30)

        # load the map that player is on
        self.INSIDE = 0
        self.blit_list = mapLoader.load('home', self)

        # spawn initial map items/entities
        self.Item(self, 'Mythril', [350, 400], world=1)
        self.NPC(self, "blacksmith", [400, 400], 100, 'still')
        for i in xrange(4):
            self.Monster(self, 'chicken', [200+(i*50),650], 1, 'neutral')
        self.Monster(self, "goop", [100, 100], 1, 'aggressive')

        # begin main game loop
        while 1:
            self.Loop()
class MainScreen(Screen):
    """
    The screen where all of the action takes place.
    It consists of a viewport and a HUD
    
    #Attributes:
    @param viewport: A window into the active world.
    @type viewport: L{Viewport}
    
    @param hud: The HUD displays information to the player. It does not contain 
    a debug menu, but does contain resource counts, menus, etc...
    @type hud: L{HUD}
    
    @param clientID: identifying string or number given by the server
    when a client is created
    """
    def __init__(self,clientID):
        Screen.__init__(self)
        self.viewport = None
        self.hud = None
        self.clientID = clientID
    
    def setClientID(self,clientID):
        self.clientID = clientID
        self.viewport.setClientID(clientID)
        self.hud.setClientID(clientID)
    
    def TEST_createViewport(self,world,manager):

        scrollLoc = (0,0)
        viewportPos = (0,0)
        viewportSize = (1024,768)
        testViewport = Viewport(world,manager,scrollLoc,viewportPos,viewportSize,self.clientID)
        self.viewport = testViewport

        self.hud=HUD(manager,self.clientID)
        self.viewport.hud=self.hud
        self.hud.viewport=self.viewport
        
    def draw(self,displaySurface,size):
        self.viewport.draw(displaySurface)
        self.hud.draw(displaySurface)
        
    def processMouseMovedEvent(self,event):
        self.viewport.mouseMoved(event)

    def processMouseClickEvent(self,event):
        self.viewport.clickEvent(event)
    
    def processDragBeganEvent(self,event):
        self.viewport.startDrag(event)
        
    def processDragEvent(self,event):
        self.viewport.continueDrag(event)
    
    def processDragCompletedEvent(self,event):
        self.viewport.completeDrag(event)

    def processAddDragCompletedEvent(self,event):
        self.viewport.completeDrag(event)

    def processNumberKeyPressEvent(self,event):
        if event.state == Event.KeyLocals.UP:
            if event.comboKeys['ctrl']:
                self.viewport.setQuickSelect(event)
            else:
                self.viewport.getQuickSelect(event)
    
    def processCompleteActionEvent(self,event):
        self.viewport.completeActionEvent(event)
        
    def processInitiateActionEvent(self,event):
        self.viewport.initiateActionEvent(event)
        
    def processUpdateEvent(self,event):
        self.viewport.processUpdateEvent(event)
        self.hud.processUpdateEvent(event)
    
    def processGameOverEvent(self,event):
        self.viewport.setGameOver()
    
    def changeWorld(self,world):
        self.viewport.changeWorld(world)
Exemple #41
0
class SpecificWorker(GenericWorker):
    logger_signal = Signal(str, str, str)

    def __init__(self, proxy_map, startup_check=False):
        super(SpecificWorker, self).__init__(proxy_map)

        self.width = 1280
        self.height = 720

        pygame.init()
        pygame.font.init()

        self.display = pygame.display.set_mode(
            (self.width, self.height), pygame.HWSURFACE | pygame.DOUBLEBUF)

        self.camera_manager = CameraManager(self.width, self.height)
        self.gnss_sensor = GNSSSensor()
        self.imu_sensor = IMUSensor()
        self.hud = HUD(self.width, self.height, self.gnss_sensor,
                       self.imu_sensor)
        self.controller = None
        self.clock = pygame.time.Clock()

        data_to_save = {
            'control': [
                'Time', 'Throttle', 'Steer', 'Brake', 'Gear', 'Handbrake',
                'Reverse', 'Manualgear'
            ],
            'communication': ['Time', 'CommunicationTime']
        }
        self.logger = Logger(self.melexlogger_proxy, 'carlaRemoteControl',
                             data_to_save)
        self.logger_signal.connect(self.logger.publish_to_logger)

        self.Period = 0

        self.previousLat = None
        self.previousLong = None

        self.currentLat = None
        self.currentLong = None

        if startup_check:
            self.startup_check()
        else:
            self.timer.timeout.connect(self.compute)
            self.timer.start(self.Period)

    def __del__(self):
        print('SpecificWorker destructor')

    def setParams(self, params):
        try:
            wheel_config = params["wheel"]
            self.controller = DualControl(self.camera_manager, self.hud,
                                          wheel_config,
                                          self.carlavehiclecontrol_proxy)

        except:
            traceback.print_exc()
            print("Error reading config params")
        return True

    @QtCore.Slot()
    def compute(self):
        if not self.previousLat and not self.previousLong:
            self.previousLat = self.gnss_sensor.latitude
            self.previousLong = self.gnss_sensor.longitude

        self.clock.tick_busy_loop(60)
        if self.controller and self.controller.parse_events(self.clock):
            exit(-1)

        if self.controller.car_moved():
            control, elapsed_time = self.controller.publish_vehicle_control()
            control_array = [
                control.throttle, control.steer, control.brake, control.gear,
                control.handbrake, control.reverse, control.manualgear
            ]
            data = ';'.join(map(str, control_array))
            self.logger_signal.emit('control', 'compute', data)
            self.logger_signal.emit('communication', 'compute',
                                    str(elapsed_time))

            self.hud.tick(self, self.clock, control)

            self.currentLat = self.gnss_sensor.latitude
            self.currentLong = self.gnss_sensor.longitude

        if self.currentLong != self.previousLong or self.currentLat != self.currentLat:
            print("\n    CURRENT POS VEHICLE -> LAT: {} , LONG: {}".format(
                self.currentLat, self.currentLong))
            self.previousLat = self.currentLat
            self.previousLong = self.currentLong

        self.camera_manager.render(self.display)
        self.hud.render(self.display)
        pygame.display.flip()

        return True

    def startup_check(self):
        QTimer.singleShot(200, QApplication.instance().quit)

    # =============== Methods for Component SubscribesTo ================
    # ===================================================================

    #
    # SUBSCRIPTION to pushRGBD method from CameraRGBDSimplePub interface
    #
    def CarCameraRGBD_pushRGBD(self, im, dep):
        self.camera_manager.images_received[im.cameraID] = im

    #
    # SUBSCRIPTION to updateSensorGNSS method from CarlaSensors interface
    #
    def CarlaSensors_updateSensorGNSS(self, gnssData):
        self.gnss_sensor.update(gnssData.latitude, gnssData.longitude,
                                gnssData.altitude, gnssData.frame,
                                gnssData.timestamp)

    #
    # SUBSCRIPTION to updateSensorIMU method from CarlaSensors interface
    #
    def CarlaSensors_updateSensorIMU(self, imuData):
        self.imu_sensor.update(imuData.accelerometer, imuData.gyroscope,
                               imuData.compass, imuData.frame,
                               imuData.timestamp)
Exemple #42
0
    def run(self):
        """
        Runs the game.

        @return: Exit status. Signals what screen comes next.
        """
        self.music.fadeout(1000)
        self.music.load(self.music.game)
        self.music.play(-1)

        pygame.mouse.set_visible(False)
        self.background = pygame.Surface(self.screen.get_size())
        self.background.fill((0, 0, 0))
        self.screen.blit(self.background, (0, 0))

        # Game objects.
        cursor = Reticule(self.screen)
        player = Player(self.screen, self.DEBUG)
        playerSonar = PlayerSonar(self.screen, player)
        self.sonarList.add(playerSonar)
        gun = GunHandler(self.screen, player, self.sfx, self.DEBUG)
        hud = HUD(self.screen, player, self.clock, gun)
        playerHealth = PlayerHealth(self.screen, player)

        # Sprite Lists.
        self.playerList.add(player)
        self.hudList.add(playerHealth)
        self.hudList.add(cursor)
        self.hudList.add(hud)

        # Main game loop.
        while (player.health > 0):
            self.clock.tick(self.FPS)
            self.addEnemies(player)

            pygame.time.wait(5)

            for event in pygame.event.get():

                # Close the window.
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit(0)

                # Keyboard input.
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        pygame.quit()
                        sys.exit(0)
                    elif event.key == pygame.K_1:
                        gun.setGun(gun.k_pistol)
                    elif event.key == pygame.K_2:
                        gun.setGun(gun.k_shotgun)
                    elif event.key == pygame.K_3:
                        gun.setGun(gun.k_smg)
                pygame.event.clear()

            # Mouse Button Press.
            self.handleMouse(player, gun)

            # Update Sprite Lists.
            self.handleCollisions(player)
            self.handleSonar(player)
            self.updateScreen()

        if not self.DEBUG:
            self.addScore(player.score)

        return 2
Exemple #43
0
 def __init__(self, size):
     self.hud = HUD(size)