# Tutorials

Some knowledge is required to help understand the binding from an SFML background. After reading this tutorial you should be able to start coding serious projects.

Note

I started to translate the official tutorials and while there are only a few available, they will soon be finished. This page should be replaced with this future page.

## System

### Vectors

To manipulate vectors you use sfml.system.Vector2 or sfml.system.Vector3 and unlike in C++ they have no specific type. It means you can set a float, an integer or whatever inside.

    1vector = sfml.system.Vector3()
    2vector.x = 5.56 # set a float
    3vector.y = -4 # set an integer
    4vector.z = Decimal(0.333333333)
    5x, y, z = vector # you can unpack the vector

To manipulate time there’s no major difference. Instead of getting the seconds, milliseconds or microseconds via a method named asSomething you do it via a property

     1t1 = sfml.milliseconds(500)
     2print(t1.seconds)
     3print(t1.microseconds)
     4
     5clock = sfml.system.Clock()
     6print(clock.elapsed_time)
     7t2 = clock.restart()
     8
     9time = t1 + t2
    10time *= t2
    11time -= t1
    12
    13sfml.sleep(time)

### Exception

Warning

sf.SFMLException has been removed and was replaced with standard exceptions.

SFML functions that may fail raise exception. If you use one of them and want to give a specific task in case of failure, you can handle them with a try… except statement.

    1try:
    2    # huge texture, will fail for sure
    3    # (except maybe if you read that in 2075 and if your processor works with light speed)
    4    texture = sf.Texture.create(987654321, 987654321)
    5except ValueError as error:
    6    print(error) # print the error
    7    exit(1)      # maybe quit ?

Note that load/open methods raise a traditional `IOError`:

    1try:
    2   music = sf.Music.from_file("song.ogg")
    3
    4except IOError:
    5   exit(1)

## Window

### Event

The way you handle events in pySFML2 is slightly different from how you do it in SFML2.

Here, rather than checking that the type property matches an event type, you check that event is an instance of a particular event class. While you could do this using python’s builtin type or isinstance functions, The Event class implements rich comparison operators to make things simpler:

    for event in window.events:
       if event == ...: # provide an event class name

Available event classes and their SFML2 equivalents are shown below:

pySFML | SFML (C++)
--- | ---
`CloseEvent` | sf::Event::Closed
`sfml.window.ResizeEvent` | sf::Event::Resized
`sfml.window.FocusEvent` | sf::Event::LostFocus sf::Event::GainedFocus
`sfml.window.TextEvent` `sfml.window.KeyEvent` | sf::Event::TextEntered sf::Event::KeyPressed sf::Event::KeyReleased
`sfml.window.MouseWheelEvent` `sfml.window.MouseButtonEvent` | sf::Event::MouseWheelMoved sf::Event::MouseButtonPressed sf::Event::MouseButtonReleased
`sfml.window.MouseMoveEvent` `sfml.window.MouseEvent` | sf::Event::MouseMoved sf::Event::MouseEntered sf::Event::MouseLeft
`sfml.window.JoystickButtonEvent` | sf::Event::JoystickButtonPressed sf::Event::JoystickButtonReleased
`sfml.window.JoystickMoveEvent` `sfml.window.JoystickConnectEvent` | sf::Event::JoystickMoved sf::Event::JoystickConnected sf::Event::JoystickDisconnected

Once you know the type of the event you can get the data inside.:

    if event == sf.MouseMoveEvent:
        x, y = event.position

For events like `KeyEvent`, `MouseButtonEvent`, etc. which can have two “states”, you’ll have to check it via their properties.:

     1if event == sf.KeyEvent:
     2    if event.pressed:
     3        ...
     4    elif event.released:
     5        ...
     6
     7if event == sf.KeyEvent and event.pressed:
     8    ...
     9
    10if event == sf.FocusEvent:
    11    if event.gained:
    12        ...
    13    if event.lost:
    14        ...

Read the `Window` class description for information about events.

## Graphics

### Rectangle

Although unpacking a rectangle will give you four integers/floats (respectively its left, its top, its width and its height) its constructor takes two `Vector2` or tuple; its position and its size.

    rectangle = mytext.local_bounds
    left, top, width, height = rectangle

    position, size = sf.Vector2(5, 10), sf.Vector2(150, 160)
    rectangle = sf.Rectangle(position, size)

