#🔒 Is there a place for a new python game engine?

171 messages · Page 1 of 1 (latest)

orchid pebble
#

Hello everyone. I’d like to hear your opinion on the viability of an idea I’ve been thinking about. Here’s a bit of background.

I’ve been working with Python for 3 years now. I’m 16 (turning 17 soon), so I have the freedom to explore new things. Over the past few years, I’ve tried many aspects of Python development, and at one point I became curious about game development using Python.

I quickly learned about the available engines that work with Python. Using mods to integrate with Unity or Unreal felt like an awkward solution, and I couldn’t find any game engine built on Python that includes a graphical editor. That led me to a fleeting but intriguing idea — creating such an engine myself.

I’m not a genius, so I won’t be inventing the wheel from scratch, but I do have some thoughts.

Python’s ecosystem includes pygame. Some might argue that pyglet or arcade are better, and they’d have a point — but pygame has an experimental module that supports modern rendering APIs like OpenGL and Vulkan. Thanks to this, performance is quite impressive compared to other libraries, while still being very simple to use. Plus, it offers cross-platform support due to its backend flexibility. For instance, I was able to render 80,000 sprites at 60fps. Shader support is also possible with some effort.

If I:

structure it similarly to Unity

build a reasonably good graphical editor

use Cython for performance bottlenecks

and focus solely on 2D games

...then, assuming the engine allows building any genre of 2D game (e.g. something like Among Us or Terraria), could such a game engine be viable? Could it gain popularity among indie developers?

lament needleBOT
#

@orchid pebble

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

vale tendon
orchid pebble
vale tendon
#

You might not grasp the scale of these projects then

#

even indie projects

#

it could be a fun hobby ecosystem like Pico8

onyx galleon
# orchid pebble Hello everyone. I’d like to hear your opinion on the viability of an idea I’ve b...

I'm not really an expert, but some issues I can think of:

  • distributing: you've probably seen 1 bajillion posts trying to "share my code with friend who doesn't have python installed" and the solution usually has many compromises; compiled languages on the other hand doesn't have this big issue
  • performance: maybe rendering is very efficient due to interfacing with opengl or vulkan, but you can't deny that, say, looping in C++ is just faster than in python; this stacks up over multiple parts of your code
orchid pebble
vale tendon
#

as Purplys is saying, there's an insane amount of backend logic running at the same time

#

If someone has the option of engine, why would they pick the weaker one?

orchid pebble
#

Most 2ds are just animations and colisias

vale tendon
#

What advantage does python have here, unless you already know the language?

orchid pebble
#

It is much simpler, if you use cython, numpy, numba, then it becomes much more productive, unlike regular python.

vale tendon
#

It's still nowhere near the speeds you'll be getting from compiled languages

orchid pebble
#

This is just my opinion, I understand that there are more powerful engines such as Unity and Unreal. But for example, the same Godot was created to be simple, although less productive.

vale tendon
#

and in games, performance is king

#

godot is less productive only because it's in its infancy

#

it's making huge strides

onyx galleon
# orchid pebble It is much simpler, if you use cython, numpy, numba, then it becomes much more p...

honestly I think the opposite, if I have to use numpy / numba to write games it'd be a pain in the ass
most of these are designed for numerical computing; numpy for example relies heavily on vectorized operations, which is against what I think you'll be doing when making games (like looping)
numba isn't much better, to JIT a function it imposes restrictions that make python really hard to write anyway

on the other hand, if performance really isn't an issue, then yeah python shines - ren'py for example, still the go-to for making visual novels

orchid pebble
# vale tendon it's making huge strides

I understand that speed is very important. for example, Unity will provide a margin of performance, unlike python. I'm not a professional, but as if tolkien for 2d python would be enough. We are not talking about 3d.

My question was about clarification. If there is enough power, will there be potential in game dev? I myself understand that if python does not cope, then in any case the idea is a failure.

vale tendon
#

Look at it this way. Python has been around for nearly 40 years. If someone could make a commercial game engine with it, they would have already.

orchid pebble
#

I also use Google Translate, keep that in mind.

vale tendon
#

< (Has worked professionally in game dev for 6+ years)

orchid pebble
#

Similarly, 40 years ago, there were powerful computers, and games were written in low-level languages. The field of game creation began to develop relatively recently

#

