コード例 #1
0
ファイル: player.py プロジェクト: eikue-lopes/jogos-python
 def __init__(self,
              dir_sprites,
              dir_sounds,
              dir_fonts,
              lifes=constants['MAX_PLAYER_LIFES'],
              hjump=constants['INITIAL_PLAYER_HJUMP'],
              gravity=constants['INITIAL_PLAYER_GRAVITY'],
              position=list(constants['START_POSITION_PLAYER'])):
     self.hud = Hud(dir_sprites, dir_fonts, lifes=lifes)
     self.sprites = {
         'wait':
         pygame.image.load(dir_sprites['player_wait']).convert_alpha(),
         'run':
         pygame.image.load(dir_sprites['player_run']).convert_alpha(),
         'hurt':
         pygame.image.load(dir_sprites['player_hurt']).convert_alpha()
     }
     #the following attribute will be modified in method _run...
     self.sprite_base = self.sprites['wait']
     self.sounds = {
         'score_plus':
         pygame.mixer.Sound(dir_sounds['sound_player_score_plus'])
     }
     self.attributes = {
         'hjump': hjump,
         'gravity': gravity,
         'position': position
     }
コード例 #2
0
    def __init__(self, virtual_width, virtual_height, map_height, map_width):


        self.v_rect = pygame.Rect(0, 0, virtual_width, virtual_height-config.hud_size)
        self.map_rect = pygame.Rect(0, 0, map_width, map_height)
        self.hud_rect = pygame.Rect(0, virtual_height-config.hud_size, virtual_width, config.hud_size)

        self.map_layer = []
        self.map_layer_surf= pygame.Surface((self.map_rect.w, self.map_rect.h))

        self.item_layer = []
        self.item_layer_surf= pygame.Surface((self.map_rect.w, self.map_rect.h), flags=pygame.SRCALPHA)

        self.unit_layer = []
        self.unit_layer_surf= pygame.Surface((self.map_rect.w, self.map_rect.h), flags=pygame.SRCALPHA)

        self.unit_action_surf = pygame.Surface((self.map_rect.w, self.map_rect.h), flags=pygame.SRCALPHA)

        self.hud = Hud(0, virtual_height-config.hud_size, virtual_width, config.hud_size, self)
        self.hud_surf = pygame.Surface((self.hud_rect.w, self.hud_rect.h))
        self.hud_surf.fill(pygame.Color("#737373"))
        self.hud_font = pygame.font.Font("assets/bitwise/bitwise.ttf", 25)

        self.dirty = 1

        self.font = pygame.font.Font(None, 20)

        self.mouse_events = []
コード例 #3
0
    def postInit(self):
        #
        # initialize game content
        #
        base.cTrav = CollisionTraverser("base collision traverser")
        base.pusher = CollisionHandlerPusher()
        self.menu = Menu()
        self.credits = Credits()
        self.charSelection = CharacterSelection()
        self.levelSelection = LevelSelection()
        self.koScreen = KoScreen()
        self.hud = Hud()
        self.menuMusic = loader.loadMusic("assets/audio/menuMusic.ogg")
        self.menuMusic.setLoop(True)
        self.fightMusic = loader.loadMusic("assets/audio/fightMusic.ogg")
        self.fightMusic.setLoop(True)
        base.audio3d = Audio3DManager(base.sfxManagerList[0], camera)

        #
        # Event handling
        #
        self.accept("escape", self.__escape)

        #
        # Start with the menu
        #
        self.request("Menu")
コード例 #4
0
    def start_loop(self):
        """Loop for start screen"""
        selected = False
        background = Background(START_BG, [0, 0])
        top_score = Hud(10, 350, 200, 40, "TOP SCORE")

        def launch_game():
            nonlocal selected
            selected = True
            self.game_loop()

        while not selected:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    selected = True

            top_score.prop = self.scores.top_score
            self.clock.tick(20)
            pygame.mouse.set_visible(True)
            self.screen.blit(background.image, background.rect)

            large_text = pygame.font.Font('freesansbold.ttf', 80)
            text_surf, text_rect = text_objects("OMEGA!", large_text,
                                                (210, 208, 224))
            text_rect.center = ((self.screen_width / 2),
                                (self.screen_height / 2.75))
            self.screen.blit(text_surf, text_rect)

            top_score.update(dest=self.screen)
            button('PLAY', ((self.screen_width / 2) - 50), 240, 100, 40,
                   ((37, 31, 71), (108, 100, 153), (210, 208, 224)),
                   self.screen, launch_game)
コード例 #5
0
    def __init__(self, _parent=None):
        self.parent = _parent

        # Containers
        self.game_objects = {}
        self.game_doors = {}
        self.game_objects_np = render.attachNewNode("Game_Objects")
        self.game_doors_np = render.attachNewNode("Player_Doors")
        self.game_doors_np.setPos(0, 0, 0)
        self.game_counter_node = None
        self.game_collector_nodes = []

        self.redDudesCount = 0
        self.blueDudesCount = 0

        # Physics world
        self.physics_world = None
        self.builder = Builder(self)

        # level lights
        self.directLight = None

        # Dude class
        self.dude = None
        self.spawnPoints = self.builder.spawnPoints

        # HUD
        self.hud = Hud()

        # Lightshow
        self.elapsed = 0.0
コード例 #6
0
 def start_game(self):
     self.logger.info("STARTGAME")
     self.tank = tanks[self.cl_id]
     self.hud = Hud()
     self.camera = Camera()
     self.camera.init_gl(Game.WIDTH, Game.HEIGHT)
     self.on_resize = self.camera.on_resize
     self.bg_player.play()
     self.running = True
     self.gui.remove(self.stack)
コード例 #7
0
    def initAttr(self):
        self.turn = True
        self.hudWidth = HUD["HUD_WIDTH"]
        self.edgeWidth = GAME["EDGE_WIDTH"]

        # 先获取 board 部分的大小,再自适应自己的大小
        self.board = Board((self.hudWidth, self.edgeWidth))
        Div.__init__(self, (self.board.width + self.hudWidth,
                            self.board.height + self.edgeWidth * 2))
        # 根据窗口高度设置 HUD 高度
        self.hud = Hud((0, self.height), (0, 0))
        self.hud.setMark(self.turn)
        self.board.setTurn(self.turn)
        self.gameID = 0
        self.order = None
コード例 #8
0
    def __init__(self) -> None:
        self.game_objects = {
            "check": [],
            "switch": [],
            "robot": [],
            "platform": [],
            "laser": [],
            "shot": [],
            "gate": [],
            "plr": [self.plr],
            "hud": [Hud(self)]
        }
        self.game_data = {}

        pyxel.init(SCREEN_WIDTH, SCREEN_HEIGHT, caption="Jumpstick robo")
        pyxel.load(
            os.path.join(os.path.dirname(__file__), 'assets',
                         'jumpy_robot.pyxres'), )

        self.load_objects()

        first_check = self.game_objects["check"][0]
        first_check.activate()
        self.plr.current_checkpoint = first_check
        self.plr.kill(True)
        self.plr.current_checkpoint.restore()

        self.game_data = json.loads(game_data)

        self.update_gate_status()
        self.draw_state = self.draw_title

        self.update_state = self.update_title

        pyxel.run(self.update, self.draw)
コード例 #9
0
ファイル: marcianitos.py プロジェクト: jorgeorvaz/marcianitos
def run_game():
    pygame.init()
    m_settings = Settings()
    stats = Estadisticas(m_settings)
    fj.cargar_puntuacion(stats)
    screen = pygame.display.set_mode((m_settings.screen_width, m_settings.screen_height)) #dibujar pantalla
    nave = Nave(screen, m_settings) #Dibujar nave
    balas = Group() #Un grupo es una lista con funciones añadidas
    marcianitos = Group()
    fj.crear_flota(m_settings, screen, nave, marcianitos)
    icon = pygame.image.load("images/alien.bmp")
    pygame.display.set_icon(icon)
    pygame.display.set_caption("Marcianitos")
    boton = Boton(m_settings, screen, "Jugar")
    hud = Hud(m_settings, screen, stats)
    m.musica_fondo()


    while True:
        fj.comprobar_eventos(m_settings, screen, nave, balas, stats, marcianitos, boton)
        if stats.jugando:
            nave.actualizar_posicion(m_settings)
            fj.actualizar_balas(m_settings, screen, nave, marcianitos, balas, stats, hud)
            fj.actualizar_flota(m_settings, stats, screen, balas, marcianitos, nave, hud)
        fj.actualizar_pantalla(m_settings, screen, nave, marcianitos, balas, boton, stats, hud)
コード例 #10
0
ファイル: main.py プロジェクト: jorjuato/panda3d-tutorial
    def postInit(self):
        #
        # initialize game content
        #
        base.cTrav = CollisionTraverser("base collision traverser")
        base.pusher = CollisionHandlerPusher()
        self.menu = Menu()
        self.credits = Credits()
        self.charSelection = CharacterSelection()
        self.levelSelection = LevelSelection()
        self.koScreen = KoScreen()
        self.hud = Hud()
        self.menuMusic = loader.loadMusic("assets/audio/menuMusic.ogg")
        self.menuMusic.setLoop(True)
        self.fightMusic = loader.loadMusic("assets/audio/fightMusic.ogg")
        self.fightMusic.setLoop(True)
        base.audio3d = Audio3DManager(base.sfxManagerList[0], camera)

        #
        # Event handling
        #
        self.accept("escape", self.__escape)

        #
        # Start with the menu
        #
        self.request("Menu")
コード例 #11
0
ファイル: gamescreen.py プロジェクト: mokapharr/python_game
 def __init__(self, window, input_handler):
     super(GameScreen, self).__init__()
     self.window = window
     self.input_handler = input_handler
     self.camera = Camera(window)
     self.render = Render(self.camera, self.window)
     sc_batch = self.render.scene_batch
     st_batch = self.render.static_batch
     self.player = player.Player(renderhook=self.render.playerhook)
     self.proj_viewer = ProjectileViewer(
         self.send_center, batch=sc_batch, scale=self.render.scale,
         rndhook=self.render.attack)
     self.controls = {}
     self.controls_old = {}
     self.map = Map('blank')
     #self.player.spawn(100, 100)
     self.time = 0
     self.moves = moves(1024)
     self.index = [0]
     self.head = [0]
     #other players
     self.players = {}
     self.specs = {}
     #crosshair
     self.cross = CrossHair(batch=st_batch)
     self.isSpec = 0.5
     self.hud = Hud(batch=st_batch, window=self.window)
     self.gs_view = GameStateViewer(self.players, self.hud.update_prop,
                                    self.hud.set_score)
     self.frozen = False
     self.rest_time = 0
コード例 #12
0
def init_game():
    """ Инициализирует игру и создает объект экрана"""
    pygame.init()
    global screen
    screen = pygame.display.set_mode(
        (game_settings.screen_width, game_settings.screen_height))
    pygame.display.set_caption("Aliens")

    # Создание кнопки Play
    global play_button
    play_button = Button(game_settings, screen, "Play")

    global hud
    hud = Hud(game_settings, screen, stats)

    # Создание корабля
    global ship
    ship = Ship(game_settings, screen)

    # Создание группы для хранения пуль
    global bullets
    bullets = pygame.sprite.Group()

    # Создание пришельцев
    global aliens
    aliens = pygame.sprite.Group()

    # Создание флота пришельцев
    create_fleet()
コード例 #13
0
ファイル: main.py プロジェクト: janEntikan/outerspacewaysinc
    def __init__(self):
        ShowBase.__init__(self)
        pman.shim.init(self)
        #props = WindowProperties()
        #props.setCursorHidden(True)
        #props.setMouseMode(WindowProperties.M_relative)
        #base.win.requestProperties(props)
        base.disableMouse()
        self.mouse = [0, 0]
        self.setFrameRateMeter(True)
        self.win.setClearColor((0, 0, 0, 1))
        self.cTrav = CollisionTraverser()
        self.cTrav.setRespectPrevTransform(True)
        self.delay = [0, 5]
        base.win.display_regions[1].dimensions = (0, 1, 0.25, 1)
        render.setShaderAuto()
        self.music = None
        self.shuffleSong()

        self.mode = "edit"
        self.defineKeys()
        self.hud = Hud(self)
        self.road = RoadMan(self)
        self.road.enableEditing()
        self.spawn()
        self.taskMgr.add(self.update)
コード例 #14
0
ファイル: main.py プロジェクト: lupo72/miner2011
    def __init__(self):
        self.display = Display()
        self.player = Charactor(self)
        self.level = Level(self)
        self.hud = Hud()

        self.prepare_stage()
コード例 #15
0
ファイル: __init__.py プロジェクト: Hatchet2k4/mannux
 def initialize(self):
     self.player = Tabby(0, 0)
     self.hud = Hud()
     self.pause = Pause()
     self.title = TitleScreen()
     self.camera = Camera(self.player.sprite)
     self.cameratarget = self.player
     self.entities.append(self.player) #player should always be the first in the list
コード例 #16
0
ファイル: game.py プロジェクト: BrettMcNeff/TBA
 def __init__(self):
     pygame.mixer.pre_init(48000,-16,2, 1024) #Sound Settings
     pygame.init()
     
     #sets the screen resolution for the game and sets a rect for the game screen
     self.screen = pygame.display.set_mode((1024,768))
     self.screen_rect = self.screen.get_rect()
     
     #initializes a clock for the game
     self.clock = pygame.time.Clock()
     
     #initializes a menu object and HUD object and Score object
     self.menu = Menu()
     self.hud = Hud()
     self.score = Score()
     #sets a boolean for whether you are still in the menu or not
     self.inMenu = True
     #sets a camera for the world
     self.camBorder = 32
     self.cam = Camera(pygame.Rect(100, 100, 1024, 768), pygame.Rect(self.camBorder, self.camBorder, 2048 - self.camBorder, 1536 - self.camBorder))
     self.camShakeFactor = 0 #Magnitude of shake
     self.camShakeDecayFactor = 0.08 #Lerp Amount
     
     #Timing
     self.timer = pygame.time.get_ticks()
     self.elapsed = 0
     
     #Sound Controller
     self.soundCon = SoundCon()
     
     #Game Values
     self.backgroundImg = pygame.image.load("Images/Arena/Arena2.png").convert_alpha()
     self.backgroundImgRect = self.backgroundImg.get_rect()
     self.player = Player( self.hud )
     
     #Effects
     self.effectInstances = []
     self.spawnSound = pygame.mixer.Sound("Sounds/ShipRev.wav")
     self.deathSound = pygame.mixer.Sound("Sounds/shipExplo.wav")
     self.enemyExplo = pygame.mixer.Sound("Sounds/enemyExplo.wav")
     self.clashSound = pygame.mixer.Sound("Sounds/clash.wav")
     self.boostSound = pygame.mixer.Sound("Sounds/boostLow.wav")
     
     #Game over fade out
     self.fadeImage = pygame.image.load("Images/HUD/CrackedGlass.png").convert_alpha()
     self.fadeRect = self.fadeImage.get_rect()
     self.fadeSurface = pygame.Surface((1024, 768), pygame.SRCALPHA)
     self.fadeSurfaceAlpha = 0
     self.fadeSurfaceRate = 1
     self.doFade = False
     self.restartGame = False
     
     #Enemies
     self.enemyList = []
     self.baseNumEnemies = 2
     self.spawnTime = 10
     self.currentSpawnTime = 30
コード例 #17
0
ファイル: main.py プロジェクト: J87/FlyingGame
    def __init__(self):
        GameBase.__init__(self, debug=False)
        FSM.__init__(self, "GUI FSM")
        base.disableMouse()

        self.menu = Menu()
        self.missionScreen = MissionScreen()
        self.debrief = Debrief()
        self.hud = Hud()
        self.missionSelect = MissionSelect()

        base.camLens.setFov(90)

        self.setMusic("audio/music.mp3", volume=0.5)
        self.setMusic("audio/engine1.wav", volume=0.3)

        self.request("Menu")
        base.taskMgr.add(self.missionOverTask, "is mission over")
コード例 #18
0
def get_new_game():
    scene = Scene()
    game = Game()
    hud = Hud()
    end_game = EndGame()
    game_ctrl = GameCtrl(game, hud, end_game)
    scene.add(game, z=0, name="game layer")
    scene.add(game_ctrl, z=1, name="game control layer")
    scene.add(hud, z=2, name="hud layer")
    scene.add(end_game, z=3, name="end game layer")
    return scene
コード例 #19
0
ファイル: start_game.py プロジェクト: tomislater/kill_spiders
 def brushing(self):
     self.weapons = []
     self.spiders = []
     self.effects = []
     self.dead_spiders = []
     self.hud = Hud()
     self.player = Player()
     self.bonus_time = 0
     self.bonus_timmer = 30
     self.double_bonus = False
     self.tripple_bonus = False
     self.level = 0
コード例 #20
0
ファイル: monorail.py プロジェクト: undent/MysticMine
    def restart(self, game_data):
        """Start a new game with the current game_data"""
        self.game_data = game_data

        self.state = MonorailGame.STATE_INTRO

        self.scenario = self.game_data.get_quest().create_scenario(
            self.game_data.skill_level.value)
        self.playfield = self.scenario.playfield
        self.controller = ctrl.GroundControl(self.playfield)
        self.init_goldcars()

        self.hud = Hud(self.scenario, self.controller, self.game_data)
        self.hud.start_intro_screen()

        self.begin_timeout = 25 * 3

        self.ingame_menu = None
        self.gui_state = GuiState()

        self.mouse_timeout = MonorailGame.MOUSE_TIMEOUT
        self.is_paused = False
コード例 #21
0
ファイル: player.py プロジェクト: grimfang/owp_shooter
    def __init__(self, _main):
        self.main = _main
        self.name = ""
        self.points = 0
        self.health = 100.0
        self.runSpeed = 1.8
        self.keyMap = {
            "left":False,
            "right":False,
            "up":False,
            "down":False
            }
        base.camera.setPos(0,0,0)
        self.model = loader.loadModel("Player")
        self.model.find('**/+SequenceNode').node().stop()
        self.model.find('**/+SequenceNode').node().pose(0)
        base.camera.setP(-90)
        self.playerHud = Hud()
        self.playerHud.hide()
        self.model.hide()

        # Weapons: size=2, 0=main, 1=offhand
        self.mountSlot = []
        self.activeWeapon = None
        self.isAutoActive = False
        self.trigger = False
        self.lastShot = 0.0
        self.fireRate = 0.0

        self.playerTraverser = CollisionTraverser()
        self.playerEH = CollisionHandlerEvent()
        ## INTO PATTERNS
        self.playerEH.addInPattern('intoPlayer-%in')
        #self.playerEH.addInPattern('colIn-%fn')
        self.playerEH.addInPattern('intoHeal-%in')
        self.playerEH.addInPattern('intoWeapon-%in')
        ## OUT PATTERNS
        self.playerEH.addOutPattern('outOfPlayer-%in')
        playerCNode = CollisionNode('playerSphere')
        playerCNode.setFromCollideMask(BitMask32.bit(1))
        playerCNode.setIntoCollideMask(BitMask32.bit(1))
        self.playerSphere = CollisionSphere(0, 0, 0, 0.6)
        playerCNode.addSolid(self.playerSphere)
        self.playerNP = self.model.attachNewNode(playerCNode)
        self.playerTraverser.addCollider(self.playerNP, self.playerEH)
        #self.playerNP.show()

        self.playerPusher = CollisionHandlerPusher()
        self.playerPusher.addCollider(self.playerNP, self.model)
        self.playerPushTraverser = CollisionTraverser()
        self.playerPushTraverser.addCollider(self.playerNP, self.playerPusher)
コード例 #22
0
ファイル: game.py プロジェクト: piratf/Game_Boxes
    def initAttr(self):
        self.turn = True
        self.hudWidth = HUD["HUD_WIDTH"]
        self.edgeWidth = GAME["EDGE_WIDTH"]

        # 先获取 board 部分的大小,再自适应自己的大小
        self.board = Board((self.hudWidth, self.edgeWidth))
        Div.__init__(self, (self.board.width + self.hudWidth, self.board.height + self.edgeWidth * 2))
        # 根据窗口高度设置 HUD 高度
        self.hud = Hud((0, self.height), (0, 0))
        self.hud.setMark(self.turn)
        self.board.setTurn(self.turn)
        self.gameID = 0
        self.order = None
