当前位置: 首页>>代码示例>>Python>>正文


Python Ball.setPosition方法代码示例

本文整理汇总了Python中ball.Ball.setPosition方法的典型用法代码示例。如果您正苦于以下问题:Python Ball.setPosition方法的具体用法?Python Ball.setPosition怎么用?Python Ball.setPosition使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ball.Ball的用法示例。


在下文中一共展示了Ball.setPosition方法的2个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: Pong

# 需要导入模块: from ball import Ball [as 别名]
# 或者: from ball.Ball import setPosition [as 别名]

#.........这里部分代码省略.........
        self.add(self.fps_text)
        self.ball = Ball(self.width/2, self.height/2, "ball.png")
        self.add(self.ball)
        self.playerOne = Paddle(20, self.height/2, "paddle.png")
        self.add(self.playerOne)
        self.playerTwo = Paddle(320 - 20, self.height/2, "paddle.png")
        self.add(self.playerTwo)

        self.sfx_padOne = soundEffect("blip1.wav")
        self.sfx_padTwo = soundEffect("blip2.wav")
        self.music_bg = musicPlayer("UGH1.wav", -1)
        self.music_bg.play()

        self.start_game(False)

    def start_game(self, active):
        self.fps_text.set_active(active)
        self.scoreP1_text.set_active(active)
        self.scoreP1 = 0
        self.scoreP2_text.set_active(active)
        self.scoreP2 = 0
        self.ball.set_active(active)
        self.playerOne.set_active(active)
        self.playerTwo.set_active(active)
        self.fps_update = 0
        self.fps_count = 0
        self.start_game_text.set_active(not active)
        self.winner_text.set_active(not active)

    def show_end_game(self):
        self.ball.set_active(False)
        self.playerOne.set_active(True)
        self.playerTwo.set_active(True)
        self.fps_update = 0
        self.fps_count = 0
        self.winner_text.set_active(True)
        self.start_game_text.set_active(True)
        if self.scoreP1 > self.scoreP2:
            self.winner_text.set_text("Player 1 Wins")
        else:
            self.winner_text.set_text("Player 2 Wins")

    def update(self, delta_time):
        self.fps_update += 1
        self.fps_count += self.delta_time
        if self.fps_update >= 20:
            self.fps_count /= 20
            self.fps_text.set_text(str(int(1.0/(float(self.fps_count)/1000))))
            self.fps_count = 0
            self.fps_update = 0
        self.handleInput()

        if self.scoreP1 == self.max_score or self.scoreP2 == self.max_score:
            self.show_end_game()
        else:
            self.checkCollision()

    def checkCollision(self):
        if self.ball.checkCollision(self.playerOne.getRect()):
            self.sfx_padOne.play_sound()
            self.ball.negateXVel()
        if self.ball.checkCollision(self.playerTwo.getRect()):
            self.sfx_padTwo.play_sound()
            self.ball.negateXVel()
        # p2 scores
        if self.ball.getX() < 0:
            self.ball.setPosition([self.width/2, self.height/2])
            self.ball.negateXVel()
            self.scoreP2 += 1
            self.scoreP2_text.set_text(str(self.scoreP2))

        # p1 scores
        if self.ball.getX() > self.width:
            self.ball.setPosition([self.width/2, self.height/2])
            self.ball.negateXVel()
            self.scoreP1 += 1
            self.scoreP1_text.set_text(str(self.scoreP1))

    def handleInput(self):
        # quitting
        if pygame.key.get_pressed()[pygame.K_ESCAPE] != 0:
            sys.exit()

        if pygame.key.get_pressed()[pygame.K_RETURN] != 0:
            self.start_game(True)
        # playerone
        if pygame.key.get_pressed()[pygame.K_UP] != 0:
            self.playerOne.setVelocity([0, -.2])
        elif pygame.key.get_pressed()[pygame.K_DOWN] != 0:
            self.playerOne.setVelocity([0, .2])
        else:
            self.playerOne.setVelocity([0, 0])

        # playertwo
        if pygame.key.get_pressed()[pygame.K_SPACE] != 0:
            self.playerTwo.setVelocity([0, -.2])
        elif pygame.key.get_pressed()[pygame.K_LALT] != 0:
            self.playerTwo.setVelocity([0, .2])
        else:
            self.playerTwo.setVelocity([0, 0])
开发者ID:JackOfDawn,项目名称:GCW-Python,代码行数:104,代码来源:main.py

示例2: GameStateImpl

