Python module providing simple game networking

Overview

nethelper

Python module providing simple game networking

This module was originally created to facilitate a class on creating multiplayer games in Pygame Zero. It designed to be simple for beginner programmers to use, and will not be as full featured or efficient as other networking libraries.

Features

  • Work over the internet or LAN
  • Designed specifically for game networking (...send and receive never blocks, messages are batched)
  • Very simple to use
  • No dependencies or installation. Just download and import one file.

How it Works

nethelper relies on a server to help relay messages between nodes (...players). This enables it to work across the internet without requiring each user to perform firewall / router configuration or share IP address. You can also run the server within your own LAN, but users outside of your LAN will likely not be able to connect to it.

Each player is a node, and nodes are organized into groups. This means that two students can play a pong game within a "pong" group, while another three students play a maze game within a "maze" group, all using the same server. There are no hardcoded limits to the number of groups, and each group can have up to 253 concurrent players.

Messages are encoded with JSON (...with a custom binary header), and transmitted via TCP to the message relay server. The message relay server will then relay the message to the intended recipient(s).

Each running game can send data to either a specific node within the same group, or to all nodes in the group. The former is useful for clients to send control commands to a game host, while the latter is useful for a game host to send the game state to all clients. See the example folder for examples of games using this pattern.

Starting the Server

For this module to work, you will require a message relay server. To start the server, simply run the module as a script.

python3 nethelper.py -g net_demo

This will start the server and configure it to recognize the "net_demo" group. Your game can use any string as a group name, as long as it is recognized by the server.

IMPORTANT : Your server must be accessible on its listening port (default to 65042). Read the section on "Server Access" for some tips on how to set this up.

You can also configure the server to recognize multiple groups.

python3 nethelper.py -g demo1 demo2 demo3

This will configure the server to recognize 3 groups; "demo1", "demo2", and "demo3". Games can only talk to others in the same group, so a game that's on "demo1" will not be able to talk to a game on "demo2".

You can also write your group names into a file and provide the filename on the command line.

python3 nethelper.py -f file_containing_groups.txt

Each group name must be on it's own line, and lines starting with # are ignored.

To see more options, run...

python3 nethelper.py -h

Game Setup

First, import the NetNode class.

from nethelper import NetNode

Next, create a NetNode object and connect to the message relay server (...make sure to start it first).

net = NetNode()
net.connect('localhost', 'foo', 'net_demo')

Now your game should be connected to the server as a node. Every node in the same group can talk to each other via the message relay server.

localhost is what I'm using here as the server address, but that will only work if the game is running on the same computer as the server. If the game is not running on the same computer as the server, you'll want to replace localhost with the IP address or domain name of the server.

foo is the name that this node is identifying itself as. You can use any string as a name, as long as every node in the same group has a unique name.

net_demo is the group that I am are connecting to. The server must be configured to recognize this group, and nodes can only communicate with other computers in the same group.

In your update() function, you should start with a...

net.process_recv()

This will receive all the incoming messages server, making them available to read.

To send a message to other nodes, use...

net.send_msg('bar', 'pp', players_pos)

This will send a message with the title pp to the node named bar. The content of the message will be the value of the variable players_pos.

To send to all nodes in the group, use ALL as the destination name.

net.send_msg('ALL', 'pp', players_pos)

To read incoming messages, use...

msg = net.get_msg('bar', 'controls')

This will get the content of the message titled controls from bar, and put it in the msg variable. If no messages are available, get_msg will return None.

Finally, you should end your update() function with a...

net.process_send()

This will push all the sent messages to the server. If you do not run process_send(), your messages will never get sent out.

One last useful function is net.get_peers(). This function will return a list containing the names of all nodes in your group.

More Documentations

See Wiki page on Github for detailed documentations.

The Wiki docs are generated from the docstrings in the nethelper.py source, so you can also read that.

Examples

As nethelper is designed for use with games, both of these examples uses Pygame Zero. However, nothing in nethelper requires Pygame Zero and it can also be used on its own without any other modules. A message relay server must be running and configured for group "net_demo" for the example to work.

