3

帮助使用 Brython 在 Python 中运行一个简单的程序。

基础(它不起作用)来自示例http://www.brython.info/gallery/pygame/chimp.html

同一目录下有 3 个文件:Eventlist.html, py_VFS.js, brython.js.

py_VFS.js

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL py_VFS.js was not found on this server.</p>
</body></html>

brython.js

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL brython.js was not found on this server.</p>
</body></html>

Eventlist.html行中的固定路径:

<script type="text/javascript" src="external/brython/brython.js"></script>
<script type="text/javascript" src="external/brython/py_VFS.js"></script>

并且替换了一个 Python 模块(pygame\examples\eventlist.py 的标准单元)。于是,Eventlist.html的整个代码:

<html>

<head>

<script type="text/javascript" src="brython.js"></script>
<script type="text/javascript" src="py_VFS.js"></script>

<script type="text/python">
#!/usr/bin/env python

"""Eventlist is a sloppy style of pygame, but is a handy
tool for learning about pygame events and input. At the
top of the screen are the state of several device values,
and a scrolling list of events are displayed on the bottom.

This is not quality 'ui' code at all, but you can see how
to implement very non-interactive status displays, or even
a crude text output control.
"""

from pygame import *

ImgOnOff = []
Font = None
LastKey = None

def showtext(win, pos, text, color, bgcolor):
    textimg = Font.render(text, 1, color, bgcolor)
    win.blit(textimg, pos)
    return pos[0] + textimg.get_width() + 5, pos[1]


def drawstatus(win):
    bgcolor = 50, 50, 50
    win.fill(bgcolor, (0, 0, 640, 120))
    win.blit(Font.render('Status Area', 1, (155, 155, 155), bgcolor), (2, 2))

    pos = showtext(win, (10, 30), 'Mouse Focus', (255, 255, 255), bgcolor)
    win.blit(ImgOnOff[mouse.get_focused()], pos)

    pos = showtext(win, (330, 30), 'Keyboard Focus', (255, 255, 255), bgcolor)
    win.blit(ImgOnOff[key.get_focused()], pos)

    pos = showtext(win, (10, 60), 'Mouse Position', (255, 255, 255), bgcolor)
    p = '%s, %s' % mouse.get_pos()
    pos = showtext(win, pos, p, bgcolor, (255, 255, 55))

    pos = showtext(win, (330, 60), 'Last Keypress', (255, 255, 255), bgcolor)
    if LastKey:
        p = '%d, %s' % (LastKey, key.name(LastKey))
    else:
        p = 'None'
    pos = showtext(win, pos, p, bgcolor, (255, 255, 55))

    pos = showtext(win, (10, 90), 'Input Grabbed', (255, 255, 255), bgcolor)
    win.blit(ImgOnOff[event.get_grab()], pos)


def drawhistory(win, history):
    win.blit(Font.render('Event History Area', 1, (155, 155, 155), (0,0,0)), (2, 132))
    ypos = 450
    h = list(history)
    h.reverse()
    for line in h:
        r = win.blit(line, (10, ypos))
        win.fill(0, (r.right, r.top, 620, r.height))
        ypos -= Font.get_height()


def main():
    init()

    win = display.set_mode((640, 480), RESIZABLE)
    display.set_caption("Mouse Focus Workout")

    global Font
    Font = font.Font(None, 26)

    global ImgOnOff
    ImgOnOff.append(Font.render("Off", 1, (0, 0, 0), (255, 50, 50)))
    ImgOnOff.append(Font.render("On", 1, (0, 0, 0), (50, 255, 50)))

    history = []

    #let's turn on the joysticks just so we can play with em
    for x in range(joystick.get_count()):
        j = joystick.Joystick(x)
        j.init()
        txt = 'Enabled joystick: ' + j.get_name()
        img = Font.render(txt, 1, (50, 200, 50), (0, 0, 0))
        history.append(img)
    if not joystick.get_count():
        img = Font.render('No Joysticks to Initialize', 1, (50, 200, 50), (0, 0, 0))
        history.append(img)

    going = True
    while going:
        for e in event.get():
            if e.type == QUIT:
                going = False
            if e.type == KEYDOWN:
                if e.key == K_ESCAPE:
                    going = False
                else:
                    global LastKey
                    LastKey = e.key
            if e.type == MOUSEBUTTONDOWN:
                event.set_grab(1)
            elif e.type == MOUSEBUTTONUP:
                event.set_grab(0)
            if e.type == VIDEORESIZE:
                win = display.set_mode(e.size, RESIZABLE)

            if e.type != MOUSEMOTION:
                txt = '%s: %s' % (event.event_name(e.type), e.dict)
                img = Font.render(txt, 1, (50, 200, 50), (0, 0, 0))
                history.append(img)
                history = history[-13:]


        drawstatus(win)
        drawhistory(win, history)

        display.flip()
        time.wait(10)

    quit()


if __name__ == '__main__':
    main()

</script>
</head>
<body onload="brython({debug:1})">
  <div id="pydiv"></div>
</body>

</html>

当您Eventlist.html在浏览器中运行一个空白页面时。该文件中的代码eventlist.py有效,结果如下: 在此处输入图像描述

结果,我想在浏览器中获得一个类似的窗口。

4

1 回答 1

2

在过去的几天里,我花了一些时间试图让Brython-PyGame在浏览器中工作,并得出结论:

  1. Brython-PyGame从未完全实现。
  2. 由于 PyGame 和浏览器在用户交互建模方式上存在根本差异,因此在 Brython 中实现完整的 PyGame 版本几乎是不可能的。

以下是详细信息:

实施不完整

Brython-PyGame 有许多未实现的功能。其中一些可能被认为是非关键的(例如,模块transform.py完全缺失)。但是其他的却是任何 PyGame 程序的核心。例如,event.py 模块中的所有重要函数,例如event.get()and event.wait(),都依赖于对SDL.py中未实现函数的调用,例如SDL_WaitEventAndReturn()and SDL_PeepEvents()。如果没有这些函数之一作为其事件循环的基础,任何重要的 PyGame 程序都无法工作。

基本设计差异

event.wait()从未完全实施的事实并非巧合。此功能触及 PyGame 和客户端 Web 编程之间概念设计差异的核心:

  • PyGame 假定控制运行您的游戏的应用程序,这意味着它可以并且经常确实阻塞主线程,直到发生感兴趣的事件。
  • 相比之下,JavaScript 编程不允许阻塞主 JS 线程,因为该线程用于页面的 UI 渲染。如果您尝试阻止此线程,浏览器将显示一条消息,说明该页面已无响应,并建议用户关闭选项卡。相反,JS 在很大程度上依赖于在事件发生时运行的 Promise 和回调。

因此,在浏览器的客户端中无法实现对 的调用,该调用会event.wait()阻塞直到发生诸如鼠标移动之类的事件。

在其他情况下,PyGame 以 JavaScript 不允许的方式使用阻塞调用。例如,考虑以下看似无辜的 PyGame 片段:

import pygame as pg
img = pg.image.load('flag.png')
screen.blit(img, (0,0))

这会加载一个图像文件并将其呈现在屏幕上。在幕后,当文件被读入内存时,pg.image.load命令会阻塞。在 Brython-PyGame 中,实现尝试从给定的 URL 读取文件。但是,读取 URL 在 JavaScript 中是非阻塞操作,因为所需的网络操作可能需要一段时间,而且我们不希望 UI 线程在完成之前阻塞。在 JavaScript 中,可以实现类似的操作,例如

var img = new Image();
ctx = getContextForSomeCanvas();
img.onload = function() {
  ctx.drawImage(img, 0, 0);
}
img.src = 'flag.png';

onload回调确保只有在ctx.drawImage图像加载后才会执行。将以前的 Python 代码转换为类似于上述 JavaScript 的代码并非易事:它需要对异步加载操作进行一些幕后处理,这将延迟调用blit()直到加载图像。即使这可以工作,对于一个天真的 PyGame 程序员来说也是非常不直观的,并且很容易在代码中导致错误(例如,如果代码假设鼠标点击在图像上,即使它还没有加载然而)。在任何情况下,Brython-PyGame 实现都没有实现这种幕后处理,导致上面的代码失败,因为图像在加载之前会被 blitted。

于 2020-10-01T07:55:45.767 回答