0

I'm trying to have a website where you can play games. You will eventually be able to click a button and launch a pygame window to play the game. To test whether I can do this with Django, I'm trying to launch the pygame window when I go to the home page as a proof of concept. However, I'm having trouble figuring out how exactly to launch the window.

Here is my first attempt in views.py:

from .games import game

def home_page(request):
    title = "Home Page"
    template_name = "home.html"
    if request.user.is_authenticated:
        message = f'Hello there, {request.user}!'
    else:
        message = 'Hello there!'
    game.main()
    return render(request, template_name, {'title': title, 'message': message})

My game.py (located in a games folder, which is in the same directory as my views.py:

import pygame
import sys

def main():
    pygame.init()

    screen = pygame.display.set_mode((50, 50))
    pygame.display.set_caption("Test")

    while True:
        screen.fill((255, 255, 255))
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
        pygame.display.update()

When I run the server and try to go 127.0.0.1:8000 (where my site is located), neither the page nor the pygame window would load. When I quit the server, the web page showed that it could not find the site. I think this was because the code never reached the return render(request, template_name, {'title': title, 'message': message}) part of my views.py.

How can open a pygame window when I go to the home page?

Cameron
  • 389
  • 1
  • 9

1 Answers1

1

Fundamentally, this approach won't work, because you're running the code on your server, but you want the pygame window to appear on the screen of the person who's visiting your website. Your code needs to run client-side. Your options are to move everything out of the web browser (i.e., provide a file for the user to download, and have the user run the game on his own machine) or to somehow use JavaScript as an intermediary, as with Pyodide or Brython. Probably the latter approach won't work if you want to use pygame.

Kodiologist
  • 2,984
  • 18
  • 33