Message sender:

import pgzrun
from nethelper import NetNode

net = NetNode()
net.connect('localhost', 'Tom', 'net_demo')

def update():
    if keyboard.up:
        net.send_msg('Jerry', 'controls', 'up')
    elif keyboard.down:
        net.send_msg('Jerry', 'controls', 'down')

    net.process_send()

pgzrun.go()

Message receiver:

import pgzrun
from nethelper import NetNode

net = NetNode()
net.connect('localhost', 'Jerry', 'net_demo')

msg = None
def update():
    global msg
    
    net.process_recv()
    msg = net.get_msg('Tom', 'controls')    

def draw():
    if msg:
        screen.clear()
        screen.draw.text(msg, (100,100), color="white")

pgzrun.go()

See the examples folder for more complete examples of games using nethelper.

Server Access

You can run the message relay server on either a computer within your own LAN, or on an internet server (...typically through a cloud service).

Computer within LAN

Running it on a computer within your own LAN can be faster and uses no internet bandwidth, but this may be blocked by your firewall or router. To open up access through the firewall, you need to allow incoming connections on TCP port 65042.

On Linux (Including Raspberry Pi)

On the command line, run...

sudo ufw allow 65042

On Windows

Visit this link for instructions https://www.tomshardware.com/news/how-to-open-firewall-ports-in-windows-10,36451.html

On Mac

Visit this link for instructions https://www.macworld.co.uk/how-to/how-open-specific-ports-in-os-x-1010-firewall-3616405/

Router Blocking Access

If the connection is being blocked by your router, you'll likely need to disable an option typically named "Wireless Isolation", "Client Isolation", or "Wireless client separation". There are many ways to configure a router to block client-to-client communications, so if that doesn't work, you'll need to consult your router manual or your network administrator for help. Alternatively, use an internet server instead.

Internet Server

Running the message relay server on the internet may be slower (ie. laggy), but will allow players on different networks to play together (eg. for an online class where every student is at their own home). It can also have less issues with network configurations. You will need to pay for a cloud hosting service, but these are not expensive (...typically 1 cent per hour).

Most cloud services including Amazon AWS, DigitalOcean, and Linode, will do just fine. The following instructions are based on DigitalOcean.

  1. Register for an account on DigitalOcean
  2. Create a new Droplet:
    • Choose Ubuntu as your distribution.
    • The cheapest plan should be sufficient for dozens of students.
    • Choose a datacenter region that is close to you.
    • For Authentication, a password will be sufficient (...no sensitive data will be stored on the server)
  3. Wait for your droplet to be ready (...this may take a few minutes), then login using an SSH client and your password.
  4. Download nethelper.py using the command:
wget https://raw.githubusercontent.com/QuirkyCort/nethelper/main/nethelper.py
  1. Open the port on the firewall using:
sudo ufw allow 65042
  1. Run nethelper.py (...see Starting the Server for details)
Owner
Cort
Cort
Jogo Flappy Bird com phyton e phygame

Flappy-Bird Tecnologias usadas Requisitos para inicializar o jogo: Python faça o download em: https://www.python.org/ Pygame faça o download em: https

João Guilherme 1 Dec 06, 2021
A Pygame application which generates mazes using randomized DFS (Depth-First-Search)

Maze-Generator-with-Randomized-DFS A Pygame application which generates mazes using randomized DFS (Depth-First-Search)-(Iterative implementation). Ra

Aysha sana 2 Feb 08, 2022
Minecraft Script to Tellraw Datapack Generator

Minecraft Script to Tellraw Datapack Geneator (STDG) can generate a chain of tellraw command in datapack from script.

1 Jan 28, 2022
Lutris helps you install and play video games from all eras and from most gaming systems.

Lutris Lutris helps you install and play video games from all eras and from most gaming systems. By leveraging and combining existing emulators, engin

Pop!_OS 2 Nov 15, 2021
Frets on Fire X: a fork of Frets on Fire with many added features and capabilities

