Ejemplo n.º 1
0
    def _Deactivate(self):
        """This will either halt the animation or make the last frame invisible"""
        self._bActive = False

        #Reload the variables for another activation!
        self._anim_Time = sf.Time(0.0)
        self._lCurrent_Frame = ["DEFAULT", 0]
        self._Update_Frame()
Ejemplo n.º 2
0
    def _Update(self, timeElapsed):
        """This will update the frame of the animation based off of the timeElapsed and the current time in
        the animation.
        @param timeElapsed """

        if self._bActive:

            #print self._anim_Time + timeElapsed, sf.Time(self._dAnimated_Sprites[self._lCurrent_Frame[0]][1]*self._fDelay)

            #Check to see if the time counter will reach the end of the animation this update.
            if self._anim_Time + timeElapsed >= sf.Time(
                (self._dAnimated_Sprites[self._lCurrent_Frame[0]][1]) *
                    self._fDelay):

                #Since we reached the end of the animation, we
                #   must rrest the animation time and the frame number.
                self._anim_Time = self._anim_Time + timeElapsed - sf.Time(
                    (self._dAnimated_Sprites[self._lCurrent_Frame[0]][1] - 1) *
                    self._fDelay)

                self._lCurrent_Frame[1] = 0

                #Then we can update the sprite so that
                #   it shows the updated position in the animation.
                self._Update_Frame()

            #Check to see if the animation is due to switch it's frame.
            elif self._anim_Time + timeElapsed >= sf.Time(
                (self._lCurrent_Frame[1] + 1) * self._fDelay):

                #We update our timecounter variable!
                self._anim_Time += timeElapsed

                #Else, just update the frame
                self._lCurrent_Frame[1] += 1

                #Then we can update the sprite so that
                #   it shows the updated position in the animation.
                self._Update_Frame()

            else:

                #We update our timecounter variable!
                self._anim_Time += timeElapsed
Ejemplo n.º 3
0
    def _Activate(self, sStateKey):
        """This will activate a new animation to be played."""
        self._bActive = True

        print "The new animation state is", sStateKey

        #Reload the variables for another activation!
        self._anim_Time = sf.Time(0.0)
        self._lCurrent_Frame = [sStateKey, 0]
        self._Update_Frame()
Ejemplo n.º 4
0
    def __init__(
            self, dData
    ):  #sComponentID, iFrameWidth, iFrameHeight, dTextureStripData):
        Component.__init__(self,
                           "STATE_ANIMATIONS:%s" % (dData['componentID']),
                           True, 2)

        self._bActive = True

        #This will denote the time in-between each frame of the animation in the textures
        self._fDelay = float(dData['Delay'])

        #This will tell us when it is time to update the frame.
        self._anim_Time = sf.Time(0.0)

        #The current animation is set to its default (which there should be...)
        #   The first item is the animation, the second is the frame.
        self._lCurrent_Frame = ['DEFAULT', 0]

        self._iFrame_Width = int(dData['FrameWidth'])
        self._iFrame_Height = int(dData['FrameHeight'])

        self._dAnimated_Sprites = {}

        windPos = dData["WindPos"].split(",")

        for sTextureName in dData["Texture"].keys():

            #This holds the textures for the animations!
            #It being in a dictionary allows systems to switch to animations easier.
            #Each sAnimation will have a list of the sprite and some data for flexible lengthed animations to be allowed.
            #The list will include [sprite, iFramesWide]
            ##only the width is needed because this is a one-dimensional strip (I think this is all we need... Unless we're dealing with LARGE frame dimensions...)
            self._dAnimated_Sprites[sTextureName] = [sf.Sprite(dData["Texture"][sTextureName]),     \
                                                     int(dData["Texture"][sTextureName].width)/self._iFrame_Width]

            self._dAnimated_Sprites[sTextureName][0].x = float(windPos[0])
            self._dAnimated_Sprites[sTextureName][0].y = float(windPos[1])

            self._dAnimated_Sprites[sTextureName][0].origin = (
                self._iFrame_Width / 2, self._iFrame_Height / 2)

            #print "The sprite's origin is", (self._iFrame_Width/2, self._iFrame_Height/2)

        #Each animation strip gets
        for key in self._dAnimated_Sprites.keys():
            self._dAnimated_Sprites[key][0].set_texture_rect(
                sf.IntRect(0, 0, self._iFrame_Width, self._iFrame_Height))
