[MouseFox logo]
The MouseFox Project
Join The Community Discord Server
[Discord logo]
Edit on GitHub

pgnet.examples

A simple example implementation of a game and client.

These examples are best viewed from source.

 1"""A simple example implementation of a game and client.
 2
 3These examples are best viewed from [source](
 4https://github.com/ArielHorwitz/pgnet/blob/master/pgnet/examples.py).
 5"""
 6
 7import functools
 8from typing import Optional
 9from .client import Client
10from .util import Game, Packet, Response
11
12
13class ExampleGame(Game):
14    """A subclass of `pgnet.Game` as a simple example.
15
16    Maintains a log of strings, that users can get and add to.
17    """
18
19    persistent = True
20
21    def __init__(self, *args, save_string: Optional[str] = None, **kwargs):
22        """On initialization, import log from *save_string*."""
23        super().__init__(*args, **kwargs)
24        self.log = list(save_string.splitlines()) if save_string else ["Game started"]
25
26    def user_joined(self, username: str):
27        """Add log message on user join."""
28        self.log.append(f"Joined: {username}")
29
30    def user_left(self, username: str):
31        """Add log message on user leave."""
32        self.log.append(f"Left: {username}")
33
34    def handle_game_packet(self, packet: Packet) -> Response:
35        """Add log message and return full log."""
36        self.log.append(f"{packet.username} says: {packet.message!r}")
37        return Response("Message added.")
38
39    def handle_heartbeat(self, packet: Packet) -> Response:
40        """Return latest log messages."""
41        return Response("Latest log entries.", payload=dict(log=self.log[-10:]))
42
43    def get_save_string(self) -> str:
44        """Export the log."""
45        return "\n".join(self.log)
46
47
48class ExampleClient(Client):
49    """Client subclass to implement heartbeat for `ExampleGame`."""
50
51    log = []
52    on_status = functools.partial(print, ">> STATUS:")
53    """Print client status feedback."""
54    on_game = functools.partial(print, ">> GAME:")
55    """Print client game changes."""
56
57    def on_connection(self, connected: bool):
58        """Print connection changes and auto create a game when connected."""
59        print(">> CONNECTION:", connected)
60        if connected:
61            self.create_game("test")  # Will auto join if created
62            # self.join_game("test")  # Use this in case game already exists
63
64    def on_heartbeat(self, heartbeat: Response):
65        """Save and print the log if changed."""
66        game_log = heartbeat.payload.get("log", ["Empty log"])
67        if self.log != game_log:
68            self.log = game_log
69            print("New log:")
70            print("\n".join(f"-- {_}" for _ in game_log))
71
72
73__all__ = (
74    "ExampleGame",
75    "ExampleClient",
76)
class ExampleGame(pgnet.util.Game):
14class ExampleGame(Game):
15    """A subclass of `pgnet.Game` as a simple example.
16
17    Maintains a log of strings, that users can get and add to.
18    """
19
20    persistent = True
21
22    def __init__(self, *args, save_string: Optional[str] = None, **kwargs):
23        """On initialization, import log from *save_string*."""
24        super().__init__(*args, **kwargs)
25        self.log = list(save_string.splitlines()) if save_string else ["Game started"]
26
27    def user_joined(self, username: str):
28        """Add log message on user join."""
29        self.log.append(f"Joined: {username}")
30
31    def user_left(self, username: str):
32        """Add log message on user leave."""
33        self.log.append(f"Left: {username}")
34
35    def handle_game_packet(self, packet: Packet) -> Response:
36        """Add log message and return full log."""
37        self.log.append(f"{packet.username} says: {packet.message!r}")
38        return Response("Message added.")
39
40    def handle_heartbeat(self, packet: Packet) -> Response:
41        """Return latest log messages."""
42        return Response("Latest log entries.", payload=dict(log=self.log[-10:]))
43
44    def get_save_string(self) -> str:
45        """Export the log."""
46        return "\n".join(self.log)

A subclass of pgnet.Game as a simple example.

Maintains a log of strings, that users can get and add to.

ExampleGame(*args, save_string: Optional[str] = None, **kwargs)
22    def __init__(self, *args, save_string: Optional[str] = None, **kwargs):
23        """On initialization, import log from *save_string*."""
24        super().__init__(*args, **kwargs)
25        self.log = list(save_string.splitlines()) if save_string else ["Game started"]

On initialization, import log from save_string.

persistent = True

Set as persistent to allow the game to persist even without players.

This is required for saving and loading (see also: Game.get_save_string).

def user_joined(self, username: str):
27    def user_joined(self, username: str):
28        """Add log message on user join."""
29        self.log.append(f"Joined: {username}")

Add log message on user join.

def user_left(self, username: str):
31    def user_left(self, username: str):
32        """Add log message on user leave."""
33        self.log.append(f"Left: {username}")

Add log message on user leave.

def handle_game_packet(self, packet: pgnet.util.Packet) -> pgnet.util.Response:
35    def handle_game_packet(self, packet: Packet) -> Response:
36        """Add log message and return full log."""
37        self.log.append(f"{packet.username} says: {packet.message!r}")
38        return Response("Message added.")

Add log message and return full log.

def handle_heartbeat(self, packet: pgnet.util.Packet) -> pgnet.util.Response:
40    def handle_heartbeat(self, packet: Packet) -> Response:
41        """Return latest log messages."""
42        return Response("Latest log entries.", payload=dict(log=self.log[-10:]))

Return latest log messages.

def get_save_string(self) -> str:
44    def get_save_string(self) -> str:
45        """Export the log."""
46        return "\n".join(self.log)

Export the log.

class ExampleClient(pgnet.client.Client):
49class ExampleClient(Client):
50    """Client subclass to implement heartbeat for `ExampleGame`."""
51
52    log = []
53    on_status = functools.partial(print, ">> STATUS:")
54    """Print client status feedback."""
55    on_game = functools.partial(print, ">> GAME:")
56    """Print client game changes."""
57
58    def on_connection(self, connected: bool):
59        """Print connection changes and auto create a game when connected."""
60        print(">> CONNECTION:", connected)
61        if connected:
62            self.create_game("test")  # Will auto join if created
63            # self.join_game("test")  # Use this in case game already exists
64
65    def on_heartbeat(self, heartbeat: Response):
66        """Save and print the log if changed."""
67        game_log = heartbeat.payload.get("log", ["Empty log"])
68        if self.log != game_log:
69            self.log = game_log
70            print("New log:")
71            print("\n".join(f"-- {_}" for _ in game_log))

Client subclass to implement heartbeat for ExampleGame.

on_status = functools.partial(<built-in function print>, '>> STATUS:')

Print client status feedback.

on_game = functools.partial(<built-in function print>, '>> GAME:')

Print client game changes.

def on_connection(self, connected: bool):
58    def on_connection(self, connected: bool):
59        """Print connection changes and auto create a game when connected."""
60        print(">> CONNECTION:", connected)
61        if connected:
62            self.create_game("test")  # Will auto join if created
63            # self.join_game("test")  # Use this in case game already exists

Print connection changes and auto create a game when connected.

def on_heartbeat(self, heartbeat: pgnet.util.Response):
65    def on_heartbeat(self, heartbeat: Response):
66        """Save and print the log if changed."""
67        game_log = heartbeat.payload.get("log", ["Empty log"])
68        if self.log != game_log:
69            self.log = game_log
70            print("New log:")
71            print("\n".join(f"-- {_}" for _ in game_log))

Save and print the log if changed.