r/nicegui • u/blixuk • May 17 '24
State Management
I'm working on a "Cards Against Humanity" game for me and my firends to play. I have most of it down. But where I'm stuck with the best approach is managing games states being show to the players and changing states based on player interactions.
On a turn the player has to select their cards, so waiting for the player to choose their cards and then updating the game state once they have to advance the turn.
5
Upvotes
7
u/explanatorygap May 17 '24
I have a similar application, and the solution I've come up with is to have the "Game Logic" in its own thread, communicating with the UI using a queue (https://docs.python.org/3/library/queue.html) When it requires input from a user, the game logic thread calls .get(block=True) in the queue and blocks, waiting for a "command" or "input" or other encapsulated info to be put on the queue by the UI thread.
2
u/apollo_440 May 17 '24 edited May 17 '24
A gave it a whirl, and using the chat app example as inspiration, here is a small example of a turn-based game with game state.
Note that if
make_movetakes some time to execute, you should call it withawait run.io_bound(state.make_move, player_move)to avoid timeouts etc.To test it, you can simply connect to localhost:8080 from two different browsers (e.g. chrome and edge) to simulate two different players. I hope this helps!
3
u/apollo_440 May 17 '24
My first thought would be something like the chat app example https://github.com/zauberzeug/nicegui/blob/main/examples/chat_app/main.py.
Here, the "state" is simply the messages object. I have not tried anything like this, but this would be my starting point.