Ejemplo n.º 5
0
 def random_time(self):
     return sf.Time(microseconds=random.randint(0, 1000000))
Ejemplo n.º 6
0
 def test_div(self):
     t = self.random_time()
     i = random.randint(1, 1000)
     self.assertEqual(t / i, sf.Time(microseconds=t.as_microseconds() / i))
     f = random.triangular(0.0, 100.0)
     self.assertEqual(t / f, sf.Time(seconds=t.as_seconds() / f))
Ejemplo n.º 7
0
 def test_mul(self):
     t = self.random_time()
     i = random.randint(1, 1000)
     self.assertEqual(t * i, sf.Time(microseconds=t.as_microseconds() * i))
     f = random.triangular(0.0, 100.0)
     self.assertEqual(t * f, sf.Time(seconds=t.as_seconds() * f))
Ejemplo n.º 8
0
 def test_sub(self):
     t1 = self.random_time()
     t2 = self.random_time()
     self.assertEqual(
         t1 - t2,
         sf.Time(microseconds=t1.as_microseconds() - t2.as_microseconds()))
Ejemplo n.º 9
0
    def test_eq(self):
        equal = [(sf.Time(microseconds=x), sf.Time(microseconds=x))
                 for x in [random.randint(0, 1000000) for n in range(10)]]

        for t1, t2 in equal:
            self.assertEqual(t1, t2)
