def __init__(self, controller):
        """
        Game initialization: 1024x768 screen for now
        """
        self.controller = controller
        gui.Container.__init__(self, width=1024, height=704)

        # Initialize screen components: Title Menu
        self.title_menu = gui.TextArea(value="Asteroid Miner", width=152, height=36, focusable=False)

        self.base_station_button = gui.Button(
            "Returning to Base Station", width=152, height=36
        )  # , background=(208, 208, 208))
        self.notify_value = "NOTIFY"
        self.notification_zone = gui.TextArea(value=self.notify_value, width=256, height=36, focusable=False)
        self.fuel_button = gui.Button("Buying Fuel", width=152, height=36)

        self.quit_button = gui.Button("Quit", width=96, height=36)

        # Initialize screen components: Gameplay Canvas
        self.lander = PhysicsEngine(0, 36, 1024, 524)

        # Initialize screen components: Lander Readouts
        self.altitude_readout = gui.TextArea(value="Altitude = 800 m", width=256, height=20, focusable=False)
        self.horizontal_speed_readout = gui.TextArea(
            value="Horizontal Speed: 0.0 km/s", width=256, height=20, focusable=False
        )  # , color=(255, 0, 0))
        self.vertical_speed_readout = gui.TextArea(
            value="Vertical Speed: 0.0 km/s", width=256, height=20, focusable=False
        )
        self.fuel_level_readout = gui.TextArea(
            value="Fuel: 1000.00 L", width=256, height=20, focusable=False
        )  # TODO From Message
        self.fuel_level = 1000.00

        # Position top menu
        self.add(self.title_menu, 0, 0)
        self.add(self.base_station_button, 360, 0)
        self.add(self.fuel_button, 512, 0)
        self.add(self.quit_button, 928, 0)

        # Position canvas and game readouts
        self.add(self.notification_zone, 768, 36)
        self.add(self.altitude_readout, 0, 562)
        self.add(self.horizontal_speed_readout, 256, 562)
        self.add(self.vertical_speed_readout, 512, 562)
        self.add(self.fuel_level_readout, 768, 562)

        # Position Gameplay info panels
        self.leaderboardPanel = LeaderboardPanel(24, 616)
        self.mineralPanel = MineralPanel(
            320, 616, {IRON: GAME_GOAL_IRON, GOLD: GAME_GOAL_GOLD, COPPER: GAME_GOAL_COPPER}
        )
        self.plotsPanel = PlotsPanel(
            744, 616, {IRON: IRON_PLOT_TOTAL, GOLD: GOLD_PLOT_TOTAL, COPPER: COPPER_PLOT_TOTAL}
        )  # TODO From Message
        self.add(self.plotsPanel, 744, 616)
        self.add(self.mineralPanel, 320, 616)
        self.add(self.leaderboardPanel, 24, 616)
Пример #2
0
class GameLoop(object):
	def __init__(self, surface, gameUpdate = lambda : None):
		# Input
		self.keyboardInput = KeyboardInput(surface)
		self.mouseInput = MouseInput(surface)

		# The game components
		self.surface = surface
		self.gameUpdate = gameUpdate
		self.physics = PhysicsEngine(self.surface)
		
		self.gameTimer = GameTimer(surface,[self.keyboardInput.update, 
			self.mouseInput.update, self.gameUpdate, self.physics.detection.updateStep, self.physics.resolution.update])

	def addKeyPressListener(self, handler):
		self.keyboardInput.addKeyPressListener(handler)

	def addKeyReleaseListener(self, handler):
		self.keyboardInput.addKeyReleaseListener(handler)

	def addKeyTypedListener(self, handler):
		self.keyboardInput.addKeyTypedListener(handler)

	def addMouseDownListener(self, handler):
		self.mouseInput.addMouseDownListener(handler)

	def addMouseUpListener(self, handler):
		self.mouseInput.addMouseUpListener(handler)
	
	def addMouseMovementListener(self, handler):
		self.mouseInput.addMouseMovementListener(handler)
	
	def addMouseClickedListener(self, handler):
		self.mouseInput.addMouseClickedListener(handler)

	def add(self, obj):
		self.surface.add(obj)
		self.physics.addBody(obj)

	def run(self):
		self.gameTimer.run()
