Window and Game loop - Madour/pyNasNas GitHub Wiki
Window parameters
ns.App.__init__
takes a bunch of arguments :
- title (str) : title of your window
- w_width (int) : window width
- w_height (int) : window height
- v_width (int) : game camera width
- v_height (int) : game camera height
- fps (int) : desired fps (you'll never obtain exactly this value)
Let's go back to game.py
, and add some parameters to the window :
# src/game.py
import NasNas as ns
class Game(ns.App):
def __init__(self):
super().__init__(title="My SFML Project", w_width=1200, w_height=675, fps=100)
# you can change sfml RenderWindow properties (see SFML documentation)
# by accessing self.window
self.window.key_repeat_enabled = False
self.window.vertical_synchronization = True
The Game Loop
The game loop is started when you call the run()
method. What it does :
while window.is_open :
for event in window.events :
self.event_handler(event)
self.update()
self.render()
All of this is done under the hood, and you don't have to write it. You only have to write your own event_handler()
and update()
methods
Event handler
The event handler lets you interact with any window, keyboard, mouse or joystick event.
In your project's game.py
, let's add this method:
# src/game.py
import NasNas as ns
from sfml import sf
class Game(ns.App):
def __init__(self):
super().__init__(title="My SFML Project", w_width=1200, w_height=675, fps=100)
# you can change sfml RenderWindow properties (see SFML documentation)
# by accessing self.window
self.window.key_repeat_enabled = False
self.window.vertical_synchronization = True
def event_handler(self, event):
if event == sf.Event.KEY_PRESSED:
if event['code'] == ns.Keyboard.ESCAPE:
self.window.close()
elif event['code'] == ns.Keyboard.Q:
print('Q key pressed')
You can run main.py
and press Q , the message will be printed. Press Escape to close the window.
You can find a full list of events in SFML documentation.
Update
The update()
method is called every frame. In this method, you write most of your game logic (moving sprites, playing a sound, doing a transformation ...).
For now, we don't have any sprites, but we can still use it, add the following code to your Game
class :
def update(self):
# this will be printed every frame
print("Updating game !")
Render
The render()
method is called every frame, immediately after update()
. It automatically draws your game scenes on the window.
You are not supposed to override or call it !
<- [Get Started]] ](/Madour/pyNasNas/wiki/[[Resource-Loader-and-Manager) ->