Ejemplo n.º 10
0
def main():
    # Create the window of the application
    window = sf.RenderWindow(sf.VideoMode(800, 600, 32), 'PySFML Pong');

    # Load the sounds used in the game
    ball_sound_buffer = sf.SoundBuffer.load_from_file("resources/ball.wav")
    ball_sound = sf.Sound(ball_sound_buffer);

    # Load the textures used in the game
    background_texture = sf.Texture.load_from_file('resources/background.jpg')
    left_paddle_texture = sf.Texture.load_from_file('resources/paddle_left.png')
    right_paddle_texture = sf.Texture.load_from_file(
        'resources/paddle_right.png')
    ball_texture = sf.Texture.load_from_file('resources/ball.png')

    # Load the text font
    font = sf.Font.load_from_file('resources/sansation.ttf')

    # Initialize the end text
    end = sf.Text()
    end.font = font
    end.character_size = 60
    end.move(150, 200);
    end.color = sf.Color(50, 50, 250)

    # Create the sprites of the background, the paddles and the ball
    background = sf.Sprite(background_texture)
    left_paddle = sf.Sprite(left_paddle_texture)
    right_paddle = sf.Sprite(right_paddle_texture)
    ball = sf.Sprite(ball_texture)

    left_paddle.move(
        10, (window.view.size[1] - left_paddle.global_bounds.height) / 2)
    right_paddle.move(
        window.view.size[0] - right_paddle.global_bounds.width - 10,
        (window.view.size[1] - right_paddle.global_bounds.height) / 2)
    ball.move((window.view.size[0] - ball.global_bounds.width) / 2,
              (window.view.size[1] - ball.global_bounds.height) / 2)

    # Define the paddles properties
    ai_timer = sf.Clock()
    ai_time = sf.Time(milliseconds=100)
    left_paddle_speed  = 0.4
    right_paddle_speed = 0.4

    # Define the ball properties
    ball_speed = 0.4
    ball_angle = 0.0

    clock = sf.Clock()

    while True:
        # Make sure the ball initial angle is not too much vertical
        ball_angle = random.uniform(0.0, 2 * math.pi)

        if abs(math.cos(ball_angle)) < 0.7:
            break

    is_playing = True

    while window.open:
        # Handle events
        for event in window.iter_events():
            # Window closed or escape key pressed : exit
            if ((event.type == sf.Event.CLOSED) or
                (event.type == sf.Event.KEY_PRESSED and
                 event.code == sf.Keyboard.ESCAPE)):
                window.close()
                break

        frame_time = clock.restart().as_milliseconds()

        if is_playing:
            # Move the player's paddle
            if (sf.Keyboard.is_key_pressed(sf.Keyboard.UP) and
                left_paddle.y > 5.0):
                left_paddle.move(0.0, -left_paddle_speed * frame_time)

            if (sf.Keyboard.is_key_pressed(sf.Keyboard.DOWN) and
                (left_paddle.y <
                 window.view.size[1] - left_paddle.global_bounds.height - 5.0)):
                left_paddle.move(0.0, left_paddle_speed * frame_time)

            # Move the computer's paddle
            if (((right_paddle_speed < 0.0) and
                 (right_paddle.y > 5.0)) or
                ((right_paddle_speed > 0.0) and
                 (right_paddle.y < window.view.size[1] -
                  right_paddle.global_bounds.height - 5.0))):
                right_paddle.move(0.0, right_paddle_speed * frame_time)

            # Update the computer's paddle direction according
            # to the ball position
            if ai_timer.elapsed_time > ai_time:
                ai_timer.restart()

                if (right_paddle_speed < 0 and
                    (ball.y + ball.global_bounds.height >
                     right_paddle.y + right_paddle.global_bounds.height)):
                    right_paddle_speed = -right_paddle_speed

                if right_paddle_speed > 0 and ball.y < right_paddle.y:
                    right_paddle_speed = -right_paddle_speed;

            # Move the ball
            factor = ball_speed * frame_time
            ball.move(math.cos(ball_angle) * factor,
                      math.sin(ball_angle) * factor)

            # Check collisions between the ball and the screen
            if ball.x < 0.0:
                is_playing = False
                end.string = "You lost !\n(press escape to exit)"

            if ball.x + ball.global_bounds.width > window.view.size[0]:
                is_playing = False
                end.string = "You won !\n(press escape to exit)"

            if ball.y < 0.0:
                ball_sound.play();
                ball_angle = -ball_angle
                ball.y = 0.1

            if ball.y + ball.global_bounds.height > window.view.size[1]:
                ball_sound.play()
                ball_angle = -ball_angle
                ball.y = window.view.size[1] - ball.global_bounds.height - 0.1

            # Check the collisions between the ball and the paddles
            # Left Paddle
            if (ball.x < left_paddle.x + left_paddle.global_bounds.width and
                ball.x > left_paddle.x +
                (left_paddle.global_bounds.width / 2.0) and
                ball.y + ball.global_bounds.height >= left_paddle.y and
                ball.y <= left_paddle.y + left_paddle.global_bounds.height):
                ball_sound.play()
                ball_angle = math.pi - ball_angle
                ball.x = left_paddle.x + left_paddle.global_bounds.width + 0.1

            # Right Paddle
            if (ball.x + ball.global_bounds.width > right_paddle.x and
                ball.x + ball.global_bounds.width < right_paddle.x +
                (right_paddle.global_bounds.width / 2.0) and
                ball.y + ball.global_bounds.height >= right_paddle.y and
                ball.y <= right_paddle.y + right_paddle.global_bounds.height):
                # ball_sound.play();
                ball_angle = math.pi - ball_angle
                ball.x = right_paddle.x - ball.global_bounds.width - 0.1

        # Clear the window
        window.clear()

        # Draw the background, paddles and ball sprites
        window.draw(background)
        window.draw(left_paddle)
        window.draw(right_paddle)
        window.draw(ball)

        # If the game is over, display the end message
        if not is_playing:
            window.draw(end)

        # Display things on screen
        window.display()