This has been implemented as such because you may want to create a rectangle at any time and the variable you have in hand can either be four variables representing the top, the left, the width or two variables representing the position and the size. In both cases you can create a rectangle in one line!

    left, top, width, height = 5, 10, 150, 160
    rectangle = sf.Rectangle((left, top), (width, height))
    # or the ugly and verbose alternative
    rectangle = sf.Rectangle(sf.Vector2(left, top), sf.Vector2(width, height))

    position, size = (5, 10), (150, 160)
    rectangle = sf.Rectangle(position, size)

Making the rectangle require four numeric values in its constructor would have involved writing more lines if you had only a position and a size in hand

    x, y = position
    w, h = size
    rectangle = sf.Rectangle(x, y, w, h)

### Drawable

To create your own drawable just inherit your class from `Drawable`.

    1class MyDrawable(sf.Drawable):
    2    def __init__(self):
    3        sf.Drawable.__init__(self)
    4
    5    def draw(self, target, states):
    6        target.draw(body)
    7        target.draw(clothes)

To have a transformable drawable you have two implementation choices. As Like SFML in C++, you can either use a transformable internally and combine your transformable at drawing time or inherit your drawable from both `Drawable` and `Transformable`.

1. sf.Transformable in an internal attribute

   This consist of having a transformable in an attribute and combine with the states at drawing time.

        1class MyDrawable(sf.Drawable):
        2    def __init__(self):
        3        sf.Drawable.__init__(self)
        4        self._transformable = sf.Transformable()
        5
        6    def draw(self, target, states):
        7        states.transform.combine(self._transformable.transform)
        8
        9        target.draw(body)
       10        target.draw(clothes)
       11
       12    def _get_position(self):
       13        return self._transfomable.position
       14
       15    def _set_position(self, position):
       16        self._transformable.position = position
       17
       18    position = property(_get_position, _set_position)

   Only the position property has been implemented in this example but you can also implement rotation, scale, origin.

2. Inheriting from sf.Drawable and sf.Transformable

   There’s a current issue concerning this way to do. As Python doesn’t allow you to subclass from two built-in types at the same time, you can’t technically do it. That’s why pySFML2 provides `TransformableDrawable` which is both an `Drawable` and `Transformable`. That way your class inherits from properties such position, rotation etc and their methods move(), rotate() etc.

        1class MyDrawable(sf.TransformableDrawable):
        2    def __init__(self):
        3        sf.Drawable.__init__(self)
        4
        5    def draw(self, target, states):
        6        states.transform.combine(self.transformable.transform)
        7        target.draw(body)
        8        target.draw(clothes)
        9
       10mydrawable = MyDrawable()
       11mydrawable.position = (20, 30) # we have properties \o/

### HandledWindow

This extra class allows you to have a window handled by an external API such as PyQt4. This class is pretty straight forward and you should just follow the cookbook for integrating.

Warning

This class exists because of an issue with constructors. I still need to justify it or figure out how I can replace it.

## Audio

Using the audio module should be very simple since there’s no differences with the original API. Just note that the class `Chunk` allows you to manipulate an array of sf::Int16 which represents the audio samples. So far this class is pretty basic and offers access to each sample via the operator [] and you can get the data in a string for Python 2 or in bytes for Python 3 via `Chunk.data`.

## Socket

There’s no systematic STATUS to check. When something goes wrong an error is raised and you just have to handle it.

    1try:
    2    socket.send(b'hello world')
    3
    4except sf.SocketError:
    5    socket.close()
    6    exit(1)

## Miscellaneous & Tricks

Once you know pySFML well you may be interested in knowing some tricks.

### Unpacking

Many classes are unpackable

    1     x, y = sf.Vector2(5, 10)
    2     x, y, z = sf.Vector3(5, 10, 15)
    3
    4     size, bpp = sf.VideoMode(640, 480, 32)
    5     depth_bits, stencil_bits, antialiasing, minor_version, major_version = sf.ContextSettings()
    6
    7     r, g, b, a = sf.Color.CYAN
    8     left, top, width, height = sf.Rectangle((5, 10), (15, 20))

If you need to discard a value, use _

    # I'm not interested in the alpha value
    r, g, b, _ = get_color()

### sfml.Image.show()

For debugging purpose pySFML provides a show() function. This allows you to see how an image will look after modification. This is to be sure all operations made on the picture were effective.

    1image = sf.Image.from_image("image.png")
    2image.create_mask_from_color(sf.Color.BLUE)
    3image.show()
    4
    5texture = sf.Texture.from_image(image)
    6texture.update(window, (50, 60))
    7texture.to_image().show()

### Attach an icon to a Window

Easily attach an icon to your window

    icon = sf.Image.from_file("data/icon.bmp")
    window.icon = icon.pixels