Frets on Fire X - FoFiX This is Frets on Fire X, a highly customizable rhythm game supporting many modes of guitar, bass, drum, and vocal gameplay for

FoFiX 377 Jan 02, 2023
A Pygame Hangman Game coded in Python 3. Run Hangman.py in a terminal if you have Python 3

Hangman A Pygame Hangman Game coded in Python 3. Run python3 Hangman.py in a terminal if you have Python 3.

1 Dec 24, 2022
Wordle-player - An optimal player for Wordle. Based on a rough understanding of information theory

Wordle-player - An optimal player for Wordle. Based on a rough understanding of information theory

Neill Johnston 3 Feb 26, 2022
A Gomoku game GUI using pygame where the user can choose to play against another player or an AI using minimax with alpha-beta pruning

Gomoku A GUI based Gomoku game using pygame where the user can choose to play against another player or an AI using minimax with alpha-beta pruning. R

Mingyu Liu 1 Oct 30, 2021
Blackjack Game made using Python

Blackjack Game made using Python Blackjack is a popular card game played in most of the casino.This is an intuition to replicate the same card game us

SUHASJAGADISH 1 Nov 28, 2021
user friendly python script who is able to catch fish in the game New World

new-world-fishing-bot release 1.1.1 click img for demonstration Download guide Click at latest release: Download and extract bot.zip: When you run fil

297 Jan 08, 2023
Este repositorio es creado con el fin de brindar soporte a las personas que están en el proceso de aprendizaje MISIONTIC 2022 en la universidad de Antioquia

Este repositorio es creado con el fin de brindar soporte a las personas que están en el proceso de aprendizaje MISIONTIC 2022 en la universidad de Antioquia. Hecho por los estudiantes para los estudi

Andrés Mauricio Gómez 11 Jun 22, 2022
Magic: The Gathering Arena draft tool that utilizes 17Lands data

MTGA_Draft_17Lands Magic: The Gathering Arena draft tool that utilizes 17Lands data. Steps for Windows Step 1: Download and unzip the MTGA_Draft_17Lan

41 Dec 31, 2022
Snake game mixed with Conway's Game of Life

SnakeOfLife Snake game mixed with Conway's Game of Life The rules are the same than a normal snake game but you have to avoid cells created by Conway'

Aidan 5 May 26, 2022
A simple yet powerful Snake Game made with myPygameWorkflow

snakeGame A simple yet powerful Snake Game made with myPygameWorkflow. Requirments python3 Python.org myPygameWorkflow Github Ripo Usage $ cd main $ p

DuskyElf 1 Dec 26, 2021
Rock Paper Scissors Games with Python

This is a classic Rock, Paper, Scissors game with some ASCII aesthetics. After the welcome message, the game asks you to choose between the three choices. Then it let the computer choose its choice.

p.katekomol 1 Jan 24, 2022
Implementation of the Spider-Man Game

Projeto FPRO FPRO/LEIC, 2021/22 Francisco Campos (up202108735) 1LEIC08 Objetivo Criar um clone do clássico Spider-Man em Pygame... Repositório de códi

1 Dec 24, 2021
Flappy bird using Pygames

flappy-bird Esse é um jogo que eu fiz utilizando a biblioteca de jogos do Python

Leandro Henrique 2 Jan 05, 2022
An ongoing process to make a physics engine using python.

Simple_Physics_Engine An ongoing process to make a physics engine using python. I am using this goal as a way to learn python in and out. I am trying

Jon Sherrick 1 Jan 18, 2022
Jogo da velha com interface gráfica desenvolvida em Python utilizando pygame e IA(Inteligência Artificial)

Jogo-da-Velha Sobre o projeto Jogo da velha com interface gráfica desenvolvida em Python utilizando pygame e IA(Inteligência Artificial) Layout tela d

Matheus Maia Alvarez 6 Apr 09, 2022
Play a game of Phazed with a bot or with other players or watch bots play with each other

Phazed Game and Player play a game of Phazed with a bot or with other players or watch bots play with each other Live Demo hosted on repl.it (makes su

Xin Yu 0 Aug 28, 2021