javascript - HTML、Python、Brython、javascript - 在 Brython 上运行

标签 javascript python html brython

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

基础是从示例中获取的(它没有工作)文件 http://www.brython.info/gallery/pygame/chimp.html

同一目录下有3个文件:Eventlist.htmlpy_VFS.jsbrython.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 中的代码有效,结果如下: enter image description here

因此,我想在浏览器中得到一个类似的窗口。

最佳答案

这几天我花了一些时间试图获得 Brython-PyGame在浏览器中工作并得出结论:

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

详情如下:

实现不完整

Brython-PyGame 有许多未实现的函数。其中一些可以被认为是非关键的(例如,模块 transform.py 完全缺失)。但是其他的则是任何 PyGame 程序的核心。例如,event.py module 中的所有非平凡函数,例如 event.get()event.wait(),依赖于对 SDL.py 中未实现函数的调用,例如 SDL_WaitEventAndReturn()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 实现没有实现这种幕后处理,导致上述代码失败,因为图像在加载之前会被 block 化。

关于javascript - HTML、Python、Brython、javascript - 在 Brython 上运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40300705/

相关文章:

javascript - React - 条件渲染(多个数组的迭代)

python - 在对我的 Windows 电脑进行基准测试后,重新安装所有 Python 库的有效方法是什么?

html - CSS 网格中的元素不跨越两行

html - 显示一组带有内联标题的图像,同时保持按高度缩放

html - 使标题 div 位于顶层

javascript - object[0] 是 JavaScript 中对象的默认键吗?

javascript - react-stripe-elements 获得 "Cannot read property ' props' of undefined"

javascript - 如何使用 mongoose db.collection.find() 的返回值编写条件逻辑?

php - 如何从 PHP 过渡到 Python Django?

python - 字典的键在添加时顺序不对?