コード例 #23
0
ファイル: main.py プロジェクト: alex31016/BiokteriiRL
    def __init__(self, ventana):
        super(Lienzo, self).__init__()
        #Cambiar el color de fondo de la ventana
        self.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color(0,0,0))
        # Pedir el tamano de la ventana
        self.set_size_request(WINDOW_SIZE,WINDOW_SIZE)
        #Asignar la ventana que recibe de paramentro a la ventana que se
        #utilizara en el lienzo
        self.ventana=ventana
        #expose-event es una propiedad de DrawingArea que le dice como
        #dibujares, aqui le decimos que utilize nuestra funcion paint
        #para ese evento en vez del que trae por defaul.
        self.connect("expose-event", self.paint)
        #reconocer cuando oprimes y sueltas el mouse
        self.connect("button_press_event",self.button_press)
        self.connect("button_release_event",self.button_release)
        self.connect("motion_notify_event",self.actualizar_dragged)
        self.set_events(gtk.gdk.BUTTON_PRESS_MASK|gtk.gdk.BUTTON_RELEASE_MASK|gtk.gdk.POINTER_MOTION_MASK)
        self.hud=Hud()
        self.minTimeToNextCell=100
        self.maxTimeToNextCell=300
        self.ticksToNextCell=random.randint(self.minTimeToNextCell,self.maxTimeToNextCell)
        self.trainingZoneLimit=WINDOW_SIZE-100

        #cells
        self.virus=[]
        self.cells=[]
        self.trainingSet=[]

        self.draggingObject = None
        self.objetoSeleccionado=[]

        self.currentState="Running"
        self.classificationList=["Target","Enemy","Food"]
        self.divisionPoints=[]

        
        self.currentCell = 0
        self.apareciendo = []
        self.numCells = 0
        self.read_file()

        self.r_table = Table()
        self.qagent = QAgent(self.r_table,'A')

        self.init_simulation()
        self.init_training_set()
コード例 #24
0
ファイル: main.py プロジェクト: lupo72/miner2011
    def __init__(self):

        self.framerate = 0 
        self.number_meanies = 32
        self.bricks_in_level = 0
        self.display = Display()
        self.hud = Hud()
        pygame.key.set_repeat(100,5)
        self.meanies = pygame.sprite.Group()
        
        self.player = Charactor(self)
        self.player.speed = 2
       
        self.level = Level(self)

        self.level.load_level(0)
        self.start_game()
コード例 #25
0
def main():
	hud = Hud()
	# ser = serial.Serial(port = '/dev/ttyUSB0',
	# 					baudrate = 9600,
	# 					parity = serial.PARITY_NONE,
	# 					stopbits = serial.STOPBITS_ONE,
	# 					bytesize = serial.EIGHTBITS,
	# 					timeout = 1)
	logger = 0
	kv = {}
	stringKV = {}
	firstPass = True

	while True:
		# wrapping this all in a try-catch should handle file-opening/-closing timeline nicely
		# i.e. catch TclError(possibly tclError): close file
		#
		# var parsing and file writing will need to be wrapped in classes
		sleep(0.5)
		#kv = RT.randomKV()
		#print kv
		try:
			#inLine = ser.readline()
			inLine = RT.randomKVLine()
			if inLine[0] == '@':
				newKV = parseLineToKV(inLine)
				newStringKV = parseLineToStringKV(inLine)
				if firstPass:
					keys = sorted(newStringKV.keys())
					logger = Logger(keys)
					firstPass = False

				if newKV != kv:
					kv = newKV
					stringKV = newStringKV
					hud.updateHud(kv)
					hud.update_idletasks()
					hud.update()
					logger.logKV(stringKV)
					print strfkv(stringKV)

		except TclError: #possibly tclError
			print "HUD was closed"
			logger.close()
			break
		except err:
			print err
			break
コード例 #26
0
ファイル: main.py プロジェクト: tucif/Biokterii
    def __init__(self, ventana):
        """"""
        super(Lienzo, self).__init__()

        #Cambiar el color de fondo de la ventana
        self.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color(0,0,0))
        # Pedir el tamano de la ventana
        self.set_size_request(WINDOW_SIZE,WINDOW_SIZE)

        #Asignar la ventana que recibe de paramentro a la ventana que se
        #utilizara en el lienzo
        self.ventana=ventana

        #expose-event es una propiedad de DrawingArea que le dice como
        #dibujares, aqui le decimos que utilize nuestra funcion paint
        #para ese evento en vez del que trae por defaul.
        self.connect("expose-event", self.paint)
        #reconocer cuando oprimes y sueltas el mouse
        self.connect("button_press_event",self.button_press)
        self.connect("button_release_event",self.button_release)
        self.connect("motion_notify_event",self.actualizar_dragged)
        self.set_events(gtk.gdk.BUTTON_PRESS_MASK|gtk.gdk.BUTTON_RELEASE_MASK|gtk.gdk.POINTER_MOTION_MASK)

        #Inicializar todos los valores
        self.init_simulation(None)
        self.hud=Hud()
        
        #celulas
        self.annealedCells=cellList+stationList
        self.virus=vir

        self.annealingCompleted=False
        self.initialized=False
        self.allVisited=False
        self.visitedCells=0
        self.nextCell=None

        self.draggingObject = None
        self.corriendo = True

        self.bestEnergy=0
        self.currentEnergy=0
        self.currentTemp=0

        self.objetoSeleccionado=[]
コード例 #27
0
ファイル: main.py プロジェクト: Zheroth/BiokteriiFuzzy
    def __init__(self, ventana):
        super(Lienzo, self).__init__()
        #Cambiar el color de fondo de la ventana
        self.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color(0,0,0))
        # Pedir el tamano de la ventana
        self.set_size_request(WINDOW_SIZE,WINDOW_SIZE)
        #Asignar la ventana que recibe de paramentro a la ventana que se
        #utilizara en el lienzo
        self.ventana=ventana
        #expose-event es una propiedad de DrawingArea que le dice como
        #dibujares, aqui le decimos que utilize nuestra funcion paint
        #para ese evento en vez del que trae por defaul.
        self.connect("expose-event", self.paint)
        #reconocer cuando oprimes y sueltas el mouse
        self.connect("button_press_event",self.button_press)
        self.connect("button_release_event",self.button_release)
        self.connect("motion_notify_event",self.actualizar_dragged)
        self.set_events(gtk.gdk.BUTTON_PRESS_MASK|gtk.gdk.BUTTON_RELEASE_MASK|gtk.gdk.POINTER_MOTION_MASK)
        self.hud=Hud()
        self.minTimeToNextCell=200
        self.maxTimeToNextCell=200
        self.ticksToNextCell=random.randint(self.minTimeToNextCell,self.maxTimeToNextCell)

        #cells
        self.virus=[Virus(
               random.randint(0,100-VIRUS_WIDTH),
               random.randint(0,WINDOW_SIZE-CELL_HEIGHT),
                ) for i in xrange(TOTAL_VIRUS)]
        self.virus[0].policy="Fuzzy"
        self.virus[1].policy="Random"
        self.cells=[]
        
        self.draggingObject = None
        self.objetoSeleccionado=[]

        self.currentState="Running"
        self.classificationList=["Target","Enemy","Food"]

        self.trainingZoneLimit=WINDOW_SIZE-100

        self.fnn = None

        self.init_simulation()
        self.run_simulation()
コード例 #28
0
    def load(self):
        super().load()

        blockWidth = blocks.Block.width
        blockHeight = blocks.Block.height
        self.gameArea = Rect(Game.curGame.width - blockWidth,
                             Game.curGame.height - Hud.height, 0, 0)

        if (self.len() == 0):
            self.generateMap()

        playerStartX = blockWidth
        playerStartY = blockHeight

        self.player = characters.EditCursor(playerStartX, playerStartY)
        # Add player
        self.addGameObject(self.player, 1)

        self.addGameObject(Hud(blockWidth, self.gameArea.height + blockHeight))
コード例 #29
0
    def __init__(self):
        super(World, self).__init__()

        self.frames = 1

        # this is normal difficulty by default
        # easy would prolly be .7ish and hard.. 1.3 or so?
        self.difficulty = 0.7
        self.spawnFreq = 10
        self.scrollPosition = 0
        self.scrollSpeed = 3
        self.endPosition = FRAMES_UNTIL_BOSS * self.scrollSpeed
        self.startScreen = True
        self.helpScreen = False
        self.difficultyScreen = False
        self.bossMode = False
        self.gameOver = False
        self.winScreen = False
        self.score = 0
        self.call_popcorn = 0
        self.boss_music=False
        self.holdingLeftMouseButton = False

        #for keeping track of for the win screen!
        self.numEnemiesAppeared = 0
        self.numEnemiesDestroyed = 0
        self.numViruses = 0
        self.numWorms = 0
        self.numPopUps = 0

        self.playerGroup = pygame.sprite.GroupSingle()
        self.enemies = pygame.sprite.Group()
        self.pickups = pygame.sprite.Group()
        self.bullets = pygame.sprite.Group()
        self.mines = pygame.sprite.Group()
        self.backgrounds = pygame.sprite.Group()
        self.spawnBkg()
        
        # sprite groups listed in draw order (lowest sprite get drawn first)
        self.spriteGroups = [self.backgrounds, self.mines, self.pickups, self.bullets, self.enemies, self.playerGroup]
        
        self.hud = Hud()
コード例 #30
0
ファイル: character.py プロジェクト: gshopov/Pyruto
    def __init__(self, player, character_name, position=Vec2D(0, 0)):
        """Initialize all member variables of character.

        damage -- numeric value, the amount of harm dealt through normal_attack
        lock -- bool varible, says if the character is currently casting an
        ability or motion
        action -- string, the action currently being excecuted by the character

        """
        pygame.sprite.Sprite.__init__(self)

        self.name = character_name
        self.damage = 100
        self.attribute = self.attributes[self.name]
        self.lock = True
        self.action = "introduction"
        self.enemy_position = pygame.Rect(0, 0, 0, 0)

        if not isinstance(position, Vec2D):
            self.position = Vec2D(position)
        else:
            self.position = position

        if player == 1:
            self.controls = P1_CONTROLS
            self.direction = "Right"
        elif player == 2:
            self.controls = P2_CONTROLS
            self.direction = "Left"
        else:
            raise SystemExit("player argument should be either 1 or 2")

        self.movements = {}
        for action in get_all_movements(self.name):
            self.movements[action] = Movement(self.name, action)

        self.skills = SkillManager()
        self.hud = Hud(player, self.name)
        self.sound_effects = SoundManager(self.name)

        self.update({})
コード例 #31
0
ファイル: monorail.py プロジェクト: aither64/MysticMine
    def restart( self, game_data ):
        """Start a new game with the current game_data"""
        self.game_data = game_data

        self.state = MonorailGame.STATE_INTRO

        self.scenario = self.game_data.get_quest().create_scenario(self.game_data.skill_level.value)
        self.playfield = self.scenario.playfield
        self.controller = ctrl.GroundControl( self.playfield )
        self.init_goldcars()

        self.hud = Hud( self.scenario, self.controller, self.game_data )
        self.hud.start_intro_screen()

        self.begin_timeout = 25 * 3

        self.ingame_menu = None
        self.gui_state = GuiState()

        self.mouse_timeout = MonorailGame.MOUSE_TIMEOUT
        self.is_paused = False
コード例 #32
0
ファイル: main.py プロジェクト: lupo72/miner2011
    def __init__(self):
    
        self.framerate = 0 
        self.number_meanies = 16
        
        self.display = Display()
        self.hud = Hud()
        self.meanie_list = []
        pygame.key.set_repeat(100,5)
        self.meanies = pygame.sprite.Group()
        
        self.player = Charactor("held.png", self.display)
        self.player.speed = 2
       
        self.init_floors()
        self.init_ladders()
        self.barrels = pygame.sprite.Group()

        self.init_barrels()
        
        self.testgroup = pygame.sprite.Group()
        self.init_meanies(0)
コード例 #33
0
ファイル: main_2.py プロジェクト: lupo72/miner2011
    def __init__(self):

        self.framerate = 0 
        self.number_meanies = 32
        self.bricks_in_level = 0
        self.display = Display()
        self.hud = Hud()
        pygame.key.set_repeat(100,5)
        self.meanies = pygame.sprite.Group()
        
        self.player = Charactor(self)
        self.player.speed = 2
       
        self.init_floors()
        self.bricks_in_level = len(self.steine)
        self.init_ladders()
        self.barrels = pygame.sprite.Group()

        self.init_barrels()
        
        self.testgroup = pygame.sprite.Group()
        self.init_meanies(0)
コード例 #34
0
ファイル: screens.py プロジェクト: ashisdhara/python_game
 def __init__(self, window):
     super(GameScreen, self).__init__()
     self.window = window
     self.camera = Camera(window)
     self.player = player.Player()
     self.proj_viewer = ProjectileViewer(self.send_center)
     self.controls = {}
     self.controls_old = {}
     self.map = Map('blank')
     #self.player.spawn(100, 100)
     self.time = 0
     self.moves = moves(1024)
     self.index = [0]
     self.head = [0]
     #other players
     self.players = {}
     self.specs = {}
     #crosshair
     self.cross = CrossHair()
     self.isSpec = True
     self.hud = Hud()
     self.gs_view = GameStateViewer(self.players, self.hud.update_prop,
                                    self.hud.set_score)
コード例 #35
0
ファイル: level.py プロジェクト: ebthepcguy/golddigger
    def load(self):
        super().load()

        blockWidth = blocks.Block.width
        blockHeight = blocks.Block.height
        self.gameArea = Rect(Game.curGame.width - blockWidth,
                             Game.curGame.height - Hud.height, 0, 0)

        playerStartX = blockWidth
        playerStartY = blockHeight

        # If there are playerSpawn blocks
        if (self.hasAny(blocks.PlayerSpawn)):
            # Get the location of the block
            playerSpawn = self.getGameObjectsByType(blocks.PlayerSpawn)
            # Create a player if there is not one already
            if not (self.player):
                self.player = characters.Player(playerStartX, playerStartY)
            # Spawn the player on the block
            self.player.x = playerSpawn[0].x
            self.player.y = playerSpawn[0].y
            self.removeGameObjectsByType(blocks.PlayerSpawn)
            self.addGameObject(self.player)
        # If there are not Player Objects create one
        elif (not self.hasAny(characters.Player)):
            if not (self.player):
                self.player = characters.Player(0, 0)
            self.player.x = playerStartX
            self.player.y = playerStartY
            self.addGameObject(self.player)
        # If there are Player Objects
        elif (self.hasAny(characters.Player)):
            self.player = self.getGameObjectsByType(characters.Player)[0]

        self.addGameObject(Hud(blockWidth, self.gameArea.height + blockHeight))

        self.originalGos = self.gameObjects
コード例 #36
0
class Main(ShowBase, FSM):
    """Main function of the application
    initialise the engine (ShowBase)"""
    def __init__(self):
        """initialise the engine"""
        ShowBase.__init__(self)
        base.notify.info("Version {}".format(versionstring))
        FSM.__init__(self, "FSM-Game")

        #
        # BASIC APPLICATION CONFIGURATIONS
        #
        # disable pandas default camera driver
        self.disableMouse()
        # set antialias for the complete sceen to automatic
        self.render.setAntialias(AntialiasAttrib.MAuto)
        # shader generator
        render.setShaderAuto()
        # Enhance font readability
        DGG.getDefaultFont().setPixelsPerUnit(100)
        # get the displays width and height for later usage
        self.dispWidth = self.pipe.getDisplayWidth()
        self.dispHeight = self.pipe.getDisplayHeight()

        #
        # CONFIGURATION LOADING
        #
        # load given variables or set defaults
        # check if particles should be enabled
        # NOTE: If you use the internal physics engine, this always has
        #       to be enabled!
        particles = ConfigVariableBool("particles-enabled", True).getValue()
        if particles:
            self.enableParticles()

        def setFullscreen():
            """Helper function to set the window fullscreen
            with width and height set to the screens size"""
            # set window properties
            # clear all properties not previously set
            base.win.clearRejectedProperties()
            # setup new window properties
            props = WindowProperties()
            # Fullscreen
            props.setFullscreen(True)
            # set the window size to the screen resolution
            props.setSize(self.dispWidth, self.dispHeight)
            # request the new properties
            base.win.requestProperties(props)
            # Set the config variables so we correctly store the
            # new size and fullscreen setting later
            winSize = ConfigVariableString("win-size")
            winSize.setValue("{} {}".format(self.dispWidth, self.dispHeight))
            fullscreen = ConfigVariableBool("fullscreen")
            fullscreen.setValue(True)
            # Render a frame to make sure the fullscreen is applied
            # before we do anything else
            self.taskMgr.step()
            # make sure to propagate the new aspect ratio properly so
            # the GUI and other things will be scaled appropriately
            aspectRatio = self.dispWidth / self.dispHeight
            self.adjustWindowAspectRatio(aspectRatio)

        # check if the config file hasn't been created
        if not os.path.exists(prcFile):
            setFullscreen()
        # automatically safe configuration at application exit
        #base.exitFunc = self.__writeConfig

        #
        # INITIALIZE GAME CONTENT
        #
        base.cTrav = CollisionTraverser("base collision traverser")
        base.pusher = CollisionHandlerPusher()
        self.menu = Menu()
        self.credits = Credits()
        self.charSelection = CharacterSelection()
        self.levelSelection = LevelSelection()
        self.koScreen = KoScreen()
        self.hud = Hud()
        self.menuMusic = loader.loadMusic("assets/audio/menuMusic.ogg")
        self.menuMusic.setLoop(True)
        self.fightMusic = loader.loadMusic("assets/audio/fightMusic.ogg")
        self.fightMusic.setLoop(True)
        base.audio3d = Audio3DManager(base.sfxManagerList[0], camera)

        #
        # EVENT HANDLING
        #
        # By default we accept the escape key
        self.accept("escape", self.__escape)

        #
        # ENTER GAMES INITIAL FSM STATE
        #
        self.request("Menu")

    #
    # FSM PART
    #
    def enterMenu(self):
        show_cursor()
        self.accept("Menu-Start", self.request, ["CharSelection"])
        self.accept("Menu-Credits", self.request, ["Credits"])
        self.accept("Menu-Quit", self.userExit)
        self.ignore("KoScreen-Back")
        self.koScreen.hide()
        self.menu.show()
        if self.menuMusic.status() != AudioSound.PLAYING:
            self.menuMusic.play()
        if self.fightMusic.status() == AudioSound.PLAYING:
            self.fightMusic.stop()

    def exitMenu(self):
        self.ignore("Menu-Start")
        self.ignore("Menu-Credits")
        self.ignore("Menu-Quit")
        self.menu.hide()

    def enterCredits(self):
        self.accept("Credits-Back", self.request, ["Menu"])
        self.koScreen.hide()
        self.credits.show()

    def exitCredits(self):
        self.ignore("Credits-Back")
        self.credits.hide()

    def enterCharSelection(self):
        self.accept("CharSelection-Back", self.request, ["Menu"])
        self.accept("CharSelection-Start", self.request, ["LevelSelection"])
        self.charSelection.show()

    def exitCharSelection(self):
        self.ignore("CharSelection-Start")
        self.ignore("CharSelection-Back")
        self.charSelection.hide()
        self.selectedChar1 = self.charSelection.selectedCharacter1
        self.selectedChar2 = self.charSelection.selectedCharacter2

    def enterLevelSelection(self):
        self.accept("LevelSelection-Back", self.request, ["CharSelection"])
        self.accept("LevelSelection-Start", self.request, ["Game"])
        self.levelSelection.show()

    def exitLevelSelection(self):
        self.ignore("LevelSelection-Start")
        self.ignore("LevelSelection-Back")
        self.levelSelection.hide()

    def enterGame(self):
        # main game code should be called here
        self.arena = Arena(self.levelSelection.selectedLevel)
        self.arena.start()
        self.camera.setPos(0, -5, 1.25)
        self.player = Player(0, self.selectedChar1, "p1")
        self.player2 = Player(1, self.selectedChar2, "p2")
        self.player.setEnemy(self.player2.collisionNodeName)
        self.player2.setEnemy(self.player.collisionNodeName)
        self.player.start(self.arena.getStartPos(1))
        self.player2.start(self.arena.getStartPos(2))
        self.taskMgr.add(self.updateWorldCam, "world camera update task")
        self.accept("gameOver", self.gameOver)
        self.hud.show()

        def lifeChanged(charId, health):
            base.messenger.send("hud_setLifeBarValue", [charId, health])

        self.accept("lifeChanged", lifeChanged)
        hide_cursor()
        if self.fightMusic.status() != AudioSound.PLAYING:
            self.fightMusic.play()
        if self.menuMusic.status() == AudioSound.PLAYING:
            self.menuMusic.stop()

    def exitGame(self):
        # cleanup for game code
        self.taskMgr.remove("world camera update task")
        self.player.stop()
        self.player2.stop()
        del self.player
        del self.player2
        self.arena.stop()
        self.ignore("gameOver")
        self.ignore("lifeChanged")
        self.hud.hide()

    #
    # FSM PART END
    #

    #
    # BASIC FUNCTIONS
    #
    def gameOver(self, LoosingCharId):
        show_cursor()
        winningChar = 1
        if LoosingCharId == 0:
            winningChar = 2
        self.accept("KoScreen-Back", self.request, ["Credits"])
        self.koScreen.show(winningChar)

    def updateWorldCam(self, task):
        playerVec = self.player.getPos() - self.player2.getPos()
        playerDist = playerVec.length()
        x = self.player.getX() + playerDist / 2.0
        self.camera.setX(x)

        zoomout = False
        if not self.cam.node().isInView(self.player.getPos(self.cam)):
            camPosUpdate = -2 * globalClock.getDt()
            self.camera.setY(self.camera, camPosUpdate)
            zoomout = True
        if not self.cam.node().isInView(self.player2.getPos(self.cam)):
            camPosUpdate = -2 * globalClock.getDt()
            self.camera.setY(self.camera, camPosUpdate)
            zoomout = True
        if not zoomout:
            if self.camera.getY() < -5:
                camPosUpdate = 2 * globalClock.getDt()
                self.camera.setY(self.camera, camPosUpdate)
        return task.cont

    def __escape(self):
        """Handle user escape key klicks"""
        if self.state == "Menu":
            # In this state, we will stop the application
            self.userExit()
        elif self.state == "LevelSelection":
            self.request("CharSelection")
        else:
            # In every other state, we switch back to the Menu state
            self.request("Menu")

    def __writeConfig(self):
        """Save current config in the prc file or if no prc file exists
        create one. The prc file is set in the prcFile variable"""
        page = None

        #
        #TODO: add any configuration variable names that you have added
        #      to the dictionaries in the next lines. Set the current
        #      configurations value as value in this dictionary and it's
        #      name as key.
        configVariables = {
            # set the window size in the config file
            "win-size":
            ConfigVariableString(
                "win-size", "{} {}".format(self.dispWidth,
                                           self.dispHeight)).getValue(),
            # set the default to fullscreen in the config file
            "fullscreen":
            "#t"
            if ConfigVariableBool("fullscreen", True).getValue() else "#f",
            # particles
            "particles-enabled":
            "#t" if self.particleMgrEnabled else "#f",
            # audio
            "audio-volume":
            str(round(self.musicManager.getVolume(), 2)),
            "audio-music-active":
            "#t"
            if ConfigVariableBool("audio-music-active").getValue() else "#f",
            "audio-sfx-active":
            "#t"
            if ConfigVariableBool("audio-sfx-active").getValue() else "#f",
            # logging
            "notify-output":
            os.path.join(basedir, "game.log"),
            # window
            "framebuffer-multisample":
            "#t" if ConfigVariableBool("framebuffer-multisample").getValue()
            else "#f",
            "multisamples":
            str(ConfigVariableInt("multisamples", 8).getValue()),
            "texture-anisotropic-degree":
            str(ConfigVariableInt("texture-anisotropic-degree").getValue()),
            "textures-auto-power-2":
            "#t" if ConfigVariableBool("textures-auto-power-2",
                                       True).getValue() else "#f",
        }

        page = None
        # Check if we have an existing configuration file
        if os.path.exists(prcFile):
            # open the config file and change values according to current
            # application settings
            page = loadPrcFile(Filename.fromOsSpecific(prcFile))
            removeDecls = []
            for dec in range(page.getNumDeclarations()):
                # Check if our variables are given.
                # NOTE: This check has to be done to not loose our base or other
                #       manual config changes by the user
                if page.getVariableName(dec) in configVariables.keys():
                    removeDecls.append(page.modifyDeclaration(dec))
            for dec in removeDecls:
                page.deleteDeclaration(dec)
        else:
            # Create a config file and set default values
            cpMgr = ConfigPageManager.getGlobalPtr()
            page = cpMgr.makeExplicitPage("Application Config")

        # always write custom configurations
        for key, value in configVariables.items():
            page.makeDeclaration(key, value)
        # create a stream to the specified config file
        configfile = OFileStream(prcFile)
        # and now write it out
        page.write(configfile)
        # close the stream
        configfile.close()
コード例 #37
0
ファイル: client.py プロジェクト: gjmiles/adventure_pygame
def main():
    """ Main Program """
    pygame.init()
 
    # Set the height and width of the screen
    size = [SCREEN_WIDTH, SCREEN_HEIGHT]
    screen = pygame.display.set_mode(size)
 
    pygame.display.set_caption("Dungeon Dreams Demo")
 
    # Create the player
    map_pix_size = 30

 
    # Create all the levels
    level_list = []
#    level_list.append( Level_01(player) )
 
    # Set the current level
    current_level_no = 0
    current_level = 0
#    current_level = level_list[current_level_no]

    active_sprite_list = pygame.sprite.Group()

 
    # Loop until the user clicks the close button.
    done = False
 
    # Used to manage how fast the screen updates
    clock = pygame.time.Clock()
    all_sprites_list = pygame.sprite.LayeredDirty()
    collid_list = pygame.sprite.LayeredDirty()
    mobiles_list = pygame.sprite.Group()
    m_attacks = pygame.sprite.Group()
    area = None
    image_files = glob.glob('HumanMage.PNG')
    hud = Hud(screen)
    player = Player(100,100,image_files,hud)
    hud.display_player_stats(player.stats)
    player.set_all_sprites(all_sprites_list)
    screen_size = (screen.get_width(),screen.get_height())
    m_fact = Monster_Factory(area,collid_list,50,screen_size,all_sprites_list,player)
    map_tool = Map_Handler(screen,all_sprites_list,collid_list,player,mobiles_list,
                           m_fact,hud)
    map_tool.build_area()
    item_fact = map_tool.get_item_fact()

    shift_x = 0
    shift_y = 0
    
    all_mobiles = m_fact.get_mobiles_group()
    dam_mod = 1
    #init path finding...
    path_finder = a_star(collid_list,50)
    player.group_add(all_mobiles)

    image_files = glob.glob('*.PNG')
    
    #init events for following and monsters, start at 3 seconds because
    #player needs a second or two catch bearings
    FOLLOW_EVENT = USEREVENT + 1
    M_ATTACK_EVENT = USEREVENT + 2
    pygame.time.set_timer(FOLLOW_EVENT, 3000)
    pygame.time.set_timer(M_ATTACK_EVENT,3000)
    game_start = False
    #-------- Main Program Loop -----------
    while not done:

        #Probably would make a class just to handle
        #client events.
        #These handle the movements
        keys = pygame.key.get_pressed()
        if keys[pygame.K_h]:
            player.changespeed(-1, 0)
        if keys[pygame.K_l]:
            player.changespeed(1, 0)
        if keys[pygame.K_k]:
            player.changespeed(0, -1)
        if keys[pygame.K_j]:
            player.changespeed(0, 1)
        if keys[pygame.K_n]: 
            player.changespeed(1,1)
        if keys[pygame.K_b]: 
            player.changespeed(-1,1)
        if keys[pygame.K_y]:
            player.changespeed(-1,-1)
        if keys[pygame.K_u]:
            player.changespeed(1,-1)

        #More events, quit and attacks and stopping the player
        #when the button goes up.
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True

            player.check_events(event)

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    r_attack = player.ranged_attack(all_sprites_list,
                                                    None,
                                                    player.r_attack_images,
                                                    dam_mod)
                    m_fact.set_check_attack(r_attack)
                    
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_h:
                    player.stop()
                if event.key == pygame.K_y:
                    player.stop()
                if event.key == pygame.K_k:
                    player.stop()
                if event.key == pygame.K_u:
                    player.stop()
                if event.key == pygame.K_l:
                    player.stop()
                if event.key == pygame.K_n:
                    player.stop()
                if event.key == pygame.K_j:
                    player.stop()
                if event.key == pygame.K_b:
                    player.stop()

            #Really for testing pathfinding, pathfinding is really for monsters.
            if event.type == pygame.MOUSEBUTTONUP:
                pos = pygame.mouse.get_pos()
                player.follow_path(path_finder.get_path(player.get_pos(),pos),
                                   map_pix_size,
                                   pos)

            #Monsters follow every two seconds to cut down on pathfinding
            #Calculations
            if event.type == FOLLOW_EVENT:
                m_fact.monster_group_follow(player.get_pos())
                pygame.time.set_timer(FOLLOW_EVENT, 2000)

            #Attack every second which is kind of a lot still
            #Otherwise player would get hurt too fast or too slow.
            if event.type == M_ATTACK_EVENT:
                m_attacks = m_fact.monsters_attack(player.get_pos())
                player.set_check_attack(m_attacks)
                pygame.time.set_timer(M_ATTACK_EVENT,1000)

        #Move the player and then check for game end or picked up item.
        player_pos = player.move(collid_list,all_mobiles)
        lost = player.damaged()
        m_fact.move_monsters(all_mobiles)
        got_item = item_fact.is_picked_up()
        #For now just one item and if it is picked up the player wins.
        if got_item:
            end_text = []
            end_text.append('You Found the Scepter of Yendor and Won the Game!')
            end_text.append('To replay press r!')
            end_text.append('To quit press q!')
            end_text.append('To continue press Space Bar!')
            done = game_end(True,end_text,screen,map_tool)
            map_tool.map_move(0,0)
            player.stop()
            player.ranged_item = 3
            player.speed = 8
            player.dam_mod = 10
        elif(lost):
            end_text = []
            end_text.append('You perished!')
            end_text.append('To replay press r!')
            end_text.append('To quit press q!')
            done = game_end(False,end_text,screen,map_tool)
            
        if(map_tool.map_section_change(player_pos)):
            area = map_tool.get_area()
            m_fact.gen_monsters(area)
        
        player.is_moving(map_pix_size)
        all_mobiles.update(None,None)
        if m_attacks:
            m_attacks.update()
        all_sprites_list.draw(screen)
        
        clock.tick(25)
        pygame.display.flip()
        
    pygame.quit()
コード例 #38
0
 def __init__(self, game):
     self.screen = pygame.display.set_mode((100 * 8, 300))
     Board.__init__(self)
     Hud.__init__(self, game)
コード例 #39
0
class Game(GameState):
    def do_setup(self, level):
        super(Game, self).do_setup()

        self.level = level

        self.setup_panda()
        self.level.setup_entities(self.entities)
        self.setup_input()
        self.setup_controllers()
        self.setup_hud()
        self.setup_logic()
        self.enter_transition()

        self.events.event('panda-escape').connect(self.enter_menu)
        self.events.event('panda-p').connect(self.toggle_pause)

        self.manager.enter_state(
            GameMessage,
            message=(('You have to kill %i pigeons in this level...\n' +
                      'Can you make it?') % self.total_pigeons))

    def enter_transition(self):
        self._transition_bg = ui.ImageEntity(entities=self.entities,
                                             image='hud/red-bg.png')
        self._transition_bg.alpha = 1.0
        self._transition_bg.fade_out()

    def leave_transition(self, next_st='menu'):
        self._transition_bg.fade_in().add_next(
            task.run(lambda: self.manager.leave_state(last_state=next_st)))

    def enter_menu(self):
        self.manager.enter_state('menu-noload', None, 'ingame')

    @weak_slot
    def on_kill_pigeon(self):
        self.hud.dec_counter('pigeons', 1)
        self.dead_pigeons += 1
        if self.dead_pigeons >= self.total_pigeons:
            self.win_game()

    @weak_slot
    def on_kill_boy(self):
        self.fail_game(
            random.choice([
                'You are dead!', 'Was it that hard to stay alive?',
                "Your soul is burning in hell..."
            ]))

    @weak_slot
    def on_finish_time(self):
        self.fail_game(
            random.choice([
                'No more time for you!', 'Too slow man...',
                'Hurry up the next time!'
            ]))

    def win_game(self):
        if self.manager.current == self:
            self.manager.enter_state(
                GameMessage, 'YOU WON!\n'
                'This was a show-case level of an in-development game,\n'
                'there is more to come in the future.', 'quit')

    def fail_game(self, reason):
        if self.manager.current == self:
            msg = random.choice([
                'LOOOOOOOOSER', 'You lost!', 'What a pity!',
                'Hey, no luck today!'
            ])
            self.manager.enter_state(GameMessage, reason + '\n' + msg, 'retry')

    @weak_slot
    def on_place_stick(self):
        if self.player_ctl.can_place_stick:
            self.num_sticks -= 1
            if self.num_sticks == 0:
                self.player_ctl.can_place_stick = False
            self.hud.set_counter('sticks', self.num_sticks)

    def highlight_stick_task(self, timer):
        pos = self.player_ctl.get_place_position(5)
        best = self.player_ctl.laser.best_stick(pos)
        if best != self._curr_best_stick:
            if self._curr_best_stick:
                self._curr_best_stick.unhighlight()
            if self.player_ctl.can_place_stick:
                self._curr_best_stick = best
                if best:
                    best.highlight()
        return task.running

    def do_update(self, timer):
        super(Game, self).do_update(timer)

    @weak_slot
    def on_shader_change(self, cfg):
        if cfg.value:
            self.glow_filter.enable(self.manager.panda)
        else:
            self.glow_filter.disable()

    @weak_slot
    def on_control_change(self, cfg):
        self.player_input.unassoc_action(cfg.name)
        if cfg.value:
            self.player_input.assoc(cfg.name, cfg.value)

    def setup_panda(self):
        self.glow_filter = shader.GlowFilter()

        panda = self.manager.panda
        if GlobalConf().path('game.shader').value:
            self.glow_filter.enable(panda)
        panda.relative_mouse()
        panda.loop_music(self.level.music)

    def setup_input(self):
        self.player_input = GameInput()
        self.camera_input = GameInput(CAMERA_INPUT_MAP)
        self.events.connect(self.player_input)
        self.events.connect(self.camera_input)
        self.tasks.add(self.player_input)
        self.tasks.add(self.camera_input)

        self.player_input.assoc('on_steer', 'panda-mouse-move')

        cfg = GlobalConf().path('game.player0.keys')
        for c in cfg.childs():
            if c.value:
                self.player_input.assoc(c.name, c.value)
            c.on_conf_change += self.on_control_change
        GlobalConf ().path ('game.shader').on_conf_change += \
            self.on_shader_change

    def setup_controllers(self):
        self.camera_ctl = CameraController(entities=self.entities,
                                           camera=base.camera)
        self.player_ctl = PlayerController(entities=self.entities,
                                           delegate=self.level.boy)
        self.level.boy.connect(self.camera_ctl)
        self.camera_input.connect(self.camera_ctl)
        self.player_input.connect(self.player_ctl)

    def setup_hud(self):
        self.hud = Hud(entities=self.entities)
        self.hud.add_counter('clock', 'hud/clock.png')
        self.hud.add_counter('pigeons', 'hud/pigeon.png')
        self.hud.add_counter('sticks', 'hud/stick.png')
        self.hud.hide()

    def setup_logic(self):
        total_pigeons = 0
        for f in self.level.flocks:
            total_pigeons += len(f.boids)
            for b in f.boids:
                b.on_death += self.on_kill_pigeon

        self.total_pigeons = total_pigeons
        self.dead_pigeons = 0
        self.level.boy.on_death += self.on_kill_boy

        self.num_sticks = self.level.max_sticks
        self.player_ctl.on_place_stick_down += self.on_place_stick
        self.hud.set_counter('sticks', self.num_sticks)

        self.timer = self.tasks.add(
            task.TimerTask(duration=self.level.max_time))
        self.timer.on_tick = lambda: self.hud.set_counter(
            'clock', int(self.timer.remaining))
        self.timer.on_finish = self.on_finish_time

        self.tasks.add(self.highlight_stick_task)
        self._curr_best_stick = None

        self.pigeon_food = []

    def do_sink(self):
        super(Game, self).do_sink()
        if self.manager.current.state_name == 'menu-noload':
            for x in self.entities.entities:
                if isinstance(x, task.Task):
                    x.pause()
        self.events.quiet = True
        self.hud.soft_hide()
        self.timer.pause()

    def do_unsink(self, action='continue'):
        super(Game, self).do_unsink()
        self.manager.panda.relative_mouse()
        self.tasks.resume()
        for x in self.entities.entities:
            if isinstance(x, task.Task):
                x.resume()
        if action == 'continue':
            self.events.quiet = False
            self.hud.soft_show()
            self.timer.resume()
        elif action == 'quit':
            self.leave_transition()
        elif action == 'retry':
            self.leave_transition('game')

    def do_release(self):
        self.level.dispose()  # TODO: To entity!
        self.glow_filter.disable()
        super(Game, self).do_release()
コード例 #40
0
ファイル: __main__.py プロジェクト: magikmw/spaced
def main():
    logg.info('Starting the main function')

    #Instancing, etc.

    main_view = View().from_rect(
        FloatRect(0, 0, PP_WIDTH, PP_HEIGHT + BAR_HEIGHT))
    window = RenderWindow(
        VideoMode(PP_WIDTH * SCALE, (PP_HEIGHT + BAR_HEIGHT) * SCALE),
        GAME_TITLE + ' v.' + GAME_VERSION)
    window.framerate_limit = 61
    window.view = main_view

    # INITIALIZE TEXTURES HERE OR AFTER \o/
    TEXTURE_WALL = Texture.load_from_file('main/walls.png')
    TEXTURE_BAR = Texture.load_from_file('main/bar.png')
    TEXTURE_HUDWEAPONS = Texture.load_from_file('main/hud_weapons.png')
    TEXTURE_FACES = Texture.load_from_file('main/faces.png')
    TEXTURE_NUMBERS = Texture.load_from_file('main/numbers.png')
    TEXTURE_WEAPONS = Texture.load_from_file('main/weapons.png')
    TEXTURE_ENEMIES = Texture.load_from_file('main/test.png')

    #Create an instance for all game variables and loop functions
    # and set the level to TESTLEVEL
    game = Gameworld(TEXTURE_ENEMIES)
    game.create_dict_map()
    game.player.gamemap = game.current_level
    game.init_physics()
    game.physics.mob_bodies(game.entities)

    #prepare the hud

    hud = Hud(player=game.player,
              background=TEXTURE_BAR,
              faces=TEXTURE_FACES,
              hudweapons=TEXTURE_HUDWEAPONS,
              weapons=TEXTURE_WEAPONS,
              numbers=TEXTURE_NUMBERS)

    #prepare the wall textures

    wall_sprites = game.create_wall_sprite_list(TEXTURE_WALL)

    rays = Raycaster(player=game.player,
                     sprites=wall_sprites,
                     gamemap=game.current_level)

    #prepare other stuff

    player_action = ''

    running = True
    nofocus = False

    ##
    # MAIN LOOP
    ##

    logg.info('Main loop starting...')
    while running:

        #iterate events

        for event in window.iter_events():
            if event.type == Event.CLOSED or player_action == 'quit':
                running = False

            if event.type == Event.LOST_FOCUS:
                nofocus = True
            elif event.type == Event.GAINED_FOCUS:
                nofocus = False

            if event.type == Event.KEY_RELEASED:
                if game.player.bob > 0:  #level the headbobbing
                    game.player.bob -= .5
                elif game.player.bob < 0:
                    game.player.bob += .5

                game.player.strafing = False
                #disable speed limiter for moving in 2 axii

        window.clear(Color(235, 235, 235,
                           255))  #clear the window of everything

        for sprite in wall_sprites:  #draw walls
            window.draw(sprite)

        #draw entities here
        for entity in game.entities:
            if entity.visible == True:
                for sprite_slice in entity.sprite:
                    window.draw(sprite_slice)

        hud.display(window)  #draw the hud

        debug_txt = text('[' + str(draw_fps(frame)) + '] ' +
                         str("{0:.2f}".format(game.player.ux)) + '(' +
                         str(game.player.x) + '),' +
                         str("{0:.2f}".format(game.player.uy)) + '(' +
                         str(game.player.y) + '):' + str(game.player.heading),
                         style=1)
        window.draw(debug_txt)

        wall_sprites = rays.texture_slices(
            rays.cast_rays(), wall_sprites,
            game.player.bob)  #determine which walls to display

        #determine wich entities to display and prepare
        for entity in game.entities:  #calculate the distance of entities to the player
            entity.distance_to_player(game.player)
            # print(str(round(entity.distance, 2)) + " " + str(entity.x) + "," + str(entity.y))

        game.entities.sort(key=lambda x: x.distance,
                           reverse=True)  #sort entities based on the distance

        for entity in game.entities:
            entity.set_sprite_for_display(game.player, rays.distances)

        ###
        # TIMERS
        ###

        if game.player.attack_delay > 0 and game.player.attack == True:
            game.player.attack_delay -= 1
        elif game.player.attack == True and game.player.attack_delay == 0:
            game.player.attack = False
            game.player.attack_delay = 2
        elif game.player.attack == False and game.player.attack_delay > 0:
            game.player.attack_delay -= 1

        if len(game.doors) != 0:
            # print('lol doors')
            for door in game.doors:
                # print(door.openess)
                state = door.open_close()
                # print(state)
                if state == 'done':
                    # print('removing doors')
                    game.doors.remove(door)

        game.physics.world.ClearForces()

        if not nofocus:
            player_action = game.handle_keys()  #player input

        game.physics.world.Step(1.0 / 60.0, 10, 8)

        game.player.update_position()
        for entity in game.entities:
            entity.update_position()

        window.display()  #blit to window

    window.close()

    logg.info('Terminating. Have a nice day.')
    logg.info('Average FPS: %s', round(average_fps / all_frames, 2))