I think @onyx galleon is right, for example, for python novels it will be enough completely

#

I don't talk about high-class projects.

#

for example, Among Us is a worldwide hit, but in fact a couple of animations, a box colaider and a network code

#

@vale tendonWhat do you think about my recent messages

orchid pebble
scarlet spade
#

game creation has been around, even for indie, for a lot longer than just 'recently' And yes there are indeed some games that are very simple that are very popular but they were also easier to make in Unity than they would have been in python. And also Among Us is an extremely niche example, an example which also did not maintain its hype at all. Much more of a flash in the pan novelty. And it have been out for years before it went viral

orchid pebble
scarlet spade
#

Well like to Fashoomp's point, with how old Python is someone would have made one already if it was going to be that much better or competitive. But on the other side of things if it is something you really want to do, creating your own game engine could be an amazing experience and learning tool as well as quite the selling point at a resume level for yourself given your age if it is a career path you would want to pursue.

orchid pebble
floral tangle
#

I would say for making a game, basically everything that have to be repeated many time in a second

scarlet spade
#

or anything that relies on quick feedback like character movement for example. nothing is more enraging in an action game (Even a 2d one) is having delay or lag in your actions vs the game itself.

#

Which to clarify is the same thing as something that relies on super fast loops. Just giving a specific example

orchid pebble
floral tangle
orchid pebble
floral tangle
#

For example collision handling
You have to calculate the collision of an object to many more object for each object, depends on how you optimise it

orchid pebble
floral tangle
#

Already did

orchid pebble
floral tangle
#

The issue is not just the computation
Is the fact that you have to call a function etc
Which introduce many overhead

orchid pebble
tranquil lake
#

Hi huymae, I think it is a good idea. However, it will require a lot of time and will not allow very complex games to be made, bc of the slowness of python.

#

There are tons of think you can built around pygame to make it easier to develop game, like database management, languages, complex inputs, distribution etc.

#

A scene manager, entity managers, some settings automatically predifined

#

Every of this is already a lot of work and do not cost much in terms of computation

#

however, the rendering part, collision detection etc. will be harder to implement efficiently and will likely need to be different between two games

floral tangle
#

I just done some simple benchmark and it takes 500ns for 1 collision check for pure python implementation
Which would be approximately checking 200 object on each other(i.e. Every object being checked for every existing object) for 120 fps
Or 16.7k check per frame

tranquil lake
#

remove the print

#

to benchmark correctly

floral tangle
#

The print is excluded from the time check

tranquil lake
#

printing takes time

floral tangle
#
for idx in range(double_size):
    x=1
    start = time.perf_counter_ns()
    fast_load_exec(compiled)
    end = time.perf_counter_ns()
    diff.append((end-start)/size)
    print(f"Completed {idx}")
tranquil lake
#

can you share the code ?

#

great

floral tangle
#
import random

size = 10_000
double_size = 10000

# preset_dict = {"".join(random.choices("0123456789abcdef", k=32)): "".join(random.choices("0123456789abcdef", k=32)) for _ in range(200)}
# preset_list = list(range(40000))
# random.shuffle(preset_list)
# preset_dict = dict.fromkeys(preset_list)

def generate(template, convert):
    for k, v in convert.items():
        while k in template:
            template = template.replace(k, f"{v()}", 1)
    return template
# (x0, x1, y0, y1)
def check_collide(l: tuple[int, int, int, int], r: tuple[int, int, int, int]) -> bool:
    return (l[0] < r[0] < l[1] or l[0] < r[1] < l[1]) or (l[2] < r[2] < l[3] or l[2] < r[3] < l[3])

x=1
test = "l=(f32,f32,f32,f32);r=(f32,f32,f32,f32);o=check_collide(l,r)"
test = "l=(f32,f32,f32,f32);r=(f32,f32,f32,f32);o=(l[0] < r[0] < l[1] or l[0] < r[1] < l[1]) or (l[2] < r[2] < l[3] or l[2] < r[3] < l[3])"

statement = ";".join(
    [
        generate(
            test, 
            {
                "f32": random.random,
                # "dict_key": lambda: repr(random.choice(list(preset_dict)))
            }
        ) 
        for _ in range(size)
    ]
)
compiled = compile(statement, "<test>", "exec")
fast_load_exec = exec
import time
print("Start")
diff = []
for idx in range(double_size):
    x=1
    start = time.perf_counter_ns()
    fast_load_exec(compiled)
    end = time.perf_counter_ns()
    diff.append((end-start)/size)
    print(f"Completed {idx}")
mean = sum(diff)/len(diff)
delta = list(map(lambda x:(x-mean)**2, diff))
sd = (sum(delta)/len(delta))**0.5
print(f"{mean} ns, ±{sd} ns {double_size} run of {size} loop with test {test}")
#

Ignore the incorrect typehint since I only implemented random float

tranquil lake
#

would you mind trying this but using pygame rects instead ?

#

it has a colliderect method

#

(assuming the engine is to be based on pygame)

floral tangle
#

I do not have pygame running, and I am not familiar on it

floral tangle
orchid pebble
#

@tranquil lake

tranquil lake
#

yes ?

orchid pebble
#
import pygame
import sys
import random

# Инициализация
pygame.init()

# Настройки экрана и карты
SCREEN_WIDTH, SCREEN_HEIGHT = 800, 600
MAP_WIDTH, MAP_HEIGHT = 5000, 5000
FPS = 100

# Цвета
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLACK = (0, 0, 0)

# Игрок
PLAYER_SIZE = (50, 50)
PLAYER_SPEED = 5

# Препятствия
obstacles = []
lament needleBOT
#

Hey @orchid pebble!

Please edit your message to use a code block

Add a py after the three backticks.

```py
print('Hello, world!')
```

This will result in the following:

print('Hello, world!')```
orchid pebble
#
# AABB коллизия
def aabb_collision(rect1, rect2):
    return rect1.colliderect(rect2)

# Игровая функция
def main():
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    pygame.display.set_caption("Камера и динамика препятствий")
    clock = pygame.time.Clock()
    font = pygame.font.SysFont(None, 24)

    # Игрок
    player = pygame.Rect(100, 100, *PLAYER_SIZE)

    # Начальные препятствия
    for _ in range(50):
        x = random.randint(0, MAP_WIDTH - 100)
        y = random.randint(0, MAP_HEIGHT - 100)
        obstacles.append(pygame.Rect(x, y, 100, 100))

    while True:
        dt = clock.tick(FPS)
        screen.fill(WHITE)

        # Обработка событий
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

        # Управление
        keys = pygame.key.get_pressed()
        dx = dy = 0
        if keys[pygame.K_LEFT]: dx = -PLAYER_SPEED
        if keys[pygame.K_RIGHT]: dx = PLAYER_SPEED
        if keys[pygame.K_UP]: dy = -PLAYER_SPEED
        if keys[pygame.K_DOWN]: dy = PLAYER_SPEED

        # Добавление препятствий
        if keys[pygame.K_SPACE]:
            for _ in range(1000):  # Добавить 10 за раз
                x = random.randint(50, MAP_WIDTH - 50)
                y = random.randint(50, MAP_HEIGHT - 50)
                obstacles.append(pygame.Rect(x, y, 10, 10))

        # Перемещение игрока с проверкой коллизий
        new_rect_x = player.move(dx, 0)
        ```
#
            player.x += dx

        new_rect_y = player.move(0, dy)
        if not any(aabb_collision(new_rect_y, obs) for obs in obstacles):
            player.y += dy

        # Камера следует за игроком
        cam_x = player.x - SCREEN_WIDTH // 2
        cam_y = player.y - SCREEN_HEIGHT // 2

        # Ограничение камеры
        cam_x = max(0, min(cam_x, MAP_WIDTH - SCREEN_WIDTH))
        cam_y = max(0, min(cam_y, MAP_HEIGHT - SCREEN_HEIGHT))

        # Рисуем препятствия (в пределах экрана)
        for obs in obstacles:
            screen_x = obs.x - cam_x
            screen_y = obs.y - cam_y
            if -100 <= screen_x <= SCREEN_WIDTH and -100 <= screen_y <= SCREEN_HEIGHT:
                pygame.draw.rect(screen, RED, (screen_x, screen_y, obs.width, obs.height))

        # Рисуем игрока
        pygame.draw.rect(screen, GREEN, (player.x - cam_x, player.y - cam_y, *PLAYER_SIZE))

        # FPS и количество препятствий
        fps_text = font.render(f"FPS: {int(clock.get_fps())} | Obstacles: {len(obstacles)}", True, BLACK)
        screen.blit(fps_text, (10, 10))

        pygame.display.flip()