Ejemplo n.º 11
0
    def key_input(self, iKeyCode, bPressed=False, timeElapsed=None):
        """This is for taking in data on the key that has been pressed (based off of sfml's enumeration of keys.) Its power is limited, but this will allow
        the game to have combos and simultaneous key presses. The only problem I see is that it won't allow a key to be pressed throughout the duration of the combo.
        And the subcombos that are a subset of a larger combo will be activated along with the larger combo (this could be an awesome feature, but also limiting.)
        @param timeElapsed This should be an SFML Timer object and it represents the time since the last key was pressed."""

        #This will prevent unknown keys from doing things to the game.
        if iKeyCode != -1:

            print("This %d keycode has been pressed" % (int(iKeyCode)),
                  bPressed)

            if bPressed == True:
                #Check to see if this input was pressed within a duration of the last input.
                if sf.Time(0.5) > timeElapsed:
                    #Check to see if the previous inputs haven't all been released yet.
                    if self._should_goto_next_pos == False:
                        #We'll just keep adding to the list of simultaneous key presses until all of these keys are released!
                        #We only ever add to the end of this list, so there's no point in using a variable.
                        self._past_inputs[-1].append(iKeyCode)

                    else:
                        #The last button has been released, so we append to the end!
                        self._past_inputs.append([iKeyCode])

                        #Gotta reset this, because it will be set to True again when iKeyCode is released.
                        self._should_goto_next_pos = False

                #elif self._inputsToBeReleased != 0:
                #Without this, the combo system's inputs that haven't been released yet won't get their OnReleased function executed.
                #return

                else:
                    #We'll have to reset our past inputs because the key being pressed isn't related to them.
                    del self._past_inputs[:]
                    #This also means that these variables should be reset as well.
                    self._inputsToBeReleased = 0
                    self._should_goto_next_pos = False

                    #This could be the start of a new combo!
                    self._past_inputs.append([iKeyCode])

                #This is suppose to end up looking like "/101.41.78./56./45.78."
                #Each "/" means that the following keys were all pressed at the same time (all keys that get pressed, until all of those keys are released, are grouped together.)
                #The "." separate the different keyIDs that exist in each group.
                sInputKey = ""

                for keyList in self._past_inputs:
                    sInputKey += "/"
                    for iKeyID in keyList:
                        sInputKey += str(iKeyID) + "."

                print("sInputKey", sInputKey)

                #This checks our queue of inputs to see if it matches any of the ones in our dictionary.
                tKeyData = self._key_listeners.get(sInputKey, None)
                if tKeyData != None:
                    if tKeyData[0] == "action":
                        #tKeyData[1] is in this format [[0,1,2],[0,1,2],...]
                        #Each item of the overall list represents a single entity
                        self._active_actions.append(tKeyData[1])

                    elif tKeyData[0] == "state":
                        self._active_states.append((sInputKeys, tKeyData[1]))

            else:
                #A key was released!

                #Check to see if its time to change the position
                if (len(self._past_inputs) != 0 and len(self._past_inputs[-1]) == 1)    \
                   or self._inputsToBeReleased == 1:
                    #Signal to append to a new position when a new key is pressed, because the previous inputs have been released!
                    self._should_goto_next_pos = True

                    sInputKey = ""

                    for keyList in self._past_inputs:
                        sInputKey += "/"
                        for iKeyID in keyList:
                            sInputKey += str(iKeyID) + "."

                    #We only want to signal the release function to be called when all of the keys are released from the last element.
                    tKeyData = self._key_listeners.get(sInputKey, None)
                    if tKeyData != None:
                        if tKeyData[2][0] != None:
                            #All released inputs will be treated the same (because any input is only released once.)
                            #But if the input in question doesn't have data pertaining to what to do when the key is released,
                            #then there's no reason to add it to this list.
                            self._active_actions.append(tKeyData[2])

                        #The first element of tKeyData is the InputType (action "a", state "s".)
                        if tKeyData[0] == "state":
                            #Take that keyCode out of the list of Active State inputs.
                            for i in range(len(self._active_states)):
                                if self._active_states[i][0] == sInputKey:
                                    del self._active_states[i]

                else:
                    #Check to see if this is the first to be released (with more to be expected.)
                    if self._inputsToBeReleased == 0:
                        #update that variable with the number of inputs that are needed to be released before we continure to the next position (minus one, because one input was released.)
                        self._inputsToBeReleased = len(
                            self._past_inputs[-1]) - 1

                    else:
                        self._inputsToBeReleased -= 1