コード例 #41
0
ファイル: game.py プロジェクト: arximboldi/pigeoncide
 def setup_hud (self):
     self.hud = Hud (entities = self.entities)
     self.hud.add_counter ('clock',   'hud/clock.png')
     self.hud.add_counter ('pigeons', 'hud/pigeon.png')
     self.hud.add_counter ('sticks',  'hud/stick.png')
     self.hud.hide ()
コード例 #42
0
 def setup_hud(self):
     self.hud = Hud(entities=self.entities)
     self.hud.add_counter('clock', 'hud/clock.png')
     self.hud.add_counter('pigeons', 'hud/pigeon.png')
     self.hud.add_counter('sticks', 'hud/stick.png')
     self.hud.hide()
コード例 #43
0
ファイル: player.py プロジェクト: eikue-lopes/jogos-python
class Player:
    def __init__(self,
                 dir_sprites,
                 dir_sounds,
                 dir_fonts,
                 lifes=constants['MAX_PLAYER_LIFES'],
                 hjump=constants['INITIAL_PLAYER_HJUMP'],
                 gravity=constants['INITIAL_PLAYER_GRAVITY'],
                 position=list(constants['START_POSITION_PLAYER'])):
        self.hud = Hud(dir_sprites, dir_fonts, lifes=lifes)
        self.sprites = {
            'wait':
            pygame.image.load(dir_sprites['player_wait']).convert_alpha(),
            'run':
            pygame.image.load(dir_sprites['player_run']).convert_alpha(),
            'hurt':
            pygame.image.load(dir_sprites['player_hurt']).convert_alpha()
        }
        #the following attribute will be modified in method _run...
        self.sprite_base = self.sprites['wait']
        self.sounds = {
            'score_plus':
            pygame.mixer.Sound(dir_sounds['sound_player_score_plus'])
        }
        self.attributes = {
            'hjump': hjump,
            'gravity': gravity,
            'position': position
        }

    def collision(self, body2):

        player_position = list(self.attributes['position'])
        player_dimensions = [
            self.sprite_base.get_width(),
            self.sprite_base.get_height()
        ]
        body2_position = list(body2.attributes['position'])
        body2_dimensions = [
            body2.sprite.get_width(),
            body2.sprite.get_height()
        ]

        player_rect = pygame.Rect(player_position, player_dimensions)
        body2_rect = pygame.Rect(body2_position, body2_dimensions)

        collided = player_rect.colliderect(body2_rect)

        if collided:
            if body2.attributes['type'] == 'obstacle':
                self.hud.decrease_lifes(1)
                #self.sounds['hurt'].play()
            #body2 is a coin or life item...
            elif body2.attributes['type'] == 'life':
                self.hud.increase_lifes(body2.attributes['life_increase'])
                #self.sounds['get_life'].play()
            elif body2.attributes['type'] == 'bronze-coin':
                self.hud.increase_score(body2.attributes['score_increase'])
                #self.sounds['get_coin'].play()
            elif body2.attributes['type'] == 'silver-coin':
                self.hud.increase_score(body2.attributes['score_increase'])
                #self.sounds['get_coin'].play()
            elif body2.attributes['type'] == 'gold-coin':
                self.hud.increase_score(body2.attributes['score_increase'])
                #self.sounds['get_coin'].play()

            #body2 exit of screen (exit from the user view)...
            body2.attributes['position'][0] = -9000

    def jump(self):
        #self.sounds['jump'].play(maxtime=100)
        self.attributes['position'][1] -= self.attributes['hjump']

    def run(self):
        st = ""

        if self.sprite_base == self.sprites['wait']:
            self.sprite_base = self.sprites['run']
            st = "run"
        elif self.sprite_base == self.sprites['run']:
            self.sprite_base = self.sprites['wait']
            st = "wait"

        if self.hud.get_lifes() <= 0:
            self.sprite_base = self.sprites['hurt']
            st = "hurt"
        elif self.sprite_base == self.sprites['hurt']:
            #default configs when lifes > 0 but sprite_base == 'hurt'...
            self.sprite_base = self.sprites['wait']
            st = "wait"

        return st

    def fall(self):
        if self.attributes['position'][1] < constants['START_POSITION_PLAYER'][
                1]:
            self.attributes['position'][1] += self.attributes['gravity']

        touch_the_ground = self.attributes['position'][1] >= constants[
            'START_POSITION_PLAYER'][1]
        return touch_the_ground

    def graphical_loop(self, constants, count_obstacles_passed, screen,
                       bodys_in_the_screen):
        #run the graphical loop of the HUD...
        self.hud.graphical_loop(constants, count_obstacles_passed, screen)
        status_return = self.run()
        #print(status_return)
        for body in bodys_in_the_screen:
            self.collision(body)

        screen.blit(self.sprite_base, self.attributes['position'])
コード例 #44
0
ファイル: monorail.py プロジェクト: aither64/MysticMine
class MonorailGame:
    STATE_INTRO, STATE_BEGIN, STATE_GAME, STATE_MENU, STATE_QUIT, STATE_STATS, STATE_TOTAL,\
                 STATE_DONE = range( 8 )

    MOUSE_TIMEOUT = 25 * 3

    def __init__( self, game_data ):
        self.restart( game_data )
        self.music_man = MusicManager()

        # preload clock sounds and big explosion graphic
        resman.get("game.clock_sound")
        resman.get("game.clockring_sound")
        resman.get("game.explosion_sprite")


    def restart( self, game_data ):
        """Start a new game with the current game_data"""
        self.game_data = game_data

        self.state = MonorailGame.STATE_INTRO

        self.scenario = self.game_data.get_quest().create_scenario(self.game_data.skill_level.value)
        self.playfield = self.scenario.playfield
        self.controller = ctrl.GroundControl( self.playfield )
        self.init_goldcars()

        self.hud = Hud( self.scenario, self.controller, self.game_data )
        self.hud.start_intro_screen()

        self.begin_timeout = 25 * 3

        self.ingame_menu = None
        self.gui_state = GuiState()

        self.mouse_timeout = MonorailGame.MOUSE_TIMEOUT
        self.is_paused = False

    def init_goldcars( self ):
        goldcar_names = []
        controllers = []
        for name, controller in self.game_data.goldcars:
            goldcar_names.append( name )
            controllers.append( controller )

        for iq in self.game_data.get_quest().get_opponent_iqs():
            goldcar_names.append( "" )
            controllers.append( ctrl.AiController( None, iq ) )

        self.playfield.add_goldcars( goldcar_names )
        self.controller.add_controllers( controllers )

    def do_tick( self, indev ):
        if self.ingame_menu is None and not self.is_paused:
            if self.game_data.is_single_player() or \
                        self.game_data.is_single_random():
                SingleSwitch.feed_keys( indev )

                # in singleplayer, all joystick buttons are keypress
                for joy in indev.joys:
                    if joy.any_went_down():
                        indev.key.feed_down( K_SPACE )
                    if joy.any_went_up():
                        indev.key.feed_up( K_SPACE )


            if self.state == MonorailGame.STATE_INTRO:
                if self.hud.is_ready(): # or self.game_data.is_single_player():
                    self.hud.end_info()
                    self.state = MonorailGame.STATE_BEGIN
                    self.music_man.play()

            elif self.state == MonorailGame.STATE_BEGIN:
                if self.begin_timeout % 50 == 0:
                    random_spawn = not self.game_data.is_single_player();
                    spawns_left = self.playfield.spawn_next_goldcar( random_spawn )
                    if spawns_left:
                        self.begin_timeout += 50

                self.controller.game_tick( indev )
                self.playfield.game_tick()

                # Start right away in single player
                if self.game_data.is_single_player():
                    self.scenario.game_tick()

                self.begin_timeout -= 1
                if self.begin_timeout <= 0:
                    self.state = MonorailGame.STATE_GAME

                if indev.mouse.has_moved():
                    self.mouse_timeout = MonorailGame.MOUSE_TIMEOUT
                else:
                    self.mouse_timeout -= 1

            elif self.state == MonorailGame.STATE_GAME:
                self.controller.game_tick( indev )
                self.playfield.game_tick()
                self.scenario.game_tick()
                if self.scenario.is_finished():
                    if not self.game_data.is_single_player():
                        self.hud.start_end_screen()
                    else:
                        self.game_data.get_quest().save_score( self.scenario )
                        skill = self.game_data.get_quest().get_skill( self.scenario )
                        self.game_data.skill_level.update( skill )

                        self.game_data.save_single_player_progress()

                        if self.scenario.has_won():
                            self.hud.start_win_screen()
                        else:
                            self.hud.start_lose_screen()

                    self.state = MonorailGame.STATE_STATS
                    self.mouse_timeout = MonorailGame.MOUSE_TIMEOUT
                    self.music_man.stop()

                if indev.mouse.has_moved():
                    self.mouse_timeout = MonorailGame.MOUSE_TIMEOUT
                else:
                    self.mouse_timeout -= 1

            elif self.state == MonorailGame.STATE_STATS:
                if self.hud.is_ready():
                    if not self.game_data.is_single_player():
                        self.game_data.add_total_scores( self.playfield )
                        self.hud.start_total_screen()
                        self.state = MonorailGame.STATE_TOTAL
                    else:
                        if self.scenario.has_won():
                            self.state = MonorailGame.STATE_DONE
                        else:
                            self.restart( self.game_data )
                            return

            elif self.state == MonorailGame.STATE_TOTAL:
                if self.hud.is_ready():
                    self.state = MonorailGame.STATE_DONE

            elif self.state == MonorailGame.STATE_MENU:
                pass

            self.hud.game_tick( indev )
            self.music_man.game_tick()

            SingleSwitch.tick( indev, None )
            if indev.key.went_down( K_ESCAPE ) or \
                        self.hud.menu_btn.went_down() or \
                        SingleSwitch.esc_went_down:
                resman.get("gui.paper_sound").play()
                self.ingame_menu = IngameMenu(self.game_data.is_single_player(), self.game_data)

        elif self.ingame_menu is not None: # Ingame Menu
            SingleSwitch.feed_keys( indev )

            self.gui_state.update( indev, self.ingame_menu )
            self.ingame_menu.tick( indev, self.gui_state )

            if self.ingame_menu.is_done():
                if self.ingame_menu.to_menu:
                    self.music_man.stop()
                    self.state = MonorailGame.STATE_MENU
                elif self.ingame_menu.should_quit:
                    self.music_man.stop()
                    self.state = MonorailGame.STATE_QUIT
                elif self.ingame_menu.to_next_level:
                    self.music_man.stop()
                    self.state = MonorailGame.STATE_DONE

                self.ingame_menu = None

            self.mouse_timeout = MonorailGame.MOUSE_TIMEOUT

#        if indev.key.went_down( K_p ):
#            self.is_paused = not self.is_paused

        event.Event.update()

        # for debugging
        if self.is_paused:
            self.controller.game_tick( indev )


    def draw( self, surface, interpol, time_sec ):
        #surface.fill( (0,0,0) )

        frame = Frame( surface, time_sec, interpol )
        if self.ingame_menu is not None or self.is_paused or\
            self.state not in [MonorailGame.STATE_BEGIN, MonorailGame.STATE_GAME]:
            frame.interpol = 0.0
        frame.draw( self.playfield )
        frame.draw( self.controller )

        self.hud.draw( frame )

        if self.ingame_menu is not None:
            self.ingame_menu.draw( surface )

        frame.draw( event.Event.instance )

    def draw_mouse( self, surface, interpol, time_sec ):
        if self.mouse_timeout > 0:
            x, y = pygame.mouse.get_pos()
            resman.get("gui_surf").draw( surface, Vec2D(x, y), (0,0,32,32) )

    def mouse_down( self, button ):
        pass

    def is_done( self ):
        return self.state == MonorailGame.STATE_DONE \
               or self.state == MonorailGame.STATE_MENU \
               or self.state == MonorailGame.STATE_QUIT
コード例 #45
0
    def __init__(self, app, screen):
        # tock started out random, but now is an important variable.
        # It is a frames count, used for periodic updates on certain
        # frames.
        self.p_max_health = 5
        self.won = False
        self.won_msg = "WINNER!"
        self.particle_ban = False
        self.wait_stop_count = -1  # -1 means do not count
        self.wait_stop_max = 120  # wait this many frames after decay
                                  # before showing menu
        self.tock = 0
        self.stage_e_bullet_odds = 15
        self.mouse_rect = None
        self.temp_rect = None
        self.app = app
        self.screen = screen
        self.app.music_name = "intro.ogg"
        # self.app.continue_music()
        if self.app.settings['music']:
            # self.app.music_loaded = self.app.music_name
            # pygame.mixer.music.load(self.app.resource_find(
            #     self.music_name))
            # pygame.mixer.music.play()  # plays once PLUS repeats param
            pass
        left_border = 50
        right_border = 50
        w, h = screen.get_size()
        self.world_rect = pygame.Rect(left_border, 0,
                                      w-right_border-left_border, h)
        self.bg = BackgroundManager(self.world_rect)

        # Yay spritegroups! They make the world go round, and iterate.
        # Basically each visible game object resides in its own special
        # spritegroup & then all one needs to do is go through these &
        # call functions & stuff.
        # It makes sense in here *points to brain*
        self.p_swarm = Swarm(self.world_rect)
        self.particles = Swarm(self.world_rect)

        self.explosion_images = self.app.load_seq('ex-medium')
        self.shield_hit_images = self.app.load_seq('shield_hit-tiny')
        self.damage_images = self.app.load_seq('ex-tiny')

        # Load player sprite as image list.
        self.p_unit_images = self.app.load_seq('pship')
        # self.p_unit_images = []
        # self.p_unit_images.append(self.load_file('pship.png'))
        # self.p_unit_images.append(self.load_file('pship1.png'))
        # self.p_unit_images.append(self.load_file('pship2.png'))
        # self.p_unit_images.append(self.load_file('pship3.png'))

        # Load enemy ship image.
        self.e_ship_image = self.load_file('eship.png')
        if self.app.settings['sounds']:
            self.p_shoot_sound = self.app.load_file('p-weapon0.wav',
                                                    file_type='sound')
            self.p_shoot_sound.set_volume(.3)
            self.e_ex_sound = self.app.load_file('e-ex.wav',
                                                 file_type='sound')
            self.p_ex_sound = self.app.load_file('p-ex.wav',
                                                 file_type='sound')
            self.e_damage_sound = self.app.load_file('e-damage.wav',
                                                     file_type='sound')
            self.e_shield_sound = self.app.load_file('e-shield.wav',
                                                     file_type='sound')
            self.p_shield_sound = self.app.load_file('p-shield.wav',
                                                     file_type='sound')
            self.p_damage_sound = self.app.load_file('p-damage.wav',
                                                     file_type='sound')
            print("loaded sounds...")
        self.menus = None
        self.tock = 0
        self.lagcount = 0
        self.leftkeydown = 0
        self.rightkeydown = 0
        # self.enemylist = []  # list of dirty rects
        self.swarm = Swarm(self.world_rect,
                           shoot_odds=self.stage_e_bullet_odds)
        self.stage = Stage(self.swarm, self.p_swarm)

        self.p_shot_image = self.load_file('p-laser.png')
        self.e_shot_image = self.load_file('e-laser.png')

        self.p_bullet_swarm = Swarm(self.world_rect)
        self.e_bullet_swarm = Swarm(self.world_rect)
        # self.bullet_width = 10
        self.hud_rect = pygame.Rect(0, 0, 5, 150)
        self.hud = Hud()
        self.hud.generate_blip('player.score', 100,
                               fg_color=(255,243,207),
                               text_color=(192,180,180),
                               caption="SCORE")
        self.hud.generate_blip('player.health', self.p_max_health,
                               fg_color=(0,255,42),
                               text_color=(192,180,180),
                               caption="SHIELD")
        self.statcounter = self.hud.get_blip('player.score')
