How to use the environment

In the following steps, we will see how to use the environment.

  1. In order to use Flappy Bird in our Python scripts, firstly, we need to import PLE and Flappy Bird:
from ple.games.flappybird import FlappyBird
from ple import PLE
  1. Then, we instance a FlappyBird object and pass it to PLE with a few parameters:
game = FlappyBird()
p = PLE(game, fps=30, display_screen=False)

Here, with display_screen, you can choose whether to display the screen.

  1. The environment is initialized by calling the init() method:
p.init()

To interact and get the state of the environment, we primarily use four functions:

    • p.act(act), to execute the act action in the game. act(act) returns the reward obtained from the action performed.
    • p.game_over(), to check whether the game reached a final state.
    • p.reset_game(), to reset the game to the initial conditions.
    • p.getGameState(), to obtain the current state of the environment. We could also use p.getScreenRGB() if we want to obtain the RGB observations (that is, the full screen) of the environment. 
  1. Putting everything together, a simple script that plays Flappy Bird for five games can be designed as in the following code snippet. Note that in order to make it work, you still have to define the get_action(state) function that returns an action given a state:
from ple.games.flappybird import FlappyBird
from ple import PLE

game = FlappyBird()
p = PLE(game, fps=30, display_screen=False)
p.init()

reward = 0

for _ in range(5):
reward += p.act(get_action(p.getGameState()))

if p.game_over():
p.reset_game()

A couple of things to point out here are as follows:

  • getGameState() returns a dictionary with the position, velocity, and the distance of the player, as well as the position of the next pipe and the following one. Before giving the state to the policymaker that we represented here with the get_action function, the dictionary is converted to a NumPy array and normalized.
  • act(action) expects None as input if no action has to be performed, or 119 if the bird has to flap its wings in order to fly higher.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset