Skip to main content

No project description provided

Project description

Netbound

A safe and fair way to play games with friends over the internet

âš¡ Quick start

The following is a basic example of how to start a websockets game server using Netbound. This example uses the asyncio library to run the server in a non-blocking manner.

# File: __main__.py

import asyncio
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
from netbound.app import ServerApp

async def main() -> None:
    db_engine: AsyncEngine = create_async_engine("sqlite+aiosqlite:///database.sqlite3")
    server_app: ServerApp = ServerApp("localhost", 443, db_engine)

    print("Server starting...")

    async with asyncio.TaskGroup() as tg:
        tg.create_task(server_app.start())
        tg.create_task(server_app.run(ticks_per_second=10))

    print("Server stopped")


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        logging.info("Server stopped by user")

Defining packets

Packets are the primary way of communicating between the server and the client, or between server "protocols". Create your own module(s) with subclass packets of netbound.packet.BasePacket and inject them into the server app.

# File: example_packets.py

from netbound.packet import BasePacket

class ExamplePacket(BasePacket):
    my_field: str
    my_other_field: int

class AnotherPacket(BasePacket):
    some_field: list[int]
# File: __main__.py

import example_packets
from netbound.app import ServerApp

server_app: ServerApp = ServerApp("localhost", 443)
server_app.register_packets(example_packets)

Defining models

Models are the primary way of storing data in the database. Create your own module(s) with subclassed models of sqlalchemy.orm.DeclarativeBase and inject them into the server app.

# File: example_models.py

from sqlalchemy.orm import DeclarativeBase

class Base(DeclarativeBase):
    pass

class ExampleModel(Base):
    my_field: str
    my_other_field: int

Now we need to tell alembic where your models are located:

alembic init alembic

And edit the alembic/env.py file to point to your models' Base class so that when when you run the following shell commands,

alembic revision --autogenerate -m "Initial migration"
alembic upgrade head

you will see your database file appear with all of your models inside.

For more information, see https://alembic.sqlalchemy.org/en/latest/tutorial.html.

Defining states

States are the primary way of managing the game state. Create an initial state for the server app and tell it to use that state.

# File: entry_state.py

from netbound.state import BaseState
from example_packets import ExamplePacket, AnotherPacket
from example_models import ExampleModel

class EntryState:
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self._name: str = "entry_state"

    async def _on_transition(self, *args, **kwargs) -> None:
        await self._queue_local_client_send(ExamplePacket(from_pid=self._pid, my_field="hello", my_other_field=42))

        async with self._get_db_session() as session:
            eg: ExampleModel = ExampleModel(my_field="hello", my_other_field=42)
            session.add(eg)
            session.commit()

    async def handle_anotherpacket(self, p: AnotherPacket) -> None:
        print("Received another packet with fields:")
        for n in p.some_field:
            print(n)
# File: __main__.py

import asyncio
from entry_state import EntryState
from netbound.app import ServerApp

async def main() -> None:
    server_app: ServerApp = ServerApp("localhost", 443)

    print("Server starting...")

    async with asyncio.TaskGroup() as tg:
        tg.create_task(server_app.start(initial_state=EntryState))
        tg.create_task(server_app.run(ticks_per_second=10))

    print("Server stopped")


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        logging.info("Server stopped by user")

NPCs

NPCs can be treated as just a special type of player protocol which doesn't have a client. This is exactly how Netbound treats them.

You can add NPCs to your game by first creating a state for them to live in. It can be easy to subclass some sort of PlayState you might have for your players, but remember not to use the self._queue_local_client_send method. Instead, it is safest to simply override that function to log a warning in the __init__ method of your NPC state.

NPC states are also where netbound.schedule really shines, as it is a non-blocking way to schedule events in the future. This is useful for making NPCs move around, or do other things at certain times.

# File: npc_state.py
from netbound import schedule
from server.packet import ChatPacket
from netbound.constants import EVERYONE
from server.state import LoggedState

class BobPlayState(LoggedState):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self._queue_local_client_send = lambda p: self._logger.warning(f"NPC tried to send packet to client: {p}")

    async def handle_chat(self, p: ChatPacket) -> None:
        reply: str = "Hi, I'm Bob!"
        schedule(
            1, 
            lambda: self._queue_local_protos_send(ChatPacket(from_pid=self._pid, to_pid=EVERYONE, exclude_sender=True, message=reply))
        )

Then, in your main file, you can add the NPC to the server app like so:

# File: __main__.py
from server.npc_state import BobPlayState

# ... (regular setup code)
server_app.add_npc(BobPlayState)
# ...

This will add an NPC to the server app that will reply to any chat messages with "Hi, I'm Bob!" after 1 second.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

netbound-0.1.11.tar.gz (12.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

netbound-0.1.11-py3-none-any.whl (13.1 kB view details)

Uploaded Python 3

File details

Details for the file netbound-0.1.11.tar.gz.

File metadata

  • Download URL: netbound-0.1.11.tar.gz
  • Upload date:
  • Size: 12.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.0.0 CPython/3.11.4

File hashes

Hashes for netbound-0.1.11.tar.gz
Algorithm Hash digest
SHA256 087e85de3fcc18551791e7fdb08e20e23c56aa0d7c1e20e5346b111e887d2c96
MD5 949575500b5dca677a108f21361f7c5e
BLAKE2b-256 7119f01aa582db91d27d88544d97bc101e13cf8494db515c977e33644db2758f

See more details on using hashes here.

File details

Details for the file netbound-0.1.11-py3-none-any.whl.

File metadata

  • Download URL: netbound-0.1.11-py3-none-any.whl
  • Upload date:
  • Size: 13.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.0.0 CPython/3.11.4

File hashes

Hashes for netbound-0.1.11-py3-none-any.whl
Algorithm Hash digest
SHA256 1e762dc69614be1bd0000153cf2e8207e1606b49ffad6766516301ed40f0de49
MD5 246638493df3de4029da7618dc257f7d
BLAKE2b-256 18a859c3f9dfb471d1643eeef78d644bd1e9291e7ff48d21f92b7f4144cb8c42

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page