コード例 #46
0
ファイル: main.py プロジェクト: Zheroth/BiokteriiFuzzy
class Lienzo(gtk.DrawingArea):
    def __init__(self, ventana):
        super(Lienzo, self).__init__()
        #Cambiar el color de fondo de la ventana
        self.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color(0,0,0))
        # Pedir el tamano de la ventana
        self.set_size_request(WINDOW_SIZE,WINDOW_SIZE)
        #Asignar la ventana que recibe de paramentro a la ventana que se
        #utilizara en el lienzo
        self.ventana=ventana
        #expose-event es una propiedad de DrawingArea que le dice como
        #dibujares, aqui le decimos que utilize nuestra funcion paint
        #para ese evento en vez del que trae por defaul.
        self.connect("expose-event", self.paint)
        #reconocer cuando oprimes y sueltas el mouse
        self.connect("button_press_event",self.button_press)
        self.connect("button_release_event",self.button_release)
        self.connect("motion_notify_event",self.actualizar_dragged)
        self.set_events(gtk.gdk.BUTTON_PRESS_MASK|gtk.gdk.BUTTON_RELEASE_MASK|gtk.gdk.POINTER_MOTION_MASK)
        self.hud=Hud()
        self.minTimeToNextCell=200
        self.maxTimeToNextCell=200
        self.ticksToNextCell=random.randint(self.minTimeToNextCell,self.maxTimeToNextCell)

        #cells
        self.virus=[Virus(
               random.randint(0,100-VIRUS_WIDTH),
               random.randint(0,WINDOW_SIZE-CELL_HEIGHT),
                ) for i in xrange(TOTAL_VIRUS)]
        self.virus[0].policy="Fuzzy"
        self.virus[1].policy="Random"
        self.cells=[]
        
        self.draggingObject = None
        self.objetoSeleccionado=[]

        self.currentState="Running"
        self.classificationList=["Target","Enemy","Food"]

        self.trainingZoneLimit=WINDOW_SIZE-100

        self.fnn = None

        self.init_simulation()
        self.run_simulation()

    def actualizar_dragged(self,widget,event):
        if self.draggingObject:
            self.draggingObject.posX=event.x
            self.draggingObject.posY=event.y

    def on_timer(self):
        self.update()
        return True

    def init_simulation(self):
        """Inicializacion de valores"""
        self.reset()
        gobject.timeout_add(20, self.on_timer)

    def run_simulation(self,extra=0):
        self.currentState="Running"
        for cell in self.cells:
            cell.width=20
            cell.height=20
            cell.velX=random.randint(1,5)/5.0
            cell.velY=random.random()
            break

    def reset(self,extra=0):
        self.currentState="Running"
        self.trainingSet=[]

    def update(self):
        self.queue_draw()
        
        cellsToPop=[]
        for cell in self.cells:
            cell.update(self.currentState)
            if cell.posX+cell.width<0 or cell.isDead==True:
                cellsToPop.append(cell)
        for cell in cellsToPop:
            self.cells.pop(indexOf(self.cells,cell))
            for virus in self.virus:
                if cell==virus.targetCell:
                    virus.targetCell=None
                    break

        if self.currentState=="Running":
            if self.ticksToNextCell<=0:
                if len(self.cells)<MAX_CELLS:
                    self.ticksToNextCell=random.randint(self.minTimeToNextCell,self.maxTimeToNextCell)
                    newCell=Cell(WINDOW_SIZE,
                        random.randint(0,TRAINING_ZONE_LIMIT-CELL_HEIGHT))
                    newCell.velX=-(random.random()+3)
                    newCell.type="NormalCell"
                    self.cells.append(newCell)
            else:
                self.ticksToNextCell-=1

            #update virus
            for virus in self.virus:
                if not virus.isDead:
                    virus.update(self.currentState)
                    if len(self.cells)>0 and virus.targetCell==None and virus.status=="Waiting1":
                        for cell in self.cells:
                            if cell.isAvailable:
                                virus.targetCell=cell
                                cell.isAvailable=False
                                break

    def paint(self, widget, event):
        """Nuestro metodo de pintado propio"""

        #Se crea un widget de cairo que despues se usara para desplegar
        #todo en la ventana
        cr = widget.window.cairo_create()
        #Le decimos a cairo que pinte su widget por primera vez.
        cr.set_source_rgb(0,0,0)
        cr.paint()

        #paint game info
        cr.set_source_rgb(1,1,1)
        cr.save()
        cr.move_to(15,15)
        text="To next cell: %d" % (self.ticksToNextCell)
        cr.show_text(text)
        cr.restore()

        cr.set_source_rgb(1,1,1)
        cr.move_to(100, 15)
        cr.line_to(100,WINDOW_SIZE-15)
        cr.set_line_width(0.6)
        cr.stroke()
        
        #pintar a los agentes
        cr.set_line_width(1)
        if self.currentState=="Training":
            for i in xrange(len(self.classificationList)):
                text=str(self.classificationList[i])
                if i==0:
                    posXText=(self.divisionPoints[i])/2-(len(text)/2)*5
                else:
                    posXText=(self.divisionPoints[i-1]+self.divisionPoints[i])/2-(len(text)/2)*5
                posYText=15
                cr.save()
                cr.move_to(posXText,posYText)
                cr.set_source_rgba(1,1,1,0.7)
                cr.show_text(text)
                cr.restore()
                
            display_simulation(cr,[],self.cells)
            self.hud.display_cells(cr,self.cells)
            self.hud.display_viruses(cr, [])

        if self.currentState=="Running":
            for (cell,type) in self.trainingSet:
                cell.paint(cr)

            display_simulation(cr,self.virus,self.cells)
            self.hud.display_cells(cr,self.cells)
            self.hud.display_viruses(cr, self.virus)

        #pintar efecto de selección sobre un agente
        if self.objetoSeleccionado:
            cr.set_line_width(2)
            cr.set_source_rgba(random.random(), 1, random.random(), 0.3)
            cr.rectangle(self.objetoSeleccionado.posX-20,self.objetoSeleccionado.posY-20,
                            self.objetoSeleccionado.width+40, self.objetoSeleccionado.height+40)

            cr.stroke()
                
        #paint score container
        cr.set_line_width(2)
        cr.set_source_rgba(1, 1, 1, 0.5)
        cr.rectangle(100+15,15,570, 5)
        cr.stroke()

        score1=self.virus[0].score+0.00000001
        score2=self.virus[1].score+0.00000001

        total=score1+score2

        #paint first gauge
        cr.save()
        width1=score1*570/total
        cr.set_source_rgba(0, 1, 1, 1)
        cr.rectangle(100+15,15,width1, 5)
        cr.fill()

        cr.move_to(100+15,35)
        text="Fuzzy"
        cr.show_text(text)
        
        #paint second gauge
        width2=570-width1
        cr.set_source_rgba(1, 0.4, 0, 1)
        cr.rectangle(100+15+width1,15,width2, 5)
        cr.fill()

        cr.move_to(670-25,35)
        text="Random"
        cr.show_text(text)
        cr.restore()


    #Para drag & drop
    def button_press(self,widget,event):
        if event.button == 1:
            self.objetoSeleccionado=[]
            lstTemp = self.virus+self.cells
            for ob in lstTemp:
                if ob.drag(event.x,event.y):
                    self.draggingObject = ob
                    self.objetoSeleccionado=ob
                    break
                    
    def button_release(self,widget,event):
        if self.draggingObject:
            self.draggingObject.drop(event.x,event.y)
            self.draggingObject = None

    def pausar(self):
        self.corriendo=False

    def correr(self):
        self.corriendo=True
コード例 #47
0
class World:
    # This is the __init__
    # its important.
    def __init__(self, app, screen):
        # tock started out random, but now is an important variable.
        # It is a frames count, used for periodic updates on certain
        # frames.
        self.p_max_health = 5
        self.won = False
        self.won_msg = "WINNER!"
        self.particle_ban = False
        self.wait_stop_count = -1  # -1 means do not count
        self.wait_stop_max = 120  # wait this many frames after decay
                                  # before showing menu
        self.tock = 0
        self.stage_e_bullet_odds = 15
        self.mouse_rect = None
        self.temp_rect = None
        self.app = app
        self.screen = screen
        self.app.music_name = "intro.ogg"
        # self.app.continue_music()
        if self.app.settings['music']:
            # self.app.music_loaded = self.app.music_name
            # pygame.mixer.music.load(self.app.resource_find(
            #     self.music_name))
            # pygame.mixer.music.play()  # plays once PLUS repeats param
            pass
        left_border = 50
        right_border = 50
        w, h = screen.get_size()
        self.world_rect = pygame.Rect(left_border, 0,
                                      w-right_border-left_border, h)
        self.bg = BackgroundManager(self.world_rect)

        # Yay spritegroups! They make the world go round, and iterate.
        # Basically each visible game object resides in its own special
        # spritegroup & then all one needs to do is go through these &
        # call functions & stuff.
        # It makes sense in here *points to brain*
        self.p_swarm = Swarm(self.world_rect)
        self.particles = Swarm(self.world_rect)

        self.explosion_images = self.app.load_seq('ex-medium')
        self.shield_hit_images = self.app.load_seq('shield_hit-tiny')
        self.damage_images = self.app.load_seq('ex-tiny')

        # Load player sprite as image list.
        self.p_unit_images = self.app.load_seq('pship')
        # self.p_unit_images = []
        # self.p_unit_images.append(self.load_file('pship.png'))
        # self.p_unit_images.append(self.load_file('pship1.png'))
        # self.p_unit_images.append(self.load_file('pship2.png'))
        # self.p_unit_images.append(self.load_file('pship3.png'))

        # Load enemy ship image.
        self.e_ship_image = self.load_file('eship.png')
        if self.app.settings['sounds']:
            self.p_shoot_sound = self.app.load_file('p-weapon0.wav',
                                                    file_type='sound')
            self.p_shoot_sound.set_volume(.3)
            self.e_ex_sound = self.app.load_file('e-ex.wav',
                                                 file_type='sound')
            self.p_ex_sound = self.app.load_file('p-ex.wav',
                                                 file_type='sound')
            self.e_damage_sound = self.app.load_file('e-damage.wav',
                                                     file_type='sound')
            self.e_shield_sound = self.app.load_file('e-shield.wav',
                                                     file_type='sound')
            self.p_shield_sound = self.app.load_file('p-shield.wav',
                                                     file_type='sound')
            self.p_damage_sound = self.app.load_file('p-damage.wav',
                                                     file_type='sound')
            print("loaded sounds...")
        self.menus = None
        self.tock = 0
        self.lagcount = 0
        self.leftkeydown = 0
        self.rightkeydown = 0
        # self.enemylist = []  # list of dirty rects
        self.swarm = Swarm(self.world_rect,
                           shoot_odds=self.stage_e_bullet_odds)
        self.stage = Stage(self.swarm, self.p_swarm)

        self.p_shot_image = self.load_file('p-laser.png')
        self.e_shot_image = self.load_file('e-laser.png')

        self.p_bullet_swarm = Swarm(self.world_rect)
        self.e_bullet_swarm = Swarm(self.world_rect)
        # self.bullet_width = 10
        self.hud_rect = pygame.Rect(0, 0, 5, 150)
        self.hud = Hud()
        self.hud.generate_blip('player.score', 100,
                               fg_color=(255,243,207),
                               text_color=(192,180,180),
                               caption="SCORE")
        self.hud.generate_blip('player.health', self.p_max_health,
                               fg_color=(0,255,42),
                               text_color=(192,180,180),
                               caption="SHIELD")
        self.statcounter = self.hud.get_blip('player.score')

    def load_file(self, name):
        return self.app.load_file(name)

    def on_exit(self):
        print("on_exit...")

    # Clears all the variables
    def clear_vars(self):
        # print("clear_vars: world_rect: " + str(self.world_rect))
        self.p_start_x = self.world_rect.width / 2
        self.p_start_y = self.world_rect.height - 60
        self.bend_y = float(self.p_start_y)
        # print("clear_vars: p_start_y: " + str(self.p_start_y))
        self.bend_rate = 0.02
        self.leftkeydown = 0
        self.rightkeydown = 0
        if self.p_unit is not None:
            self.hud.set_blip_value('player.health', self.p_unit.health)
        else:
            print("WARNING: clear_vars failed to set bar since no" +
                  " player unit exists")
        self.statcounter.set_val(0)
        self.stage.set_stage_number(-1)  # hax
        self.stage_e_bullet_odds = 100
        self.swarm.empty()
        self.p_bullet_swarm.empty()
        self.p_swarm.empty()
        self.particles.empty()
        self.e_bullet_swarm.empty()

    # Define function to draw player ship on X, Y plane
    def draw_player_units(self):
        self.p_swarm.draw(self.screen)

    # Define function to move the enemy ship
    def emove(self):
        self.swarm.draw(self.screen)  # use spritegroup draw method

    # Draws all the enemys you ask it
    def generate_enemies(self):
        print("generating enemies...")
        # Some recursive loops:
        xmin = self.world_rect.left
        xmax = self.world_rect.right
        ymin = self.world_rect.top
        stage_data = self.stage.get_data()
        self.e_ship_image = self.app.load_file(stage_data['e']+".png")
        enemy_width, enemy_height = self.e_ship_image.get_size()
        enemy_spacing_x = 15
        enemy_spacing_y = 10
        init_enemy_speed = 3
        angle = -90  # cartesian

        self.app.music_name = stage_data['music']
        # if self.app.music_name == 'intro.ogg':
            # self.app.continue_music()  # force song change
        e_max_health = stage_data['e_h']
        for enemycol in range(stage_data['x_e_count']):
            # Now for the rows
            for enemyrow in range(stage_data['y_e_count']):
                # Make a new enemy object:
                new_enemy = Entity(self.app,
                                  'eship', [self.e_ship_image],
                                  init_enemy_speed, angle,
                                  self.swarm, e_max_health,
                                  self.explosion_images, self.particles,
                                  ai_enable=True,
                                  value=stage_data['e_h'],
                                  ex_sound=self.e_ex_sound)
                new_enemy.set_xy(
                    xmin +
                    enemycol * (enemy_width +
                                enemy_spacing_x),
                    ymin +
                    enemyrow * (enemy_height +
                                enemy_spacing_y) - 150
                )
                new_enemy.set_range(
                    xmin +
                    enemycol * (enemy_width +
                                enemy_spacing_x),
                    xmax -
                    (stage_data['x_e_count'] - enemycol) *
                    (enemy_height +
                     enemy_spacing_x)
                )

                # Now add the temp enemy to the array and we're good to
                # go
                self.swarm.add(new_enemy)

    # So I'm trying out having the program check for collisions, instead
    # of the enemy objects i think i might switch to the objects, but
    # still keep this function just hand the computing to the object
    def test_collision(self):
        part_speed = 1
        part_angle = -90
        part_health = 1
        e_hit = pygame.sprite.groupcollide(self.swarm,
                                           self.p_bullet_swarm,
                                           0, 0)
        for sprite, bullets in e_hit.items():
            # print("removed " + str(bullet)
            for bullet in bullets:
                was_alive = sprite.get_is_alive()
                prev_health = sprite.health
                if sprite.get_is_alive():
                    sprite.set_hit(1)
                damage = prev_health - sprite.health
                poof = self.shield_hit_images
                temper_sound = self.e_shield_sound
                if damage > 0:
                    poof = self.damage_images
                    temper_sound = self.e_damage_sound
                if not was_alive:
                    break
                point = pygame.sprite.collide_mask(sprite,
                                                   bullet)
                if ((point is not None) and
                        (not self.particle_ban)):
                    particle = Entity(self.app, 'particle',
                                      poof,
                                      part_speed,
                                      part_angle, self.particles,
                                      part_health,
                                      None,
                                      None,
                                      anim_done_remove=True,
                                      temper_sound=temper_sound)
                    particle.temper = 1  # start particle death
                    x1, y1 = sprite.get_pos()  # top left
                    x = x1 + point[0] - particle.rect.width / 2
                    y = y1 + point[1] - particle.rect.height / 2
                    particle.set_xy(x, y)
                    self.particles.add(particle)
            if not sprite.get_is_alive():
                points = sprite.take_value()  # only once & if health 0
                if points > 0:
                    self.statcounter.add_value(points)
            self.p_bullet_swarm.remove(bullets)



        p_hit = pygame.sprite.groupcollide(self.p_swarm,
                                           self.e_bullet_swarm,
                                           0, 0)
        for sprite, bullets in p_hit.items():
            for bullet in bullets:
                was_alive = sprite.get_is_alive()
                prev_health = sprite.health
                if sprite.get_is_alive():
                    sprite.set_hit(1)
                damage = prev_health - sprite.health
                poof = self.shield_hit_images
                temper_sound = self.p_shield_sound
                if damage > 0:
                    poof = self.damage_images
                    temper_sound = self.p_damage_sound
                    self.hud.set_blip_value('player.health',
                                            self.p_unit.health)
                # New in pygame 1.8.0:
                point = pygame.sprite.collide_mask(sprite, bullet)
                if not was_alive:
                    break
                if (point is not None) and (not self.particle_ban):
                    particle = Entity(self.app, 'particle',
                                      poof,
                                      part_speed,
                                      part_angle, self.particles,
                                      part_health,
                                      None,
                                      None,
                                      anim_done_remove=True,
                                      temper_sound=temper_sound)
                    particle.temper = 1  # start particle death
                    x1, y1 = sprite.get_pos()  # top left
                    x = x1 + point[0] - particle.rect.width / 2
                    y = y1 + point[1] - particle.rect.height / 2
                    particle.set_xy(x, y)
                    self.particles.add(particle)

        # if pygame.sprite.spritecollideany(self.p_unit,
                                          # self.e_bullet_swarm):
            # self.p_unit.set_hit(1)
            # self.hud.set_blip_value('player.health',
            #                         self.p_unit.health)

    # if there are no enemys left, go to the next stage
    def check_done(self):
        if not self.swarm:
            if self.stage.is_last_stage():
                if not self.won:
                    self.won = True  # TODO: make ending screen
                    # self.app.music_name = 'victory.ogg'
                    # if self.app.music_name == 'intro.ogg':
                        # self.app.continue_music()  # force song change
                    self.app.music_name = None  # stop repeating
                    self.app.check_music() # apply None to loop
                    self.app.queue_music('victory.ogg', 1)
            if not self.won:
                self.stage.next_stage()
                if self.stage_e_bullet_odds > 15:
                    self.stage_e_bullet_odds -= 15
                self.generate_enemies()

    # checks to see if we can expand the ranges of the bots so its nice
    # and.... umm... nice.
    def check_rows(self):
        if self.tock % 20 == 0:
            # simple sorting algorithm to find the highest values
            xmin = self.world_rect.left
            xmax = self.world_rect.right
            highest = xmin
            lowest = xmax
            for enemy in self.swarm:
                if enemy.get_range()[1] > highest:
                    highest = enemy.get_range()[1]
                if enemy.get_range()[0] < lowest:
                    lowest = enemy.get_range()[0]
            highest = xmax - highest
            lowest = lowest - xmin
            if highest != 0 or lowest != 0:
                    # makes things |--| this much more efficient
                for enemy in self.swarm:
                    erange = enemy.get_range()
                    enemy.set_range(erange[0]-lowest,
                                    erange[1]+highest)

    # major hack just to get this thing playable..... sorry
    def again(self):
        if self.hud.get_blip_value('player.health') <= 0:
            self.particle_ban = True
        if self.p_unit.get_is_decayed():
            self.particle_ban = True
            # also wait for particles to finish for prettier ending
            if len(self.particles) < 1:
                if self.wait_stop_count < 0:
                    print("player unit decayed, counting down to menu")
                    self.wait_stop_count = 0
                # return False
        if self.wait_stop_count >= 0:
            self.wait_stop_count += 1
            if self.wait_stop_count > self.wait_stop_max:
                return False
        if self.won:
            if self.wait_stop_count < 0:
                print("won game, counting down to menu")
                self.wait_stop_count = 0
        return True

    # this is called if the player initiates shooting
    def pshoot(self):
        # sx = self.p_unit.rect.centerx -
        #      self.p_shot_image.rect.width / 2
        # sy = self.p_unit.rect.top +
        #      self.p_shot_image.rect.height * .75
        if self.p_unit.get_is_alive():
            self.p_unit.shoot(self.p_shot_image,
                              self.p_bullet_swarm)
            # self.p_unit.shoot_from(self.p_shot_image,
            #                        self.p_bullet_swarm,
            #                        sx, sy, self.p_unit.angle)

    def draw_bullets(self):
        self.p_bullet_swarm.draw(self.screen)
        self.e_bullet_swarm.draw(self.screen)

    def draw_hud(self):
        if self.tock % 5 == 0:
            self.hud.update()
        self.hud.draw(self.screen)

    # Goes through all the objects and makes each of them move as
    # necessary
    def tick(self):
        self.bend_y += self.bend_rate
        bend_max = 5.0
        if self.bend_rate < 0.0:
            self.bend_rate -= .02
        else:
            self.bend_rate += .02
        if ((self.bend_y > self.p_start_y + bend_max) or
            (self.bend_y < self.p_start_y)):
            if self.bend_rate < 0.0:
                self.bend_rate = .02
                self.bend_y = float(self.p_start_y)
            else:
                self.bend_rate = -.02
                self.bend_y = float(self.p_start_y) + bend_max
        self.p_unit.set_xy(self.p_unit.get_pos()[0],
                           int(self.bend_y+.5))
        self.p_bullet_swarm.update()
        self.swarm.update()
        self.e_bullet_swarm.update()

    ######################
    # Here are a bunch of metafunctions.
    # I break it up so its really easy to add new features,
    # like if we ant a counter? add something to check() and draw().
    # All of these are called once per frame.
    def check(self):
        self.check_done()
        self.test_collision()
        self.check_rows()
        self.bg.update()
        if self.p_unit.get_is_alive():
            self.swarm.shoot(self.e_shot_image, self.e_bullet_swarm)
        self.p_unit.update()
        for particle in self.particles:
            particle.update()

    def draw(self):
        self.screen.fill(self.bg.bg_color)
        # if self.world_rect is not None:
            # self.screen.fill((64, 64, 64), self.world_rect)
        self.bg.draw(self.screen)
        self.draw_bullets()
        self.draw_player_units()
        self.emove()
        self.particles.draw(self.screen)
        self.draw_hud()
        # if self.p_unit is not None:
            # if self.p_unit.rect is not None:
                # self.screen.fill((128, 128, 128), self.p_unit.rect)
        # if self.mouse_rect is not None:
            # self.screen.fill((255, 255, 255), self.mouse_rect)
        # if self.temp_rect is not None:
            # self.screen.fill((128, 0, 0), self.temp_rect)


    # does just what it sounds like.....
    def clear_screen(self):
        self.screen.fill(self.bg.bg_color)
        # pygame.display.flip()

    # for debugging info mostly
    def dispvars(self):
        print("The Enemy SpriteGroup size is:" +
              str(len(self.swarm.sprites())))
        print("The Player Bullet Array size is:" +
              str(len(self.p_bullet_swarm.sprites())))
        print("The Enemy Bullet Array size is:" +
              str(len(self.e_bullet_swarm.sprites())))

    # does lots and lots of stuff, it really needs to be cleaned up
    def process_events(self, events):
        # print("input: self.p_unit.rect: " + str(self.p_unit.rect))
        xmin = self.world_rect.left
        xmax = self.world_rect.right
        smooth_scroll_var1 = 10
        smooth_scroll_var2 = 2
        pygame.event.pump()  # redraw Window so OS knows not frozen
        self.app.check_music()
        pause_menu_strings = ["RESUME", "ABOUT", "HELP", "EXIT"]
        if self.won:
            pause_menu_strings.insert(0, self.won_msg)
        for event in events:
            if event.type == QUIT:
                self.on_exit()
                sys.exit(0)

            if event.type == pygame.MOUSEMOTION:
                pygame.event.get()
                prev_pos = self.p_unit.get_pos()
                tempx = (pygame.mouse.get_pos()[0] -
                         self.p_unit.rect.width / 2)
                # *Just to make sure we don't get the ship way out:
                if tempx + self.p_unit.rect.width > xmax:
                    # if its outside the world,
                    # just stick it as far as possible
                    self.p_unit.set_xy(xmax - self.p_unit.rect.width,
                                       prev_pos[1])
                elif tempx < xmin:
                    self.p_unit.set_xy(xmin, prev_pos[1])
                elif abs(tempx-self.p_start_x) > \
                        smooth_scroll_var1:
                    # smooth scrolling if the mouse gets far
                    # from the ship
                    self.p_unit.set_xy(
                        prev_pos[0] +
                        (tempx-prev_pos[0]) /
                        smooth_scroll_var2,
                        prev_pos[1])
                else:
                    # if it gets down to this point,
                    # we've passed all sanity checks so just move it
                    self.p_unit.set_xy(tempx, prev_pos[1])

            elif event.type == pygame.MOUSEBUTTONDOWN:
                self.pshoot()

            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_q:
                    self.menus.show_dialog(pause_menu_strings)
                if event.key == pygame.K_p:
                    self.menus.show_dialog(pause_menu_strings)
                if event.key == pygame.K_ESCAPE:
                    self.menus.show_dialog(pause_menu_strings)
                # keyboard controls
                if event.key == pygame.K_LEFT:
                    self.leftkeydown = 1
                if event.key == pygame.K_RIGHT:
                    self.rightkeydown = 1
                if event.key == pygame.K_SPACE:
                    self.pshoot()

            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT:
                    self.leftkeydown = 0
                if event.key == pygame.K_RIGHT:
                    self.rightkeydown = 0
            elif event.type == pygame.USEREVENT:
                if event.code == pygame.USEREVENT_DROPFILE:
                    print("Tried to open file on MacOS (this should" +
                          " never happen:")
                    print("  " + str(event))
                else:  # should be event.code 0
                    self.app.continue_music()
                    print("music queue ended in game:")
                    if event.code != 0:
                        print("unknown USEREVENT event.code: " +
                              str(event.code))

        if self.leftkeydown:
            self.p_unit.move_one(-1, self.world_rect)
        if self.rightkeydown:
            self.p_unit.move_one(1, self.world_rect)

        pygame.event.clear()

    ####################################################################

    def start(self, menus):
        self.won = False
        self.particle_ban = False
        self.wait_stop_count = -1  # -1 means do not count down to menu
        self.menus = menus
        p_speed = 10
        self.p_unit = Entity(self.app, 'pship', self.p_unit_images,
                             p_speed, 90.0,
                             self.p_swarm, self.p_max_health,
                             self.explosion_images,
                             self.particles,
                             ex_sound = self.p_ex_sound)
        self.p_unit.shoot_sound = self.p_shoot_sound
        print("Clearing vars...")
        self.clear_vars()  # does reset player unit (p_unit) position
        self.p_swarm.add(self.p_unit)
        self.p_unit.set_xy(self.p_start_x, self.p_start_y)
        print("Starting main event loop...")
        self.loop()

    # Yeah see this one does all of the work
    def loop(self):
        # Start loop
        REFRESH_TIME = self.app.get_fps() * 3
        while (not self.menus.get_bool('exit')) and (self.again()):
            # Refresh screen periodically
            if self.tock >= REFRESH_TIME:
                # self.clear_screen()
                self.tock = 0
            self.tock += 1

            # Check everythign and see if changes need to be made
            self.check()

            # Draw bullets
            self.draw()

            # Move everything
            self.tick()

            # Initiate input function
            self.process_events(pygame.event.get())

            # applies the smart screen updating
            pygame.display.update()
            # TODO: ? pygame.display.update(self.enemylist)
            # self.enemylist = []

            # Pauses and waits
            timeittook = self.app.clock.tick(self.app.get_fps())