Ejemplo n.º 12
0
def main():
    #Initialize the window and windowView (the windowView won't be setup until the state changes!)
    window, windowView = Init()

    #These variables will track our position within the game.
    lCurrentState = ["NULL", "NULL"]
    lNextState = ["Menu", "MainMenu"]

    #This will be updated when we change to a state.
    EntityManager = Entity_Manager()

    #The AssetManager will be used by ChangeState in order to retrieve sounds/textures for a particular type of entity.
    AssetManager = assets.Asset_Manager()

    ChangeState(lCurrentState, lNextState, windowView, EntityManager,
                AssetManager)

    timer = sf.Clock()

    SKIP_TICKS = 1 / config.TICKS_PER_SEC
    MAX_FRAMESKIP = 5

    iLoops = None
    fNextGameTick = timer.elapsed_time

    #This will be False if the player clicks outside of the program's window and "pause" the program
    windowIsActive = True

    bQuit = False
    while not bQuit:

        #This will loop through all of the events that have been triggered by player input
        for event in window.iter_events():

            if event.type == sf.Event.MOUSE_MOVED:
                Input_Manager._Mouse_Has_Moved(
                    window.convert_coords(event.x, event.y))

            elif event.type == sf.Event.TEXT_ENTERED:
                Input_Manager._Key_Input(event.unicode, True,
                                         timer.elapsed_time)

            elif event.type == sf.Event.KEY_PRESSED:
                Input_Manager._Key_Input(event.code, True, timer.elapsed_time)

            elif event.type == sf.Event.KEY_RELEASED:
                Input_Manager._Key_Input(event.code, False, timer.elapsed_time)

            elif event.type == sf.Event.MOUSE_BUTTON_PRESSED:
                Input_Manager._Mouse_Input(event.button, True)

            elif event.type == sf.Event.MOUSE_BUTTON_RELEASED:
                Input_Manager._Mouse_Input(event.button, False)

            elif event.type == sf.Event.LOST_FOCUS:
                windowIsActive = False

            elif event.type == sf.Event.GAINED_FOCUS:
                windowIsActive = True

            elif event.type == sf.Event.CLOSED:
                for stateIndx in xrange(len(lNextState)):
                    lNextState[stateIndx] = "QUIT"
                bQuit = True

        iLoops = 0  #A counter for the amount of game update loops that are made in sucession whilst skipping rendering updates.

        #This loop will start if it is time to commence the next update and will keep going if we are behind schedule and need to catch up.
        while timer.elapsed_time > fNextGameTick and iLoops < MAX_FRAMESKIP:

            #This makes the program so that it basically pauses all of its game updates when a user clicks outside of the window. And it waits until the user clicks on the window.
            if windowIsActive:

                #We don't want to change lNextState if the game has been set to QUIT
                if not bQuit:

                    #lNextState will contain "NULL"s when no state change is signaled
                    #lNextState will have all of its elements change when switching to a new state.
                    lNextState = EntityManager._Input_Update()

                    #Check to see if we have signaled to quit the game thus far
                    if lNextState[0] == "QUIT":
                        bQuit = True

                    #If one of the lNextState elements is changed, they all are (just how it goes.)
                    if lNextState[0] != "NULL" and lNextState[0] != "QUIT":
                        ChangeState(lCurrentState, lNextState, windowView,
                                    EntityManager, AssetManager)

                #Finally after we've handled input and have correctly adjusted to the nextState (in most cases it won't happen,)
                #we can then update our game's model with stuff that will happen in the respective state with each game update.
                if not bQuit:
                    EntityManager._Logic_Update(
                        timer.elapsed_time - fNextGameTick
                    )  #This updates our model depending on what is going on in the current state

            #If we have received a quit signal, we should stop our loop and quit the game!
            if bQuit:
                break

            iLoops += 1
            fNextGameTick += sf.Time(seconds=SKIP_TICKS)

        EntityManager._Render_Update(window, windowView)
        window.display()

    #This closes our RenderWindow!
    window.close()