Пример #3
0
	def __init__(self, surface, gameUpdate = lambda : None):
		# Input
		self.keyboardInput = KeyboardInput(surface)
		self.mouseInput = MouseInput(surface)

		# The game components
		self.surface = surface
		self.gameUpdate = gameUpdate
		self.physics = PhysicsEngine(self.surface)
		
		self.gameTimer = GameTimer(surface,[self.keyboardInput.update, 
			self.mouseInput.update, self.gameUpdate, self.physics.detection.updateStep, self.physics.resolution.update])
Пример #4
0
 def setup(self):
     '''
     sets up the game
     '''
     self.currentMap = self.mapList[0].getSpriteLists()
     
     for i in range(self.levelCount):
         levelAdd = Level()
         levelAdd.load(self.currentMap, i)
         self.levels.append(levelAdd)
     
     
     startX = self.currentMap['StartBlock'].sprite_list[0].center_x
     startY = self.currentMap['StartBlock'].sprite_list[0].center_y
     self.playerSprite = Player(startX, startY, 'player_imgs')
     self.playerSprite.laserPool = self.lasers
     self.characterList = self.levels[0].characters
     for char in self.characterList:
         char.target = self.playerSprite
         char.laserPool = self.lasers
     self.characterList.append(self.playerSprite)
     self.physicsEngine = PhysicsEngine(self.characterList, self.levels[self.currentLevel].noWalk)
     self.score = self.playerSprite.score
     self.set_mouse_visible(False)