コード例 #48
0
ファイル: game.py プロジェクト: ChristianLowe/pyasumi
from hud import Hud
from scene import Scene
from window import Window
from character import Character

# Create a grid with a specific atlas.
g = Grid(10, 10, 50, 50, "terrain_atlas.json")

# Create a character.
goo = Character("goo", "../images/goo_hl.gif", 7, 7, "animation")
g.add_character(goo, 5, 5)
goo.scale(.10)

# Create a few HUDs.
meter_hud = Hud(x_offset=15,
                y_offset=80,
                hud_image_loc="../images/ui/hud-test.png")
heart_hud0 = Hud(x_offset=120,
                 y_offset=40,
                 hud_image_loc="../images/ui/heart.png")
heart_hud0.image.scale = 0.55
heart_hud1 = Hud(x_offset=140,
                 y_offset=40,
                 hud_image_loc="../images/ui/heart.png")
heart_hud1.image.scale = 0.55
huds = [meter_hud, heart_hud0, heart_hud1]

# Create a scene with a grid and some huds attached.
s = Scene(g, huds)

# Create the window.
コード例 #49
0
    def __init__(self):
        """initialise the engine"""
        ShowBase.__init__(self)
        base.notify.info("Version {}".format(versionstring))
        FSM.__init__(self, "FSM-Game")

        #
        # BASIC APPLICATION CONFIGURATIONS
        #
        # disable pandas default camera driver
        self.disableMouse()
        # set antialias for the complete sceen to automatic
        self.render.setAntialias(AntialiasAttrib.MAuto)
        # shader generator
        render.setShaderAuto()
        # Enhance font readability
        DGG.getDefaultFont().setPixelsPerUnit(100)
        # get the displays width and height for later usage
        self.dispWidth = self.pipe.getDisplayWidth()
        self.dispHeight = self.pipe.getDisplayHeight()

        #
        # CONFIGURATION LOADING
        #
        # load given variables or set defaults
        # check if particles should be enabled
        # NOTE: If you use the internal physics engine, this always has
        #       to be enabled!
        particles = ConfigVariableBool("particles-enabled", True).getValue()
        if particles:
            self.enableParticles()

        def setFullscreen():
            """Helper function to set the window fullscreen
            with width and height set to the screens size"""
            # set window properties
            # clear all properties not previously set
            base.win.clearRejectedProperties()
            # setup new window properties
            props = WindowProperties()
            # Fullscreen
            props.setFullscreen(True)
            # set the window size to the screen resolution
            props.setSize(self.dispWidth, self.dispHeight)
            # request the new properties
            base.win.requestProperties(props)
            # Set the config variables so we correctly store the
            # new size and fullscreen setting later
            winSize = ConfigVariableString("win-size")
            winSize.setValue("{} {}".format(self.dispWidth, self.dispHeight))
            fullscreen = ConfigVariableBool("fullscreen")
            fullscreen.setValue(True)
            # Render a frame to make sure the fullscreen is applied
            # before we do anything else
            self.taskMgr.step()
            # make sure to propagate the new aspect ratio properly so
            # the GUI and other things will be scaled appropriately
            aspectRatio = self.dispWidth / self.dispHeight
            self.adjustWindowAspectRatio(aspectRatio)

        # check if the config file hasn't been created
        if not os.path.exists(prcFile):
            setFullscreen()
        # automatically safe configuration at application exit
        #base.exitFunc = self.__writeConfig

        #
        # INITIALIZE GAME CONTENT
        #
        base.cTrav = CollisionTraverser("base collision traverser")
        base.pusher = CollisionHandlerPusher()
        self.menu = Menu()
        self.credits = Credits()
        self.charSelection = CharacterSelection()
        self.levelSelection = LevelSelection()
        self.koScreen = KoScreen()
        self.hud = Hud()
        self.menuMusic = loader.loadMusic("assets/audio/menuMusic.ogg")
        self.menuMusic.setLoop(True)
        self.fightMusic = loader.loadMusic("assets/audio/fightMusic.ogg")
        self.fightMusic.setLoop(True)
        base.audio3d = Audio3DManager(base.sfxManagerList[0], camera)

        #
        # EVENT HANDLING
        #
        # By default we accept the escape key
        self.accept("escape", self.__escape)

        #
        # ENTER GAMES INITIAL FSM STATE
        #
        self.request("Menu")
コード例 #50
0
class Game():

    def __init__(self, _parent=None):
        self.parent = _parent

        # Containers
        self.game_objects = {}
        self.game_doors = {}
        self.game_objects_np = render.attachNewNode("Game_Objects")
        self.game_doors_np = render.attachNewNode("Player_Doors")
        self.game_doors_np.setPos(0, 0, 0)
        self.game_counter_node = None
        self.game_collector_nodes = []

        self.redDudesCount = 0
        self.blueDudesCount = 0

        # Physics world
        self.physics_world = None
        self.builder = Builder(self)

        # level lights
        self.directLight = None

        # Dude class
        self.dude = None
        self.spawnPoints = self.builder.spawnPoints

        # HUD
        self.hud = Hud()

        # Lightshow
        self.elapsed = 0.0



    def start(self, levelID, winCondition=25):
        self.winCondition = winCondition

        self.loadLevel("assets/level{}".format(levelID))
        self.loadLights()

        # player
        self.loadPlayer("default")
        self.loadDude()

        # Timer
        taskMgr.add(self.update, "Game_Update_Task", 0)

        self.hud.show()

        # start the Lightshow
        taskMgr.add(self.discoLightTask, "the lightshow")

    def stop(self):
        self.player.stop()
        self.dude.stop()
        self.builder.cleanup()
        self.physics_world = None
        render.clearLight()
        self.directLight = None
        self.hud.hide()
        taskMgr.remove("the lightshow")

    def update(self, task):

        if self.game_counter_node is None:
            return

        ghost = self.game_counter_node.node()
        for node in ghost.getOverlappingNodes():

            if "red" in node.name:
                self.redDudesCount += 1
                self.physics_world.removeRigidBody(self.dude.dudes[node.name].node())
                self.dude.dudes[node.name].removeNode()
                self.hud.update(self.redDudesCount, self.blueDudesCount)
                del self.dude.dudes[node.name]
                break


            elif "blue" in node.name:
                self.blueDudesCount += 1
                self.physics_world.removeRigidBody(self.dude.dudes[node.name].node())
                self.dude.dudes[node.name].removeNode()
                self.hud.update(self.redDudesCount, self.blueDudesCount)
                del self.dude.dudes[node.name]
                break

        if self.redDudesCount > self.blueDudesCount:
            base.messenger.send("lostGame")
            return Task.done
        elif self.blueDudesCount >= self.winCondition:
            base.messenger.send("wonGame")
            return Task.done

        for collectorGhostNP in self.game_collector_nodes:
            collectorGhost = collectorGhostNP.node()
            for node in collectorGhost.getOverlappingNodes():
                if "red" in node.name:
                    self.physics_world.removeRigidBody(self.dude.dudes[node.name].node())
                    self.dude.dudes[node.name].removeNode()
                    self.hud.update(self.redDudesCount, self.blueDudesCount)
                    del self.dude.dudes[node.name]

        return Task.cont

    def setPhysicsWorld(self, _physicsworld):
    	self.physics_world = _physicsworld

    #### LOADERS ####
    def loadLevel(self, _filename):
        self.builder.parseEggFile(_filename)


    def loadLights(self):
        # Set a simple light
        dlight = DirectionalLight('DirectLight')
        dlnp = render.attachNewNode(dlight)
        dlnp.setHpr(-30, 0, 0)
        render.setLight(dlnp)
        self.directLight = dlnp

        self.discoLights = []

        p1 = PointLight("PointLight1")
        p1.setColor(VBase4(1, 0, 0, 1))
        p1.setAttenuation((0.08, 0, 0.05))
        p1np = render.attachNewNode(p1)
        p1np.setPos(0, -5, 0)
        render.setLight(p1np)
        self.discoLights.append(p1)

        p2 = PointLight("PointLight2")
        p2.setColor(VBase4(0, 1, 0, 1))
        p2.setAttenuation((0.08, 0, 0.05))
        p2np = render.attachNewNode(p2)
        p2np.setPos(5, -5, 0)
        render.setLight(p2np)
        self.discoLights.append(p2)

        p3 = PointLight("PointLight3")
        p3.setColor(VBase4(0, 0, 1, 1))
        p3.setAttenuation((0.08, 0, 0.05))
        p3np = render.attachNewNode(p3)
        p3np.setPos(-5, -5, 0)
        render.setLight(p3np)
        self.discoLights.append(p3)

        p4 = PointLight("PointLight4")
        p4.setColor(VBase4(0, 0, 1, 1))
        p4.setAttenuation((0.08, 0, 0.05))
        p4np = render.attachNewNode(p4)
        p4np.setPos(-5, -5, 5)
        render.setLight(p4np)
        self.discoLights.append(p4)

        p5 = PointLight("PointLight1")
        p5.setColor(VBase4(0, 0, 1, 1))
        p5.setAttenuation((0.08, 0, 0.05))
        p5np = render.attachNewNode(p5)
        p5np.setPos(0, -5, 5)
        render.setLight(p5np)
        self.discoLights.append(p5)

        p6 = PointLight("PointLight1")
        p6.setColor(VBase4(0, 0, 1, 1))
        p6.setAttenuation((0.08, 0, 0.05))
        p6np = render.attachNewNode(p6)
        p6np.setPos(5, -5, 5)
        render.setLight(p6np)
        self.discoLights.append(p6)

    def discoLightTask(self, task):
        self.elapsed += globalClock.getDt()

        if self.elapsed > 0.75:
            for light in self.discoLights:
                newcolor = choice(
                    [VBase4(0, 0, 1, 1),
                    VBase4(0, 1, 0, 1),
                    VBase4(1, 0, 0, 1),
                    VBase4(0, 1, 1, 1),
                    VBase4(1, 0, 1, 1),
                    VBase4(1, 1, 0, 1),]
                    )
                light.setColor(newcolor)
            self.elapsed = 0.0
        return task.cont

    def loadPlayer(self, _name):
        self.player = Player(self)
        self.player.start()

    def loadDude(self):
        self.dude = Dude(self)
        self.dude.start()
コード例 #51
0
ファイル: game.py プロジェクト: arximboldi/pigeoncide
class Game (GameState):

    def do_setup (self, level):
        super (Game, self).do_setup ()
                
        self.level = level
        
        self.setup_panda ()
        self.level.setup_entities (self.entities)
        self.setup_input ()
        self.setup_controllers ()
        self.setup_hud ()
        self.setup_logic ()
        self.enter_transition ()
        
        self.events.event ('panda-escape').connect (self.enter_menu)
        self.events.event ('panda-p').connect (self.toggle_pause)

        self.manager.enter_state (
            GameMessage, message =
            (('You have to kill %i pigeons in this level...\n' +
             'Can you make it?') % self.total_pigeons))

    def enter_transition (self):
        self._transition_bg = ui.ImageEntity (entities = self.entities,
                                              image    = 'hud/red-bg.png')
        self._transition_bg.alpha = 1.0
        self._transition_bg.fade_out ()

    def leave_transition (self, next_st = 'menu'):
        self._transition_bg.fade_in ().add_next (task.run (lambda:
            self.manager.leave_state (last_state = next_st)))

    def enter_menu (self):
        self.manager.enter_state ('menu-noload', None, 'ingame')        
        
    @weak_slot
    def on_kill_pigeon (self):
        self.hud.dec_counter ('pigeons', 1)
        self.dead_pigeons += 1
        if self.dead_pigeons >= self.total_pigeons:
            self.win_game ()

    @weak_slot
    def on_kill_boy (self):
        self.fail_game (random.choice (['You are dead!',
                                        'Was it that hard to stay alive?',
                                        "Your soul is burning in hell..."]))

    @weak_slot
    def on_finish_time (self):
        self.fail_game (random.choice (['No more time for you!',
                                        'Too slow man...',
                                        'Hurry up the next time!']))
        
    def win_game (self):
        if self.manager.current == self:
            self.manager.enter_state (
                GameMessage,
                'YOU WON!\n'
                'This was a show-case level of an in-development game,\n'
                'there is more to come in the future.',
                'quit')
            
    def fail_game (self, reason):
        if self.manager.current == self:
            msg = random.choice (['LOOOOOOOOSER', 'You lost!', 'What a pity!',
                                  'Hey, no luck today!'])
            self.manager.enter_state (GameMessage, reason + '\n' + msg, 'retry')
    
    @weak_slot
    def on_place_stick (self):
        if self.player_ctl.can_place_stick:
            self.num_sticks -= 1
            if self.num_sticks == 0:
                self.player_ctl.can_place_stick = False
            self.hud.set_counter ('sticks', self.num_sticks)

    def highlight_stick_task (self, timer):
        pos = self.player_ctl.get_place_position (5)
        best = self.player_ctl.laser.best_stick (pos)
        if best != self._curr_best_stick:
            if self._curr_best_stick:
                self._curr_best_stick.unhighlight ()
            if self.player_ctl.can_place_stick:
                self._curr_best_stick = best
                if best:
                    best.highlight ()
        return task.running
    
    def do_update (self, timer):
        super (Game, self).do_update (timer)

    @weak_slot
    def on_shader_change (self, cfg):
        if cfg.value:
            self.glow_filter.enable (self.manager.panda)
        else:
            self.glow_filter.disable ()
    
    @weak_slot
    def on_control_change (self, cfg):
        self.player_input.unassoc_action (cfg.name)
        if cfg.value:
            self.player_input.assoc (cfg.name, cfg.value)
    
    def setup_panda (self):
        self.glow_filter = shader.GlowFilter ()
        
        panda = self.manager.panda
        if GlobalConf ().path ('game.shader').value:
            self.glow_filter.enable (panda)        
        panda.relative_mouse ()
        panda.loop_music (self.level.music)

    def setup_input (self):
        self.player_input = GameInput ()
        self.camera_input = GameInput (CAMERA_INPUT_MAP)
        self.events.connect (self.player_input)
        self.events.connect (self.camera_input)
        self.tasks.add (self.player_input)
        self.tasks.add (self.camera_input)        

        self.player_input.assoc ('on_steer', 'panda-mouse-move')

        cfg = GlobalConf ().path ('game.player0.keys')
        for c in cfg.childs ():
            if c.value:
                self.player_input.assoc (c.name, c.value)
            c.on_conf_change += self.on_control_change
        GlobalConf ().path ('game.shader').on_conf_change += \
            self.on_shader_change

    def setup_controllers (self):
        self.camera_ctl = CameraController (
            entities = self.entities,
            camera = base.camera)
        self.player_ctl = PlayerController (
            entities = self.entities,
            delegate = self.level.boy)
        self.level.boy.connect (self.camera_ctl)
        self.camera_input.connect (self.camera_ctl)
        self.player_input.connect (self.player_ctl)
    
    def setup_hud (self):
        self.hud = Hud (entities = self.entities)
        self.hud.add_counter ('clock',   'hud/clock.png')
        self.hud.add_counter ('pigeons', 'hud/pigeon.png')
        self.hud.add_counter ('sticks',  'hud/stick.png')
        self.hud.hide ()
    
    def setup_logic (self):
        total_pigeons = 0
        for f in self.level.flocks:
            total_pigeons += len (f.boids)
            for b in f.boids:
                b.on_death += self.on_kill_pigeon
        
        self.total_pigeons = total_pigeons
        self.dead_pigeons = 0
        self.level.boy.on_death += self.on_kill_boy

        self.num_sticks = self.level.max_sticks
        self.player_ctl.on_place_stick_down += self.on_place_stick
        self.hud.set_counter ('sticks', self.num_sticks)
        
        self.timer = self.tasks.add (
            task.TimerTask (duration = self.level.max_time))
        self.timer.on_tick = lambda: self.hud.set_counter (
            'clock', int (self.timer.remaining))
        self.timer.on_finish = self.on_finish_time

        self.tasks.add (self.highlight_stick_task)
        self._curr_best_stick = None

        self.pigeon_food = []
        
    def do_sink (self):
        super (Game, self).do_sink ()
        if self.manager.current.state_name == 'menu-noload':
            for x in self.entities.entities:
                if isinstance (x, task.Task):
                    x.pause ()        
        self.events.quiet = True
        self.hud.soft_hide ()
        self.timer.pause ()
        
    def do_unsink (self, action = 'continue'):
        super (Game, self).do_unsink ()
        self.manager.panda.relative_mouse ()
        self.tasks.resume ()
        for x in self.entities.entities:
            if isinstance (x, task.Task):
                x.resume ()
        if action == 'continue':
            self.events.quiet = False
            self.hud.soft_show ()
            self.timer.resume ()
        elif action == 'quit':
            self.leave_transition ()
        elif action == 'retry':
            self.leave_transition ('game')
        
    def do_release (self):
        self.level.dispose () # TODO: To entity!
        self.glow_filter.disable ()
        super (Game, self).do_release ()