Ejemplo n.º 13
0
def main():
    #Initialize the window and windowView (the windowView won't be setup until the state changes!)
    Init()

    #These variables will track our position within the game.
    lCurrentState = ["NULL", "NULL"]
    lNextState = ["Menu", "Intro"]

    #This will be updated when we change to a state.
    EntityManager = Entity_Manager()

    ChangeState(lCurrentState, lNextState, config.window, config.windowView,
                EntityManager)

    t = sf.Time(0.0)

    accumulator = sf.Time(0.0)

    MAX_FRAMESKIP = 5

    timer = sf.Clock()

    lastKeyPress = sf.Clock()

    #This will be False if the player clicks outside of the program's window and "pause" the program
    windowIsActive = True

    bQuit = False
    while not bQuit:

        frameTime = timer.elapsed_time

        timer.restart()

        #This caps the time inbetween frames to
        #   prevent a spiral of death (which happens when the computer
        #   can't keep up.)
        if frameTime > sf.Time(0.25):

            print "preventing spiral of death"
            frameTime = sf.Time(0.25)

        accumulator += frameTime

        #This will loop through all of the events that have been triggered by player input
        for event in config.window.iter_events():

            if event.type == sf.Event.MOUSE_MOVED:
                Input_Manager._Mouse_Has_Moved(
                    config.window.convert_coords(event.x, event.y))

            #elif event.type == sf.Event.TEXT_ENTERED:
            #Input_Manager._Key_Input(event.unicode, True, lastKeyPress.elapsed_time)

            #This restarts the Timer for the lastKeyPress since a new key just
            #   got pressed.
            #lastKeyPress.restart()

            elif event.type == sf.Event.KEY_PRESSED:
                Input_Manager._Key_Input(event.code, True,
                                         lastKeyPress.elapsed_time)

                #This restarts the Timer for the lastKeyPress since a new key just
                #   got pressed.
                lastKeyPress.restart()

            elif event.type == sf.Event.KEY_RELEASED:
                #The time elapsed isn't necessary for the released key.
                Input_Manager._Key_Input(event.code)

            elif event.type == sf.Event.MOUSE_BUTTON_PRESSED:
                Input_Manager._Mouse_Input(event.button, True)

            elif event.type == sf.Event.MOUSE_BUTTON_RELEASED:
                Input_Manager._Mouse_Input(event.button, False)

            elif event.type == sf.Event.CLOSED:
                for stateIndx in xrange(len(lNextState)):
                    lNextState[stateIndx] = "QUIT"
                bQuit = True

            elif event.type == sf.Event.LOST_FOCUS:
                windowIsActive = False

            elif event.type == sf.Event.GAINED_FOCUS:
                windowIsActive = True

        iLoops = 0  #A counter for the amount of game update loops that are made in sucession whilst skipping rendering updates.

        #This loop will start if it is time to commence the next update and will keep going if we are behind schedule and need to catch up.
        while accumulator >= sf.Time(
                1. / config.FRAME_RATE) and iLoops < MAX_FRAMESKIP:

            #This makes the program so that it basically pauses all of its game updates when a user clicks outside of the window. And it waits until the user clicks on the window.
            if windowIsActive:
                #We don't want to change lNextState if the game has been set to QUIT
                if not bQuit:
                    #lNextState will contain "NULL"s when no state change is signaled
                    #lNextState will have all of its elements change when switching to a new state.
                    lNextState = EntityManager._Input_Update()

                    #Check to see if we have signaled to quit the game thus far
                    if lNextState[0] == "QUIT":
                        bQuit = True

                    #If one of the lNextState elements is changed, they all are (just how it goes.)
                    if lNextState[0] != "NULL" and lNextState[0] != "QUIT":
                        ChangeState(lCurrentState, lNextState, config.window,
                                    config.windowView, EntityManager)

                    #Finally after we've handled input and have correctly adjusted to the nextState (in most cases it won't happen,)
                    #we can then update our game's model with stuff that will happen in the respective state with each game update.

                    #Notice that DT is a constant variable that represents how much time is going by during
                    #   this update.
                    lNextState = EntityManager._Logic_Update(
                        sf.Time(1. / config.FRAME_RATE))

                    #Check to see if we have signaled to quit the game thus far
                    if lNextState[0] == "QUIT":
                        bQuit = True

                    #If one of the lNextState elements is changed, they all are (just how it goes.)
                    if lNextState[0] != "NULL" and lNextState[0] != "QUIT":
                        ChangeState(lCurrentState, lNextState, config.window,
                                    config.windowView, EntityManager)

            #If we have received a quit signal, we should stop our loop and quit the game!
            if bQuit:
                break

            #The accumulator contains the time that hasn't yet been used for the updates.
            #Each update will assume that dt time is going by, so the accumulator just
            #   needs to subtract by the time that is being used up.
            accumulator -= sf.Time(1. / config.FRAME_RATE)

            #This counts the Update loop
            iLoops += 1

        #This makes the program so that it basically pauses all of its game updates when a user clicks outside of the window. And it waits until the user clicks on the window.
        if windowIsActive:
            EntityManager._Render_Update(config.window, config.windowView)

        config.window.display()

    #This closes our RenderWindow!
    config.window.close()