class LanderContainer(gui.Container):
    """
    This container is the main GUI for the Lander Game.
    
    """

    def __init__(self, controller):
        """
        Game initialization: 1024x768 screen for now
        """
        self.controller = controller
        gui.Container.__init__(self, width=1024, height=704)

        # Initialize screen components: Title Menu
        self.title_menu = gui.TextArea(value="Asteroid Miner", width=152, height=36, focusable=False)

        self.base_station_button = gui.Button(
            "Returning to Base Station", width=152, height=36
        )  # , background=(208, 208, 208))
        self.notify_value = "NOTIFY"
        self.notification_zone = gui.TextArea(value=self.notify_value, width=256, height=36, focusable=False)
        self.fuel_button = gui.Button("Buying Fuel", width=152, height=36)

        self.quit_button = gui.Button("Quit", width=96, height=36)

        # Initialize screen components: Gameplay Canvas
        self.lander = PhysicsEngine(0, 36, 1024, 524)

        # Initialize screen components: Lander Readouts
        self.altitude_readout = gui.TextArea(value="Altitude = 800 m", width=256, height=20, focusable=False)
        self.horizontal_speed_readout = gui.TextArea(
            value="Horizontal Speed: 0.0 km/s", width=256, height=20, focusable=False
        )  # , color=(255, 0, 0))
        self.vertical_speed_readout = gui.TextArea(
            value="Vertical Speed: 0.0 km/s", width=256, height=20, focusable=False
        )
        self.fuel_level_readout = gui.TextArea(
            value="Fuel: 1000.00 L", width=256, height=20, focusable=False
        )  # TODO From Message
        self.fuel_level = 1000.00

        # Position top menu
        self.add(self.title_menu, 0, 0)
        self.add(self.base_station_button, 360, 0)
        self.add(self.fuel_button, 512, 0)
        self.add(self.quit_button, 928, 0)

        # Position canvas and game readouts
        self.add(self.notification_zone, 768, 36)
        self.add(self.altitude_readout, 0, 562)
        self.add(self.horizontal_speed_readout, 256, 562)
        self.add(self.vertical_speed_readout, 512, 562)
        self.add(self.fuel_level_readout, 768, 562)

        # Position Gameplay info panels
        self.leaderboardPanel = LeaderboardPanel(24, 616)
        self.mineralPanel = MineralPanel(
            320, 616, {IRON: GAME_GOAL_IRON, GOLD: GAME_GOAL_GOLD, COPPER: GAME_GOAL_COPPER}
        )
        self.plotsPanel = PlotsPanel(
            744, 616, {IRON: IRON_PLOT_TOTAL, GOLD: GOLD_PLOT_TOTAL, COPPER: COPPER_PLOT_TOTAL}
        )  # TODO From Message
        self.add(self.plotsPanel, 744, 616)
        self.add(self.mineralPanel, 320, 616)
        self.add(self.leaderboardPanel, 24, 616)

    def clicked_in_button(self, button, position):
        return button.collidepoint(position)

    def mouse_event_handler(self, event):
        if event.type == pygame.MOUSEBUTTONDOWN:
            pos = pygame.mouse.get_pos()

            # Purchasing / Traveling Buttons
            if self.clicked_in_button(self.base_station_button.rect, pos):
                self.triggerBaseStation()
            elif self.clicked_in_button(self.fuel_button.rect, pos):
                self.triggerBuyFuel()
            elif self.clicked_in_button(self.quit_button.rect, pos):
                self.quit()

            # Mining Plots Selection
            elif self.clicked_in_button(self.plotsPanel.rectIron, pos):
                self.triggerMiningPlotIron()
            elif self.clicked_in_button(self.plotsPanel.rectGold, pos):
                self.triggerMiningPlotGold()
            elif self.clicked_in_button(self.plotsPanel.rectCopper, pos):
                self.triggerMiningPlotCopper()
            # else: self.updateNotify(str(pos[0]) + " " + str(pos[1]))

        elif event.type == pygame.MOUSEBUTTONUP:
            pass

    def key_event_handler(self, event):
        if event.key == pygame.K_b:
            self.triggerBaseStation()
        elif event.key == pygame.K_f:
            self.triggerBuyFuel()
        else:
            self.lander.on_key_event(event)

    def game_ready(self):
        self.lander.set_ready()

    def draw_game(self, screen):
        # Update game
        self.lander.draw(screen)
        status = self.lander.get_status()
        if status == "CRASHED":
            self.updateNotify(status)
            self.triggerCrashedLanded()
            self.lander.set_status(self.lander.STATUS_PAUSED)
        elif status == "LANDED":
            self.triggerLandedSafely(10)
            self.lander.set_status(self.lander.STATUS_PAUSED)
            # send this signal to server

        # Update Readouts
        self.altitude_readout.value = "Altitude: " + str(self.lander.get_vertical_position()) + " m"

        self.horizontal_speed_readout.value = (
            "Horizontal Speed: " + str(self.lander.get_horizontal_velocity()) + " km/s"
        )
        self.vertical_speed_readout.value = "Vertical Speed: " + str(self.lander.get_vertical_velocity()) + " km/s"
        if abs(self.lander.get_horizontal_velocity()) > 4 or self.lander.get_vertical_velocity() > 4:
            pygame.draw.rect(screen, (255, 0, 0), (0, 560, 1024, 2), 0)
        self.notification_zone.value = self.notify_value
        if status == "RUNNING":
            self.fuel_level -= 1
        self.fuel_level_readout.value = "Fuel: " + str(self.fuel_level) + " L"

    def triggerMiningPlotIron(self):
        self.updateNotify("Mining: Iron")
        self.controller.RequestPlot(IRON)

    def triggerMiningPlotGold(self):
        self.updateNotify("Mining: Gold")
        self.controller.RequestPlot(GOLD)

    def triggerMiningPlotCopper(self):
        self.updateNotify("Mining: Copper")
        self.controller.RequestPlot(COPPER)

    def triggerBaseStation(self):
        self.fuel_level = 1000.00
        self.updateNotify("Returning to Base Station")
        self.controller.ReturnToEarth()

    def triggerBuyFuel(self):
        self.updateNotify("Buying Fuel")
        self.controller.BuyFuel()

    def triggerUpdateMineralScore(self, score_dict):
        self.mineralPanel.update_score(score_dict)

    def updateNotify(self, notif):
        print notif
        self.notify_value = notif

    def triggerCrashedLanded(self):
        self.controller.CrashLanded()

    def triggerLandedSafely(self, score):
        self.controller.LandedSafely(score)

    def refreshLeaderboard(self, data):
        self.leaderboardPanel.refreshLeaderboard(data)

    def updatePlots(self, data):
        self.plotsPanel.update_plots(data)

    def quit(self):
        # TODO Send player quitting message here
        sys.exit(0)