コード例 #52
0
ファイル: main.py プロジェクト: USMAnss/Pybrawl
def playGame(character1, character2):
    pygame.init()
    pygame.mixer.init()
    pygame.mixer.music.load("Sound/07 - The Raising Fighting Spirit.ogg") #Background music "The Rising Fighting Spirit":http://downloads.khinsider.com/game-soundtracks/album/naruto-original-soundtrack-1
    pygame.mixer.music.play(-1)
    displaysurf = pygame.display.set_mode((WIDTH, HEIGHT))
    clock = pygame.time.Clock()
    player1=Character(PLAYER1_CONTROLS, IMAGES[character1], SOUNDS[character1], PLAYER1_POSITION)
    player2=Character(PLAYER2_CONTROLS, IMAGES[character2], SOUNDS[character2], PLAYER2_POSITION)
    HUD1_IMAGES=HUD_IMAGES.copy()
    HUD1_IMAGES["icon"]=IMAGES[character1]["icon"]
    HUD2_IMAGES=HUD_IMAGES.copy()
    HUD2_IMAGES["icon"]=IMAGES[character2]["icon"]
    player1_hud=Hud(HUD1_IMAGES, LEFT_HUD_POSITION)
    player2_hud=Hud(HUD2_IMAGES, RIGHT_HUD_POSITION)
    player2_hud.flip()
    background=load_image("Background/training_background.png") #http://spritedatabase.net/game/1889
    background=pygame.transform.scale(background, (WIDTH, HEIGHT))
    player1_wins=load_image("Background/player1wins.png") #Used the folowing website to generate the win signs: http://www.dafont.com/ninja-naruto.font
    player2_wins=load_image("Background/player2wins.png")
    pygame.display.set_caption('Pybrawl')
    game_over=False
    while True: # main game loop
        displaysurf.blit(background, (0,0))
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN and event.key == K_RETURN and game_over:
                return

        if player1.health==0:
            game_over=True
            pygame.mixer.music.stop()
            displaysurf.blit(player2_wins, (172, 200))

        if player2.health==0:
            game_over=True
            pygame.mixer.music.stop()
            displaysurf.blit(player1_wins, (172, 200))

        keys_status=pygame.key.get_pressed()
        if game_over:
            keys_status=[False for i in keys_status]

        player1.update(keys_status)
        player2.update(keys_status)

        collide(player1, player2)

        keep_inside(player1)
        keep_inside(player2)

        if player1.rect.centerx < player2.rect.centerx:
            player1.direction="right"
            player2.direction="left"
        else:
            player1.direction="left"
            player2.direction="right"

        player1_hud.update(player1.health/player1.max_health,
                           player1.mana/player1.max_mana)
        player2_hud.update(player2.health/player2.max_health,
                           player2.mana/player2.max_mana)

        player1.draw(displaysurf)
        player2.draw(displaysurf)
        player1_hud.draw(displaysurf)
        player2_hud.draw(displaysurf)
        pygame.display.update()
コード例 #53
0
ファイル: client.py プロジェクト: gjmiles/adventure_pygame
def main():
    """ Main Program """
    pygame.init()

    # Set the height and width of the screen
    size = [SCREEN_WIDTH, SCREEN_HEIGHT]
    screen = pygame.display.set_mode(size)

    pygame.display.set_caption("Dungeon Dreams Demo")

    # Create the player
    map_pix_size = 30

    # Create all the levels
    level_list = []
    #    level_list.append( Level_01(player) )

    # Set the current level
    current_level_no = 0
    current_level = 0
    #    current_level = level_list[current_level_no]

    active_sprite_list = pygame.sprite.Group()

    # Loop until the user clicks the close button.
    done = False

    # Used to manage how fast the screen updates
    clock = pygame.time.Clock()
    all_sprites_list = pygame.sprite.LayeredDirty()
    collid_list = pygame.sprite.LayeredDirty()
    mobiles_list = pygame.sprite.Group()
    m_attacks = pygame.sprite.Group()
    area = None
    image_files = glob.glob('HumanMage.PNG')
    hud = Hud(screen)
    player = Player(100, 100, image_files, hud)
    hud.display_player_stats(player.stats)
    player.set_all_sprites(all_sprites_list)
    screen_size = (screen.get_width(), screen.get_height())
    m_fact = Monster_Factory(area, collid_list, 50, screen_size,
                             all_sprites_list, player)
    map_tool = Map_Handler(screen, all_sprites_list, collid_list, player,
                           mobiles_list, m_fact, hud)
    map_tool.build_area()
    item_fact = map_tool.get_item_fact()

    shift_x = 0
    shift_y = 0

    all_mobiles = m_fact.get_mobiles_group()
    dam_mod = 1
    #init path finding...
    path_finder = a_star(collid_list, 50)
    player.group_add(all_mobiles)

    image_files = glob.glob('*.PNG')

    #init events for following and monsters, start at 3 seconds because
    #player needs a second or two catch bearings
    FOLLOW_EVENT = USEREVENT + 1
    M_ATTACK_EVENT = USEREVENT + 2
    pygame.time.set_timer(FOLLOW_EVENT, 3000)
    pygame.time.set_timer(M_ATTACK_EVENT, 3000)
    game_start = False
    #-------- Main Program Loop -----------
    while not done:

        #Probably would make a class just to handle
        #client events.
        #These handle the movements
        keys = pygame.key.get_pressed()
        if keys[pygame.K_h]:
            player.changespeed(-1, 0)
        if keys[pygame.K_l]:
            player.changespeed(1, 0)
        if keys[pygame.K_k]:
            player.changespeed(0, -1)
        if keys[pygame.K_j]:
            player.changespeed(0, 1)
        if keys[pygame.K_n]:
            player.changespeed(1, 1)
        if keys[pygame.K_b]:
            player.changespeed(-1, 1)
        if keys[pygame.K_y]:
            player.changespeed(-1, -1)
        if keys[pygame.K_u]:
            player.changespeed(1, -1)

        #More events, quit and attacks and stopping the player
        #when the button goes up.
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True

            player.check_events(event)

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    r_attack = player.ranged_attack(all_sprites_list, None,
                                                    player.r_attack_images,
                                                    dam_mod)
                    m_fact.set_check_attack(r_attack)

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_h:
                    player.stop()
                if event.key == pygame.K_y:
                    player.stop()
                if event.key == pygame.K_k:
                    player.stop()
                if event.key == pygame.K_u:
                    player.stop()
                if event.key == pygame.K_l:
                    player.stop()
                if event.key == pygame.K_n:
                    player.stop()
                if event.key == pygame.K_j:
                    player.stop()
                if event.key == pygame.K_b:
                    player.stop()

            #Really for testing pathfinding, pathfinding is really for monsters.
            if event.type == pygame.MOUSEBUTTONUP:
                pos = pygame.mouse.get_pos()
                player.follow_path(path_finder.get_path(player.get_pos(), pos),
                                   map_pix_size, pos)

            #Monsters follow every two seconds to cut down on pathfinding
            #Calculations
            if event.type == FOLLOW_EVENT:
                m_fact.monster_group_follow(player.get_pos())
                pygame.time.set_timer(FOLLOW_EVENT, 2000)

            #Attack every second which is kind of a lot still
            #Otherwise player would get hurt too fast or too slow.
            if event.type == M_ATTACK_EVENT:
                m_attacks = m_fact.monsters_attack(player.get_pos())
                player.set_check_attack(m_attacks)
                pygame.time.set_timer(M_ATTACK_EVENT, 1000)

        #Move the player and then check for game end or picked up item.
        player_pos = player.move(collid_list, all_mobiles)
        lost = player.damaged()
        m_fact.move_monsters(all_mobiles)
        got_item = item_fact.is_picked_up()
        #For now just one item and if it is picked up the player wins.
        if got_item:
            end_text = []
            end_text.append(
                'You Found the Scepter of Yendor and Won the Game!')
            end_text.append('To replay press r!')
            end_text.append('To quit press q!')
            end_text.append('To continue press Space Bar!')
            done = game_end(True, end_text, screen, map_tool)
            map_tool.map_move(0, 0)
            player.stop()
            player.ranged_item = 3
            player.speed = 8
            player.dam_mod = 10
        elif (lost):
            end_text = []
            end_text.append('You perished!')
            end_text.append('To replay press r!')
            end_text.append('To quit press q!')
            done = game_end(False, end_text, screen, map_tool)

        if (map_tool.map_section_change(player_pos)):
            area = map_tool.get_area()
            m_fact.gen_monsters(area)

        player.is_moving(map_pix_size)
        all_mobiles.update(None, None)
        if m_attacks:
            m_attacks.update()
        all_sprites_list.draw(screen)

        clock.tick(25)
        pygame.display.flip()

    pygame.quit()
コード例 #54
0
ファイル: run.py プロジェクト: erszcz/agrajag
def run():
    pygame.init()
    random.seed()

    display_size = 800, 600
    viewport_size = display_size[0], 600
    black = 0, 0, 0
    red = 255, 70, 70
    green = 70, 255, 70
    blue = 70, 70, 255
    white = 255, 255, 255

    l_green = 50, 255, 0

    screen = pygame.display.set_mode(display_size)
    screen.fill(black)

    clock = Clock(readonly=False)

    dbman = DBManager()
    dbman.import_db("./db")

    gfxman = GfxManager()
    gfxman.import_gfx(dbman.get(), "./gfx")

    stagemanager = StageManager()
    stagemanager.import_stages("./stages")
    stages = stagemanager.get()

    groupmanager = GroupManager()

    g_draw = groupmanager.add("draw", "OrderedUpdates")
    g_ship = groupmanager.add("ship")
    g_enemies = groupmanager.add("enemies")
    g_enemy_projectiles = groupmanager.add("enemy_projectiles")
    g_player_projectiles = groupmanager.add("player_projectiles")
    g_beams = groupmanager.add("beams")
    g_explosions = groupmanager.add("explosions")
    g_shields = groupmanager.add("shields")
    g_bonuses = groupmanager.add("bonuses")

    hud = Hud(viewport_size)

    g_enemies.add(Obstacle((60, 30)))
    g_enemies.add(MovingObstacle((160, 80)))

    g_bonuses.add(RechargeBonus((300, 200)))
    g_bonuses.add(SuperShieldBonus((500, 300)))
    g_bonuses.add(ShieldUpgradeBonus((500, 500)))
    g_bonuses.add(ShieldUpgradeBonus((300, 500)))

    ship = ref(PlayerShip((175, viewport_size[1] - 60), g_ship))
    hud.setup_connections(ship())

    back = SpaceBackground(viewport_size)

    for stage_name in sorted(stages.keys()):
        stage_clock = 0
        while True:
            for spawn_time in stages[stage_name]["spawn"]:
                if spawn_time <= stage_clock:
                    while stages[stage_name]["spawn"][spawn_time]:
                        spawn = stages[stage_name]["spawn"][spawn_time].pop()
                        pos = spawn["x"], spawn["y"]

                        object_cls = eval(spawn["object_cls_name"])
                        if spawn["object_base_cls_name"]:
                            if spawn["object_base_cls_name"] == "Projectile":
                                if not spawn.has_key("object_params"):
                                    raise ValueError, "Params for projectile '%s' in stage %s \
                      not set" % (
                                        spawn["object_cls_name"],
                                        stage_name,
                                    )

                                if not spawn["object_params"].has_key("dir"):
                                    raise ValueError, "Invalid 'dir' for projectile '%s' in \
                      stage %s" % (
                                        spawn["object_cls_name"],
                                        stage_name,
                                    )

                                if not spawn["object_params"].has_key("collision_group"):
                                    raise ValueError, "Invalid 'collision_group' for projectile \
                      '%s' in stage %s" % (
                                        spawn["object_cls_name"],
                                        stage_name,
                                    )

                                params = spawn["object_params"]

                                dir = params["dir"]
                                g_coll = groupmanager.get(params["collision_group"])
                                object = object_cls(pos, dir, g_coll)

                            elif spawn["object_base_cls_name"] == "Bonus":
                                pass
                            else:
                                raise ValueError, "Invalid value '%s' for attrubite \
                    'object_base_cls_name' in stage %s" % (
                                    spawn["object_base_cls_name"],
                                    stage_name,
                                )
                        else:
                            object = object_cls(pos)

                        if spawn["bonus_cls_name"]:
                            if isinstance(object, BonusHolder):
                                object.set_bonus(spawn["bonus_cls_name"], spawn["bonus_params"])
                            else:
                                raise ValueError, "Instances of %s can not hold bonuses." % object.__class__.__name__

                        if spawn["mover_cls_name"]:
                            mover_cls = eval("mover.%s" % spawn["mover_cls_name"])
                            m = mover_cls(pos, object.max_speed, spawn["mover_params"])
                            object.set_mover(m)

                        for g in spawn["groups"]:
                            if g == "enemies":
                                g_enemies.add(object)
                            elif g == "explosions":
                                g_explosions.add(object)
                            elif g == "enemy_projectiles":
                                g_enemy_projectiles.add(object)
                            elif g == "player_projectiles":
                                g_player_projectiles.add(object)

            # time management
            clock.tick(40)
            # clock.tick( float(sys.argv[1]) )
            stage_clock += clock.get_time()

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        sys.exit()
                    elif event.key == pygame.K_s:
                        if ship():
                            ship().next_weapon()
                    elif event.key == pygame.K_a:
                        if ship():
                            ship().previous_weapon()
                    elif event.key == pygame.K_x:
                        if ship():
                            ship().activate_shield(True)
                elif event.type == pygame.KEYUP:
                    if event.key == pygame.K_UP:
                        if ship():
                            ship().fly_up(False)
                    elif event.key == pygame.K_x:
                        if ship():
                            ship().activate_shield(False)

            pressed_keys = pygame.key.get_pressed()
            if pressed_keys[pygame.K_UP]:
                if ship():
                    ship().fly_up(True)
            if pressed_keys[pygame.K_DOWN]:
                if ship():
                    ship().fly_down(viewport_size[1])
            if pressed_keys[pygame.K_LEFT]:
                if ship():
                    ship().fly_left()
            if pressed_keys[pygame.K_RIGHT]:
                if ship():
                    ship().fly_right(viewport_size[0])
            if pressed_keys[pygame.K_z]:
                if ship():
                    ship().shoot()

            back.clear(screen, clear_bg)
            back.update()
            back.draw(screen)

            # temp
            # if ship():
            #  ship().damage(1)
            #

            g_draw.clear(screen, clear_bg)
            hud.clear(screen, clear_bg)

            g_draw.update()
            hud.update()

            g_draw.draw(screen)
            hud.draw(screen)

            pygame.display.flip()
コード例 #55
0
walltorch_bottomright.rect.y = 64 * 7
walltorch_lefttop = WallTorch(Character.Direction.LEFT)
walltorch_lefttop.rect.x = 0
walltorch_lefttop.rect.y = 64 * 2
walltorch_leftbottom = WallTorch(Character.Direction.LEFT)
walltorch_leftbottom.rect.x = 0
walltorch_leftbottom.rect.y = 64 * 5

cricket = Cricket()
cricket.loadSprites()

crabzone = Rect(left_wall.rect.right + 64, top_wall.rect.bottom + 64, right_wall.rect.left - left_wall.rect.width - 128, bottom_wall.rect.top - top_wall.rect.height - 128)
crabspawner = CrabSpawner(crabzone)

hud_space = Rect(0, bottom_wall.rect.bottom, width, height - left_wall.rect.height)
hud = Hud(hud_space)
hud.registerListeners(cricket, crabspawner)

clock = pygame.time.Clock()

#display.fill(blue)
pygame.display.flip()

while 1:
    clock.tick(60)
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): 
            sys.exit()
        if((event.type == KEYDOWN) or (event.type == KEYUP)):
            keyhandler.handle(event)