# 需要导入模块: from ball import Ball [as 别名]
# 或者: from ball.Ball import setPosition [as 别名]
class GameStateImpl(game_state_base.GameStateBase):
    __instance = None

    def __new__(cls):
        """Override the instantiation of this class. We're creating a singleton yeah"""
        return None

    def __init__(self):
        """ This shouldn't run.. We call __init__ on the __instance member"""
        #super(GameStateImpl, self).__init__()
        #self.SetName("Playing State")
        #print "GAMESTATE Playing State __init__ running (creating data members and method functions)"
        pass

    def Init(self, engineRef, takeWith=None):
		# Snag some vital object refs from the engine object
        self.game_size = engineRef.game_size
        self.screen_size = engineRef.screen_size
        self.cell_size = engineRef.cell_size
        self.surface_bg = engineRef.surface_bg
        self.game_viewport = engineRef.game_viewport
        self.bg_col = engineRef.bg_col
        self.mixer = engineRef.mixer

        # TODO perhaps move the loading of this config to the main game engine. Then, simply pass a reference to the config object into this function, rather than doing the loading here
        # Load config file
        with open(os.path.normpath(engineRef.exepath + '/../data/config/settings.json'), 'r+') as fd:
            cfgFromFile = json.load(fd)
        config = dot_access_dict.DotAccessDict(cfgFromFile)

        with open(os.path.normpath(engineRef.exepath + '/../data/scores/highscores.json'), 'r') as fd:
            highScores = json.load(fd)

        self.vital_stats = GameplayStats(config, highScores)
        # TODO - Fix Gameplaystats. Right now, it's a patchwork object that takes some items that were loaded in from a cfg file, but others that are hard-coded. The patchwork is an artifact of the patchwork design/implementation of this game (I'm adding things as I figure out how to, heh)

        self.ball = Ball()
        self.ball._accumulator_s[1] = 0.0
        self.ball.setPosition(32, 0) # Position is given in coordinates on the 64x64 grid. Actual screen coordinates are calculated from grid coordinates
        self.ball.setSpeed(0,1)
        self.ball.setMaxSpeed(1,1)
        self.ball.changeGameState(BallGameState.FREEFALL)
        #print "Changing ball game state to FREEFALL"

        self._eventQueue = MessageQueue() # Event queue, e.g. user key/button presses, system events
        self._eventQueue.Initialize(64)

        self.mm = DisplayMessageManager()

        self.rm = RowManager()
        self.rm.initLevel(self.vital_stats.initialRowSpacing, self.vital_stats.initialRowUpdateDelay, self.cell_size) 

        self.displayMsgScore = DisplayMessage()
        self.displayMsgScore.create(txtStr="Score: ", position=[66, 5], color=(192,192,192))

        self.displayMsgTries = DisplayMessage()
        self.displayMsgTries.create(txtStr="Tries: ", position=[66, 10], color=(192,192,192))
    
        self.displayMsgLevel = DisplayMessage()
        self.displayMsgLevel.create(txtStr="Level: ", position=[66, 20], color=(192,192,192))

        self.displayMsgCrushed = DisplayMessage()
        self.displayMsgCrushed.create(txtStr="Crushed :-(", position=[66, 30], color=(192,192,192))
    
        self.displayMsgGameOver = DisplayMessage()
        self.displayMsgGameOver.create(txtStr="GameOver :-(", position=[66, 32], color=(192,192,192))

        # Register Event Listeners
        self._eventQueue.RegisterListener('ball', self.ball.controlState, 'PlayerControl')
        self._eventQueue.RegisterListener('rowmgr', self.rm, 'Difficulty')
        self._eventQueue.RegisterListener('mixer', self.mixer, 'PlaySfx')
        self._eventQueue.RegisterListener('engine', engineRef, 'Application') # Register the game engine to listen to messages with topic, "Application"

        # Initialize sound effects
        # TODO make a class or some other smarter way to manage loading the sound effects
        self.mixer.addSfxFileToMap('gap'        , os.path.normpath(engineRef.exepath + '/../asset/audio/gap.wav'))
        self.mixer.addSfxFileToMap('crushed'    , os.path.normpath(engineRef.exepath + '/../asset/audio/explosion2.wav'))
        self.mixer.addSfxFileToMap('levelUp'    , os.path.normpath(engineRef.exepath + '/../asset/audio/powerup2.wav'))
        self.mixer.loadSfxFiles()
        self.mixer.setSfxVolume(config['mixer.sfxVol'] / 10.0)  # TODO Design a way to avoid hard-coding the config keys here
        # A note on dependencies: setSfxVolume has to come after sound effects are loaded. That is because Pygame sets sfx levels per Sound object; the sounds must be loaded to set their volume
        # Music volume, on the other hand, appears to be configurable at any time

        # Add music files to mapping
        # NOTE: We could have initialized the playing state music files in the main menu (along with the main menu music), because the mixer object is shared across all gamestates. But, we're initializing them here because they logically belong to this gamestate
        self.mixer.addMusicFileToMap('level'    , os.path.normpath(engineRef.exepath + '/../asset/audio/gameplay_music_01.ogg'))
        self.mixer.addMusicFileToMap('gameOver' , os.path.normpath(engineRef.exepath + '/../asset/audio/gameover.ogg'))
        self.mixer.setMusicVolume(config['mixer.musicVol'] / 10.0)  # TODO Design a way to avoid hard-coding the config keys here

        self.mixer.loadMusicFile('level')
        self.mixer.playMusic(repeatMode=sound_and_music.SoundNMusicMixer.REPEAT_TRACK)   # TODO revisit music playback. Maybe make a few songs to randomly shuffle?


    def Cleanup(self):
        # NOTE this class is a port from a C++ class. Because Python is garbage-collected, Cleanup() is probably not necessary here. But it's included for completeness
        #print "GAMESTATE Playing State cleaning up."
        pass

    @staticmethod
    def Instance():
#.........这里部分代码省略.........
开发者ID:masskonfuzion,项目名称:falldown_low_rez,代码行数:103,代码来源:game_state_playing.py


注:本文中的ball.Ball.setPosition方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。