Пример #6
0
class Game(arcade.Window):
    '''
    top level class for the game
    '''
    #constants
    mapcount = 1
    background = arcade.color.BLACK
    viewportMargin = 300
    movementSpeed = 4
    levelCount = 3
    N, NE, E, SE, S, SW, W, NW = 0, 1, 2, 3, 4, 5, 6, 7
    keyToDir = {
                0:None, 1:W, 2:E, 3:None,
                4:S, 5:SW, 6:SE, 7:S, 8:N,
                9:NW, 10:NE, 11:N, 12:None,
                13:W, 14:E, 15:None
                }


    def __init__(self, width = 1440, height = 900, title = 'Game', fullScreen = True):
        '''
        Constructor
        '''
        super().__init__(width, height, title, fullscreen=fullScreen)
        self.mapList = None
        #change later
        self.playerSprite = None
        self.mapList = [Map('map1.tmx')]
        
        self.currentMap = None
        self.currentLevel = 0
        self.levels = []
        self.characterList = None
        self.enemyList = None
        
        self.leftPressed = False
        self.rightPressed = False
        self.upPressed = False
        self.downPressed = False
        
        self.physicsEngine = None
        
        self.directionKey = 0
        
        self.viewLeft, self.viewBottom = 0, 0
        self.lasers = []
        
        self.score = 0
        self.stats = StatsScreen(self)
        
        arcade.set_background_color(self.background)        
        
    def setup(self):
        '''
        sets up the game
        '''
        self.currentMap = self.mapList[0].getSpriteLists()
        
        for i in range(self.levelCount):
            levelAdd = Level()
            levelAdd.load(self.currentMap, i)
            self.levels.append(levelAdd)
        
        
        startX = self.currentMap['StartBlock'].sprite_list[0].center_x
        startY = self.currentMap['StartBlock'].sprite_list[0].center_y
        self.playerSprite = Player(startX, startY, 'player_imgs')
        self.playerSprite.laserPool = self.lasers
        self.characterList = self.levels[0].characters
        for char in self.characterList:
            char.target = self.playerSprite
            char.laserPool = self.lasers
        self.characterList.append(self.playerSprite)
        self.physicsEngine = PhysicsEngine(self.characterList, self.levels[self.currentLevel].noWalk)
        self.score = self.playerSprite.score
        self.set_mouse_visible(False)
           
    def on_draw(self):
        '''
        draws the game elements
        '''
        arcade.start_render()
        self.levels[self.currentLevel].draw()
        for laser in self.lasers:
            laser.draw()
        self.characterList.draw()
        if self.playerSprite.target:
            arcade.draw_circle_outline(self.playerSprite.target.center_x, self.playerSprite.target.center_y, 35, arcade.color.LIME_GREEN, 4)
        self.stats.draw()
            
    def _changeLevel(self, dLevel):
        '''
        called when going up or down stairs. dLevel is -1 for going down, +1 for going up.
        changes the current level and game character list appropriately
        '''
        assert dLevel in (1, -1)
        #clear lasers
        for laser in self.lasers:
            self.lasers.remove(laser)
        #remove the player form the current level's list of characters before changing level
        self.levels[self.currentLevel].characters.remove(self.playerSprite)
        self.currentLevel += dLevel
        self.physicsEngine.walls = self.levels[self.currentLevel].noWalk
        if dLevel == -1:
            self.playerSprite.center_x = self.levels[self.currentLevel].startDownX
            self.playerSprite.center_y = self.levels[self.currentLevel].startDownY
        else:
            self.playerSprite.center_x = self.levels[self.currentLevel].startUpX
            self.playerSprite.center_y = self.levels[self.currentLevel].startUpY
        self.characterList = self.levels[self.currentLevel].characters
        #target all NPCs to player
        for char in self.characterList:
            char.target = self.playerSprite
            char.laserPool = self.lasers
        self.characterList.append(self.playerSprite)
        self.physicsEngine.characters = self.characterList
        
    def _scrollUpdate(self):
        '''
        manages screen scrolling
        '''
        changed = False

        # check scroll left
        left_bndry = self.viewLeft + self.viewportMargin
        if self.playerSprite.left < left_bndry:
            self.viewLeft -= left_bndry - self.playerSprite.left
            changed = True

        # check scroll right
        right_bndry = self.viewLeft + self.width - self.viewportMargin
        if self.playerSprite.right > right_bndry:
            self.viewLeft += self.playerSprite.right - right_bndry
            changed = True

        # check scroll up
        top_bndry = self.viewBottom + self.height - self.viewportMargin
        if self.playerSprite.top > top_bndry:
            self.viewBottom += self.playerSprite.top - top_bndry
            changed = True

        # check scroll down
        bottom_bndry = self.viewBottom + self.viewportMargin
        if self.playerSprite.bottom < bottom_bndry:
            self.viewBottom -= bottom_bndry - self.playerSprite.bottom
            changed = True

        if changed:
            arcade.set_viewport(self.viewLeft,
                                self.width + self.viewLeft,
                                self.viewBottom,
                                self.height + self.viewBottom)
                
    def update(self, delta_time):
        '''
        updates the character list, physics engine, and checks for going up or down stairs
        '''
        self._scrollUpdate()       
        self.playerSprite.isoDirection = self.keyToDir[self.directionKey]
        if self.directionKey == 0:
            self.playerSprite.moving = False
        else:
            self.playerSprite.moving = True
            self._searchTarget()
        
        self.characterList.update()
        self.physicsEngine.update()
        self._manageLasers()
        self.levels[self.currentLevel].update()
              
        # Check stairs
        if self.levels[self.currentLevel].upstairs:
            if arcade.check_for_collision_with_list(self.playerSprite, self.levels[self.currentLevel].upstairs):
                self._changeLevel(1)
        if self.levels[self.currentLevel].downstairs:
            if arcade.check_for_collision_with_list(self.playerSprite, self.levels[self.currentLevel].downstairs):
                self._changeLevel(-1)
            
    def _searchTarget(self):
        closest = None
        minDistance = None
        for char in self.characterList:
            if char != self.playerSprite and char:
                distance = spriteDistance(self.playerSprite, char)
                if closest and minDistance:
                    if distance < minDistance:
                        minDistance = distance
                        closest = char
                else:
                    minDistance = distance
                    closest = char
        self.playerSprite.target = closest
    
    def on_key_press(self, key, modifiers):
        '''
        implements actions associated with key press
        close on esc
        set the direction key using binary encoding on direction keys
        binary encoding is (A3)(A2)(A1)(A0) = (UP)(DOWN)(RIGHT)(LEFT)
        player shoots on space
        '''
        if key == arcade.key.ESCAPE:
            self.close()
            
        if key == arcade.key.UP:
            self.directionKey += 8
        if key == arcade.key.DOWN:
            self.directionKey += 4
        if key == arcade.key.RIGHT:
            self.directionKey += 2
        if key == arcade.key.LEFT:
            self.directionKey += 1
        
        if key == arcade.key.SPACE and self.playerSprite.target:
            self.playerSprite.shoot()
    
    def on_key_release(self, key, modifiers):
        '''
        updates the direction key binary encoding and character shooting
        '''
        if key == arcade.key.UP:
            self.directionKey -= 8
        elif key == arcade.key.DOWN:
            self.directionKey -= 4
        elif key == arcade.key.RIGHT:
            self.directionKey -= 2
        elif key == arcade.key.LEFT:
            self.directionKey -= 1
        
        if key == arcade.key.SPACE:
            self.playerSprite.shootDirection = None
    
    def on_mouse_motion(self, x:float, y:float, dx:float, dy:float):
        pass
    
    def _manageLasers(self):
        for laser in self.lasers:
            points = (laser.center_x, laser.center_y), (laser.center_x + laser.change_x, laser.center_y + laser.change_y)
            for wall in self.levels[self.currentLevel].noWalk:
                if arcade.geometry.are_polygons_intersecting(points, wall.points):
                    try:
                        self.lasers.remove(laser)
                        laser.owner.lasers.remove(laser)
                    except:
                        pass
                    continue
            for char in self.characterList:
                if arcade.geometry.are_polygons_intersecting(points, char.points) and char != laser.owner:
                    try:
                        self.lasers.remove(laser)
                        laser.owner.lasers.remove(laser)
                    except:
                        pass
                    try:
                        self.characterList.remove(char)
                        if char is self.playerSprite:
                            arcade.draw_text('game over', 720, 450, arcade.color.WHITE, font_size=50)
                            arcade.pause(2)
                            self.close()
                        self.score += 1
                    except:
                        pass