if __name__ == "__main__":
    main()

#

this code processed the colosseum of 80K sprites at 60 fps.

#

chat gpt wrote it for me for a test.

#

AABB

tranquil lake
orchid pebble
#

on my PC configuration, it's 60 fps.

tranquil lake
#

the variable FPS is set to 100

orchid pebble
tranquil lake
#

pygame doesn't care about your computer

orchid pebble
#

but fps dropped after 80k sprites

#

100 fps is the upper limit, but below fps can be

tranquil lake
#

yes it can, but if it works correlcty (so below you 80k) it shouldn't

orchid pebble
tranquil lake
#

also remember you are only trying to collide one object with multiple other objects

#

not these objects together

fossil cypress
#

Not an expert and i haven’t touched python in while and im not really good but isnt godot based on python?

tranquil lake
#

it's based on godotscript

tranquil lake
#

which is close to python

#

but isn't python

orchid pebble
#

another code has already drawn 650 objects, which it checks at one time

fossil cypress
#

Ok thanks. Sorry for the misinformation then.

tranquil lake
#

yes, python can be good enough

#

honestly it depends on what kind of game you would like to be done with your engine

orchid pebble
#

this is not much, but you can use optimization in the form of processing all coliseums through porous numbers, and when a collision is detected, send a signal, this will greatly speed up the work.

tranquil lake
#

you can also use a chunk system

#

to not check all collisions

#

plenty of things to be done

orchid pebble
tranquil lake
#

Honestly you can go for your game engine

#

it will take time and might not be as usefull as you would like to be

#

but it would still be a good project

orchid pebble
#

in general, I want to use Tolkien's pygame for rendering, and the first versions of the engine will be minimal.

tranquil lake
#

what's that ?

#

Tolkien's pygame ?

stiff heart
#

middle earth pygame version?

orchid pebble
#

I'm using a translator, sorry.

#

I want to use pygame to draw graphics.

tranquil lake
#

elf.init()

#

yeah so regular pygame then

#

while I am at it:
Use pygame-ce

stiff heart
#

pure pygame is fully on the CPU though. no GPU used. you'd have to use something else for that (like dafluffy did)

orchid pebble
#

pygame has an experimental model that uses a video card

#

GPU yes

#

pygame._sdl2.viedo

tranquil lake
#

yes

orchid pebble
#

it supports different rendering APIs. Open Gl, Vulkan, Diret X

#

The functionality of such a module is very limited, but there is such a thing.

stiff heart
#

eh

floral tangle
orchid pebble
floral tangle
#

So all object can collide with each other? Can you share the code?

orchid pebble
#

The code was written by chat gpt

floral tangle
#

But can you share it?

orchid pebble
#
import random
import sys

pygame.init()

# Параметры
WIDTH, HEIGHT = 800, 600
MAP_WIDTH, MAP_HEIGHT = 3000, 3000
NUM_BOXES = 650
BOX_SIZE = 20
PLAYER_SPEED = 4

screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("AABB Толкание 1000 объектов")
clock = pygame.time.Clock()
font = pygame.font.SysFont(None, 24)

# Игрок
player = pygame.Rect(1500, 1500, BOX_SIZE, BOX_SIZE)

# Прямоугольники
boxes = []
for _ in range(NUM_BOXES):
    while True:
        rect = pygame.Rect(
            random.randint(0, MAP_WIDTH - BOX_SIZE),
            random.randint(0, MAP_HEIGHT - BOX_SIZE),
            BOX_SIZE,
            BOX_SIZE
        )
        if not rect.colliderect(player):  # не спавним в игроке
            boxes.append(rect)
            break