コード例 #56
0
class Main(ShowBase, FSM):
    """Main function of the application
    initialise the engine (ShowBase)"""
    def __init__(self):
        """initialise the engine"""
        ShowBase.__init__(self)
        FSM.__init__(self, "FSM-Game")

        #
        # BASIC APPLICATION CONFIGURATIONS
        #
        # disable pandas default camera driver
        self.disableMouse()
        # set background color to black
        self.setBackgroundColor(0, 0, 0)
        # set antialias for the complete sceen to automatic
        self.render.setAntialias(AntialiasAttrib.MAuto)
        # shader generator
        render.setShaderAuto()

        #
        # CONFIGURATION LOADING
        #
        # load given variables or set defaults
        # check if audio should be muted
        mute = ConfigVariableBool("audio-mute", False).getValue()
        if mute:
            self.disableAllAudio()
        else:
            self.enableAllAudio()
        # check if particles should be enabled
        particles = ConfigVariableBool("particles-enabled", True).getValue()
        if particles:
            self.enableParticles()
        # check if the config file hasn't been created
        if not os.path.exists(prcFile):
            # get the displays width and height
            w = self.pipe.getDisplayWidth()
            h = self.pipe.getDisplayHeight()
            # set window properties
            # clear all properties not previously set
            base.win.clearRejectedProperties()
            # setup new window properties
            props = WindowProperties()
            # Fullscreen
            props.setFullscreen(True)
            # set the window size to the screen resolution
            props.setSize(w, h)
            # request the new properties
            base.win.requestProperties(props)
        elif base.appRunner:
            # As when the application is started as appRunner instance
            # it doesn't respect our loadPrcFile configurations specific
            # to the window, hence we need to manually set them here.
            for dec in range(mainConfig.getNumDeclarations()):
                #TODO: Check for all window specific variables like
                #      fullscreen, screen size, title and window
                #      decoration that you have in your configuration
                #      and set them by your own.
                if mainConfig.getVariableName(dec) == "fullscreen":
                    if not mainConfig.getDeclaration(dec).getBoolWord(0): break
                    # get the displays width and height
                    w = self.pipe.getDisplayWidth()
                    h = self.pipe.getDisplayHeight()
                    # set window properties
                    # clear all properties not previously set
                    base.win.clearRejectedProperties()
                    # setup new window properties
                    props = WindowProperties()
                    # Fullscreen
                    props.setFullscreen(True)
                    # set the window size to the screen resolution
                    props.setSize(w, h)
                    # request the new properties
                    base.win.requestProperties(props)
                    break

        # automatically safe configuration at application exit
        base.exitFunc = self.__writeConfig

        # due to the delayed window resizing and switch to fullscreen
        # we wait some time until everything is set so we can savely
        # proceed with other setups like the menus
        if base.appRunner:
            # this behaviour only happens if run from p3d files and
            # hence the appRunner is enabled
            taskMgr.doMethodLater(0.5,
                                  self.postInit,
                                  "post initialization",
                                  extraArgs=[])
        else:
            self.postInit()

    def postInit(self):
        #
        # initialize game content
        #
        base.cTrav = CollisionTraverser("base collision traverser")
        base.pusher = CollisionHandlerPusher()
        self.menu = Menu()
        self.credits = Credits()
        self.charSelection = CharacterSelection()
        self.levelSelection = LevelSelection()
        self.koScreen = KoScreen()
        self.hud = Hud()
        self.menuMusic = loader.loadMusic("assets/audio/menuMusic.ogg")
        self.menuMusic.setLoop(True)
        self.fightMusic = loader.loadMusic("assets/audio/fightMusic.ogg")
        self.fightMusic.setLoop(True)
        base.audio3d = Audio3DManager(base.sfxManagerList[0], camera)

        #
        # Event handling
        #
        self.accept("escape", self.__escape)

        #
        # Start with the menu
        #
        self.request("Menu")

    #
    # FSM PART
    #
    def enterMenu(self):
        show_cursor()
        self.accept("Menu-Start", self.request, ["CharSelection"])
        self.accept("Menu-Credits", self.request, ["Credits"])
        self.accept("Menu-Quit", self.quit)
        self.ignore("KoScreen-Back")
        self.koScreen.hide()
        self.menu.show()
        if self.menuMusic.status() != AudioSound.PLAYING:
            self.menuMusic.play()
        if self.fightMusic.status() == AudioSound.PLAYING:
            self.fightMusic.stop()

    def exitMenu(self):
        self.ignore("Menu-Start")
        self.ignore("Menu-Credits")
        self.ignore("Menu-Quit")
        self.menu.hide()

    def enterCredits(self):
        self.accept("Credits-Back", self.request, ["Menu"])
        self.koScreen.hide()
        self.credits.show()

    def exitCredits(self):
        self.ignore("Credits-Back")
        self.credits.hide()

    def enterCharSelection(self):
        self.accept("CharSelection-Back", self.request, ["Menu"])
        self.accept("CharSelection-Start", self.request, ["LevelSelection"])
        self.charSelection.show()

    def exitCharSelection(self):
        self.ignore("CharSelection-Start")
        self.ignore("CharSelection-Back")
        self.charSelection.hide()
        self.selectedChar1 = self.charSelection.selectedCharacter1
        self.selectedChar2 = self.charSelection.selectedCharacter2

    def enterLevelSelection(self):
        self.accept("LevelSelection-Back", self.request, ["CharSelection"])
        self.accept("LevelSelection-Start", self.request, ["Game"])
        self.levelSelection.show()

    def exitLevelSelection(self):
        self.ignore("LevelSelection-Start")
        self.ignore("LevelSelection-Back")
        self.levelSelection.hide()

    def enterGame(self):
        # main game code should be called here
        self.arena = Arena(self.levelSelection.selectedLevel)
        self.arena.start()
        self.camera.setPos(0, -5, 1.25)
        self.player = Player(0, self.selectedChar1, "p1")
        self.player2 = Player(1, self.selectedChar2, "p2")
        self.player.setEnemy(self.player2.collisionNodeName)
        self.player2.setEnemy(self.player.collisionNodeName)
        self.player.start(self.arena.getStartPos(1))
        self.player2.start(self.arena.getStartPos(2))
        self.taskMgr.add(self.updateWorldCam, "world camera update task")
        self.accept("gameOver", self.gameOver)
        self.hud.show()

        def lifeChanged(charId, health):
            base.messenger.send("hud_setLifeBarValue", [charId, health])

        self.accept("lifeChanged", lifeChanged)
        hide_cursor()
        if self.fightMusic.status() != AudioSound.PLAYING:
            self.fightMusic.play()
        if self.menuMusic.status() == AudioSound.PLAYING:
            self.menuMusic.stop()

    def exitGame(self):
        # cleanup for game code
        self.taskMgr.remove("world camera update task")
        self.player.stop()
        self.player2.stop()
        del self.player
        del self.player2
        self.arena.stop()
        self.ignore("gameOver")
        self.ignore("lifeChanged")
        self.hud.hide()

    #
    # FSM PART END
    #

    #
    # BASIC FUNCTIONS
    #
    def gameOver(self, LoosingCharId):
        show_cursor()
        winningChar = 1
        if LoosingCharId == 0:
            winningChar = 2
        self.accept("KoScreen-Back", self.request, ["Credits"])
        self.koScreen.show(winningChar)

    def updateWorldCam(self, task):
        playerVec = self.player.getPos() - self.player2.getPos()
        playerDist = playerVec.length()
        x = self.player.getX() + playerDist / 2.0
        self.camera.setX(x)

        zoomout = False
        if not self.cam.node().isInView(self.player.getPos(self.cam)):
            camPosUpdate = -2 * globalClock.getDt()
            self.camera.setY(self.camera, camPosUpdate)
            zoomout = True
        if not self.cam.node().isInView(self.player2.getPos(self.cam)):
            camPosUpdate = -2 * globalClock.getDt()
            self.camera.setY(self.camera, camPosUpdate)
            zoomout = True
        if not zoomout:
            if self.camera.getY() < -5:
                camPosUpdate = 2 * globalClock.getDt()
                self.camera.setY(self.camera, camPosUpdate)
        return task.cont

    def __escape(self):
        if self.state == "Menu":
            self.quit()
        elif self.state == "LevelSelection":
            self.request("CharSelection")
        else:
            self.request("Menu")

    def quit(self):
        """This function will stop the application"""
        self.userExit()

    def __writeConfig(self):
        """Save current config in the prc file or if no prc file exists
        create one. The prc file is set in the prcFile variable"""
        page = None

        #TODO: get values of configurations here
        particles = "#f" if not base.particleMgrEnabled else "#t"
        volume = str(round(base.musicManager.getVolume(), 2))
        mute = "#f" if base.AppHasAudioFocus else "#t"
        #TODO: add any configuration variable name that you have added
        customConfigVariables = [
            "", "particles-enabled", "audio-mute", "audio-volume"
        ]
        if os.path.exists(prcFile):
            # open the config file and change values according to current
            # application settings
            page = loadPrcFile(Filename.fromOsSpecific(prcFile))
            removeDecls = []
            for dec in range(page.getNumDeclarations()):
                # Check if our variables are given.
                # NOTE: This check has to be done to not loose our base or other
                #       manual config changes by the user
                if page.getVariableName(dec) in customConfigVariables:
                    decl = page.modifyDeclaration(dec)
                    removeDecls.append(decl)
            for dec in removeDecls:
                page.deleteDeclaration(dec)
            # NOTE: particles-enabled and audio-mute are custom variables and
            #       have to be loaded by hand at startup
            # Particles
            page.makeDeclaration("particles-enabled", particles)
            # audio
            page.makeDeclaration("audio-volume", volume)
            page.makeDeclaration("audio-mute", mute)
        else:
            # Create a config file and set default values
            cpMgr = ConfigPageManager.getGlobalPtr()
            page = cpMgr.makeExplicitPage("%s Pandaconfig" % appName)
            # set OpenGL to be the default
            page.makeDeclaration("load-display", "pandagl")
            # get the displays width and height
            w = self.pipe.getDisplayWidth()
            h = self.pipe.getDisplayHeight()
            # set the window size in the config file
            page.makeDeclaration("win-size", "%d %d" % (w, h))
            # set the default to fullscreen in the config file
            page.makeDeclaration("fullscreen", "1")
            # particles
            page.makeDeclaration("particles-enabled", "#t")
            # audio
            page.makeDeclaration("audio-volume", volume)
            page.makeDeclaration("audio-mute", "#f")
        # create a stream to the specified config file
        configfile = OFileStream(prcFile)
        # and now write it out
        page.write(configfile)
        # close the stream
        configfile.close()
コード例 #57
0
ファイル: screens.py プロジェクト: ashisdhara/python_game
class GameScreen(Events):
    """docstring for GameScreen"""
    def __init__(self, window):
        super(GameScreen, self).__init__()
        self.window = window
        self.camera = Camera(window)
        self.player = player.Player()
        self.proj_viewer = ProjectileViewer(self.send_center)
        self.controls = {}
        self.controls_old = {}
        self.map = Map('blank')
        #self.player.spawn(100, 100)
        self.time = 0
        self.moves = moves(1024)
        self.index = [0]
        self.head = [0]
        #other players
        self.players = {}
        self.specs = {}
        #crosshair
        self.cross = CrossHair()
        self.isSpec = True
        self.hud = Hud()
        self.gs_view = GameStateViewer(self.players, self.hud.update_prop,
                                       self.hud.set_score)

    def update(self, dt):
        dt = int(dt * 1000000) / 1000000.
        if self.controls['esc'] and not self.controls_old['esc']:
            self.send_message('menu_transition_+', (GameMenu, self.isSpec))

        if self.controls['rdy'] and not self.controls_old['rdy']:
            if not self.isSpec:
                self.ready_up()

        if self.controls['chat'] and not self.controls_old['chat']:
            self.send_message('menu_transition_+',
                              (ChatScreen, self.window))

        self.update_keys()
        self.on_update(dt)

    def update_physics(self, dt, state=False, input=False):
        playergen = (player.rect for player in self.players.itervalues())
        mapgen = (rect for rect in self.map.quad_tree.retrieve([],
                  self.player.rect))
        rectgen = chain(playergen, mapgen)
        self.player.update(dt, rectgen, state, input)
        return self.player.state

    def update_state_only(self, state):
        self.player.state.update(0, state)

    def update_keys(self):
        for key_, value in self.controls.items():
            self.controls_old[key_] = value

    def from_server(self, data):
        typ, data = data
        if typ == proto.playerUpdate:
            ind, time, s_state, inpt, weaponinfo = data
            smove = move(time, inpt, s_state)
            if ind == self.player.id:
                correct_client(self.update_physics, smove, self.moves,
                               self.head, self.index[0],
                               self.update_state_only)
                self.player.weapons.from_server(weaponinfo)
            else:
                #try:
                self.players[ind].client_update(s_state)
                self.players[ind].input = inpt
                #except KeyError:
                #    pass
        elif typ == proto.projectile:
            self.proj_viewer.process_proj(data)
        elif typ == proto.newPlayer:
            gs, data = data
            if gs == proto.goesSpec:
                ind, name, colstring = data
                new = player.Player()
                new.name = name
                new.id = ind
                new.set_color(colstring)
                self.specs[ind] = new
            #if there are existing players on the server
            elif gs == proto.wantsJoin:
                ind, name, state, time, colstring = data
                new = player.Player()
                new.name = name
                new.state = state
                new.time = time
                new.id = ind
                new.set_color(colstring)
                new.rect.update_color(new.color)
                self.players[ind] = new
                print 'new player: %s' % name
                self.gs_view.to_team(ind)
        elif typ == proto.disconnect:
            ind = data
            if ind in self.players:
                self.gs_view.leave(ind)
                del self.players[ind]
            elif ind in self.specs:
                del self.specs[ind]
        elif typ == proto.stateUpdate:
            gametime, data = data
            gs, ind = data
            self.gs_view.set_time(gametime)
            if gs == proto.wantsJoin:
                if ind == self.player.id:
                    self.send_message('menu_transition_-')
                    self.player.state.isDead = False
                    self.trans_to_game()
                else:
                    self.players[ind] = self.specs[ind]
                    del self.specs[ind]
                    self.gs_view.to_team(ind)
            elif gs == proto.goesSpec:
                if ind == self.player.id and self.isSpec:
                    pass
                elif ind == self.player.id and not self.isSpec:
                    self.send_message('menu_transition_-')
                    self.trans_to_spec()
                else:
                    self.specs[ind] = self.players[ind]
                    self.gs_view.leave(ind)
                    del self.players[ind]
            elif gs == proto.isDead:
                ind, killer, weapon = ind
                if ind == self.player.id:
                    self.player.die()
                else:
                    self.players[ind].die()
                self.gs_view.score(ind, killer, weapon)
            elif gs == proto.spawns:
                ind, pos = ind
                if ind == self.player.id:
                    self.player.spawn(*pos)
                else:
                    self.players[ind].spawn(*pos, other=True)
            elif gs == proto.isReady:
                ind, name = ind
                self.gs_view.is_ready(ind, name)
            elif gs == proto.countDown:
                self.player.freeze()
            elif gs == proto.inProgress:
                self.gs_view.start_game()
            elif gs == proto.warmUp:
                self.gs_view.to_warmup()
        elif typ == proto.mapUpdate:
            ind, itemid, gt, spawn = data
            self.gs_view.set_time(gt)
            if ind == self.player.id:
                if isinstance(self.map.items[itemid], Triangle):
                    st = self.map.items[itemid].keystr
                    if not st in self.player.weapons.weapons:
                        self.player.weapons.pickup(st)
                    else:
                        self.player.weapons.apply(st, self.player)
            self.map.serverupdate(itemid, spawn)
        elif typ == proto.chat:
            ind, msg = data
            if ind == self.player.id:
                name = self.player.name
                color = self.player.color
            elif ind in self.players:
                name = self.players[ind].name
                color = self.players[ind].color
            else:
                name = self.specs[ind].name
                color = self.specs[ind].color
            #chatdata = ' '.join((name + ':', '\t', msg))
            chatdata = (name, color, msg)
            self.hud.update_prop(chat=chatdata)

    def send_to_client(self, dt):
        temp_input = proto.Input()
        self.time += int(dt * 1000000)
        temp_input.CopyFrom(self.player.input)
        c_move = move(self.time, temp_input, self.player.state.copy())
        try:
            self.moves[self.index[0]] = c_move
        except IndexError:
            self.moves.append(c_move)
        self.moves.advance(self.index)
        self.send_message('input', (self.player.input, self.time))

    def spec_send(self, dt):
        self.send_message('input', (proto.Input(), self.time))

    def draw(self):
        self.on_draw()

    def on_connect(self, msg):
        ind, mapname, name = msg
        self.player.get_id(ind, name)
        self.map = Map(mapname)
        print 'connected with id: ' + str(self.player.id)
        #self.send_message('input', (self.player.input, 1337))
        self.gs_view.init_self(ind)
        self.trans_to_spec()

    def try_join(self):
        msg = proto.Message()
        msg.type = proto.stateUpdate
        plr = proto.Player()
        plr.id = self.player.id
        msg.player.CopyFrom(plr)
        if self.isSpec:
            msg.gameState = proto.wantsJoin
        else:
            msg.gameState = proto.goesSpec
        self.send_message('other', msg)

    def ready_up(self):
        msg = proto.Message()
        msg.type = proto.stateUpdate
        plr = proto.Player()
        plr.id = self.player.id
        msg.player.CopyFrom(plr)
        msg.gameState = proto.isReady
        self.send_message('other', msg)

    def send_chat(self, chatmsg):
        msg = proto.Message()
        msg.type = proto.chat
        plr = proto.Player()
        plr.id = self.player.id
        plr.chat = chatmsg
        msg.player.CopyFrom(plr)
        self.send_message('other', msg)

    def on_update(self, dt):
        pass

    def on_draw(self):
        pass

    def idle_update(self, dt):
        self.send_to_client(dt)
        self.gs_view.update(dt)
        self.hud.update(dt)

    def trans_to_spec(self):
        self.on_update = self.spec_update
        self.on_draw = self.spec_draw
        self.isSpec = True
        self.player.state.hook_hud(self.hud.update_prop)
        self.hud.init_spec()

    def trans_to_game(self):
        self.on_update = self.game_update
        self.on_draw = self.game_draw
        self.isSpec = False
        self.player.weapons.hook_hud(self.hud.update_prop)
        self.player.state.hook_hud(self.hud.update_prop)
        self.gs_view.add_self(self.player)
        self.hud.init_player(self.players)

    def game_update(self, dt):
        self.update_physics(dt)
        self.camera.update(dt, self.player.state)
        self.send_to_client(dt)
        self.proj_viewer.update(dt)
        self.gs_view.update(dt)
        self.hud.update(dt)

    def game_draw(self):
        self.camera.set_camera()
        for plr in self.players.itervalues():
            plr.draw()
        self.player.draw()
        self.proj_viewer.draw()
        self.map.draw()
        self.camera.set_static()
        self.hud.draw()
        self.cross.draw(*self.camera.mpos)

    def spec_update(self, dt):
        self.player.specupdate(dt)
        self.camera.update(dt, self.player.state)
        #self.send_to_client(dt)
        self.spec_send(dt)
        self.proj_viewer.update(dt)
        self.gs_view.update(dt)
        self.hud.update(dt)

    def spec_draw(self):
        self.camera.set_camera()
        for plr in self.players.itervalues():
            plr.draw()
        self.proj_viewer.draw()
        self.map.draw()
        self.camera.set_static()
        self.hud.draw()

    def send_center(self, ind):
        if ind == self.player.id:
            pl = self.player
            return pl.rect.center, (pl.input.mx, pl.input.my)
        else:
            pl = self.players[ind]
            return pl.rect.center, (pl.input.mx, pl.input.my)
コード例 #58
0
ファイル: main.py プロジェクト: lupo72/miner2011
class BasicMovement(Display):
    
    def __init__(self):
    
        self.framerate = 0 
        self.number_meanies = 16
        
        self.display = Display()
        self.hud = Hud()
        self.meanie_list = []
        pygame.key.set_repeat(100,5)
        self.meanies = pygame.sprite.Group()
        
        self.player = Charactor("held.png", self.display)
        self.player.speed = 2
       
        self.init_floors()
        self.init_ladders()
        self.barrels = pygame.sprite.Group()

        self.init_barrels()
        
        self.testgroup = pygame.sprite.Group()
        self.init_meanies(0)
        
        
    def init_floors(self):
        
        self.steine = pygame.sprite.Group()
        
        c = 0
        for y in range (300, self.display.bgmax[1], 200):

            if  c % 2 == 0:
                for x in range(self.display.bgmax[0]/2 + 64, self.display.bgmax[0], 32):
                    
                    s = Boden1([x,y])
                    self.steine.add(s)
            else:
                for x in range(64, self.display.bgmax[0]/2, 32):
                    
                    s = Boden1([x,y])
                    self.steine.add(s)
            
            c += 1
        
        del c

        ## Place a Floor at bottom of level
        for x in range(0,self.display.bgmax[0],32):
            s = Boden1([x, self.display.bgmax[1]-16])
            self.steine.add(s)


    def init_ladders(self):
        self.ladders = pygame.sprite.Group()
        
        for x in range(50, 700, 500):
            
            for y in range(0, self.display.bgmax[1], 32):
                
                i = Leiter([x,y])
                self.ladders.add(i)
        

    def init_barrels(self):

        for y in range(87, self.display.bgmax[1], 200):

            x = random.randint(0, self.display.bgmax[0])

            s = Fass([200, y])
            self.barrels.add(s)


    def init_meanies(self, counter):

        move_index = 0
        while counter < self.number_meanies:

            mx = random.randint( 0, self.display.bgmax[0]-40 )
            my = random.randint( 0, self.display.bgmax[1]-40 )

            meanie = Meanie()
            meanie.state.set_random_move_index()
            meanie.rect.center = mx,my
            self.testgroup.add(meanie)

            if meanie.overlaps(self.testgroup):
                self.testgroup.remove(meanie)
                meanie.kill()
                self.init_meanies(counter)
            else:
                self.meanie_list.insert(counter,meanie)
                self.meanies.add(self.meanie_list[counter])
                counter += 1

        if counter == self.number_meanies:
            self.start_game()


    def start_game(self):
        del self.testgroup
        self.gameRunning = True
        self.mainloop()

    def mainloop(self):
        self.clock = pygame.time.Clock()
        self.player.rect.center = [120,220]

        while self.gameRunning:

            dirty = []
            
            self.clock.tick(FPS)
            self.framerate = self.clock.get_fps()

            self.display.paint_background(dirty)

            self.player.state.set_current_state(self)

            # blit player on screen
            d = self.display.paint_sprite(self.player)
            dirty.insert(len(dirty), d)
            
            self.steine.update()
            self.ladders.update()
            self.barrels.update(self)
            self.meanies.update(self, dirty)
            self.hud.showinfo(self, dirty)

            for e in pygame.event.get():

                if e.type == QUIT:
                    self.gameRunning = False
                    pygame.quit()
                    sys.exit()
                elif e.type == KEYDOWN:
                    
                    if e.key == K_ESCAPE:
                        self.gameRunning = False
                        pygame.quit()
                        sys.exit()
                    elif e.key == K_UP and self.player.state.climbing:
                        self.player.movement[1]= - self.player.speed
                            
                    elif e.key == K_DOWN and not self.player.state.falling and self.player.state.climbing:
                        self.player.movement[1]= self.player.speed
                        
                    elif e.key == K_LEFT:
                        if self.player.state.falling:
                            self.player.movement[0] = - self.player.speed/2
                        else:
                            self.player.movement[0] = - self.player.speed
                        
                    elif e.key == K_RIGHT:  
                        if self.player.state.falling:
                            self.player.movement[0] = self.player.speed/2
                        else:
                            self.player.movement[0] = self.player.speed
                
                elif e.type == KEYUP:
                    if e.key == K_UP or e.key == K_DOWN:
                        self.player.movement[1] = 0
                    elif e.key == K_LEFT or e.key == K_RIGHT:
                        self.player.movement[0] = 0

            self.player.update(self)
            pygame.display.update(dirty)
コード例 #59
0
 def __init__(self, player):
     self.level_type = "none"
     self.background = None
     self.player = player
     self.hud = Hud()