# Камера
def get_camera(player):
    cam_x = max(0, min(player.x - WIDTH // 2, MAP_WIDTH - WIDTH))
    cam_y = max(0, min(player.y - HEIGHT // 2, MAP_HEIGHT - HEIGHT))
    return cam_x, cam_y

# AABB толкание
def resolve_push(mover, others):
    for other in others:
        if mover is other:
            continue
        if mover.colliderect(other):
            dx = (mover.centerx - other.centerx)
            dy = (mover.centery - other.centery)

            if abs(dx) > abs(dy):
                shift = 1 if dx > 0 else -1
                mover.x += shift
                other.x -= shift
            else:
                shift = 1 if dy > 0 else -1
                mover.y += shift
                other.y -= shift
lament needleBOT
#

Hey @orchid pebble!

Please edit your message to use a code block

Add a py after the three backticks.

```py
print('Hello, world!')
```

This will result in the following:

print('Hello, world!')```
orchid pebble
#
while True:
    dt = clock.tick(60)
    screen.fill((255, 255, 255))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    # Управление игроком
    keys = pygame.key.get_pressed()
    dx = dy = 0
    if keys[pygame.K_LEFT]: dx = -PLAYER_SPEED
    if keys[pygame.K_RIGHT]: dx = PLAYER_SPEED
    if keys[pygame.K_UP]: dy = -PLAYER_SPEED
    if keys[pygame.K_DOWN]: dy = PLAYER_SPEED

    player.move_ip(dx, 0)
    resolve_push(player, boxes)

    player.move_ip(0, dy)
    resolve_push(player, boxes)

    # Каждую коробку "толкаем" если есть столкновение
    for box in boxes:
        resolve_push(box, boxes + [player])

    # Камера
    cam_x, cam_y = get_camera(player)

    # Рендер
    pygame.draw.rect(screen, (0, 255, 0), player.move(-cam_x, -cam_y))
    for box in boxes:
        pygame.draw.rect(screen, (255, 0, 0), box.move(-cam_x, -cam_y))

    fps_text = font.render(f"FPS: {int(clock.get_fps())} | Boxes: {NUM_BOXES}", True, (0, 0, 0))
    screen.blit(fps_text, (10, 10))

    pygame.display.flip()
lament needleBOT
#

Hey @orchid pebble!

Please edit your message to use a code block

Add a py after the three backticks.

```py
print('Hello, world!')
```

This will result in the following:

print('Hello, world!')```
floral tangle
#

And how many FPS to you get?

orchid pebble
#

60

floral tangle
#

Try increase the box size and see?

orchid pebble
#

gpt has written a new version of the code, optimized by cells

lament needleBOT
orchid pebble
#

I think that with all the optimizations, it will be able to handle enough collisions to create most games.

floral tangle
#

Make all of them carry a initial velocity

orchid pebble
#

I'll try

lament needleBOT
orchid pebble
#

3500 obj

#

50-60 fps

#

3500 => 3000 obj

floral tangle
#

I get my phone to 40 fps by pushing 30 object at once in 1k

orchid pebble
floral tangle
#

oh ye I have pydroid and I thinl they might have preinstall pygame for demonstration

orchid pebble
floral tangle
#

Well my phone is probably the most powerful out of my device

#

but I am on 20fps on your new code

#

and moving to group of red box go to 11

vale tendon
#

If your only goal is to make something extremely basic, then it's fine, but I'd rather use an engine that can make something basic AND something advanced, instead of pick an engine that can only make basic things

#

if I decided my next game should be more advanced, now I need to switch engines? That seems silly

#

There's a lot of shared code between in house games, like handling character control, pathing, cameras, state machines, etc

scarlet spade
# vale tendon If your *only* goal is to make something extremely basic, then it's fine, but I'...

Yes this is a very valid point. or not even the case of if your next game you want to be more advanced but you could get to a point where your original game grows to a point of the engine limits which means either you do have to abandone the game because of engine limits or you have to refactor the whole thing into another engine. Which easily could have been avoided by choosing a more capable engine to begin with.

And yes, re-using assets is a very real benefit in indie dev and really dev in general but certainly for games where it is more than just code that makes up your game.

#

And also to the point of a phone running the code is a valid point too. Like yes mobile devices tend to be weaker than other platforms but also you are now also cutting a platform out of support for a game engine. good luck getting a python based engine to be chosen for mobile games. And mobile games is a very big industry

orchid pebble
#

that is the final conclusion.

Is my idea of engine not promising at all and absolutely no one will use it?

scarlet spade
#

I go by my earlier statement, but the TL;DR version of it is. "I think creating your own game engine if you are passionate about it, and especially if you want to extend that into making your own game using it would be an incredible investment in learning and growing as a dev. I would not expect it to be something that gets wide use (if much at all) as a replacement to any existing engines or options if the engine is being created in Python."

lament needleBOT
#
Python help channel closed for inactivity

This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.