PYTHON 使用退出键退出时出现问题

2024-02-08

我在使用以下代码时遇到问题。它似乎对退出键有反应,但它冻结得很厉害。我将 pyscripter 与 python 2.7 和 pygame 一起使用。

# An example implementation of the algorithm described at
# http://www.niksula.cs.hut.fi/~hkankaan/Homepages/metaballs.html
#
# The code contains some references to the document above, in form
# ### Formula (x)
# to make clear where each of the formulas is implemented (and what
# it looks like in Python)
#
# Since Python doesn't have an in-built vector type, I used complex
# numbers for coordinates (x is the real part, y is the imaginary part)
#
# Made by Hannu Kankaanpää. Use for whatever you wish.

import math

import pygame
from pygame.locals import *


def main():
    # This is where the execution starts.
    # First initialize the screen.
    pygame.init()
    screen = pygame.display.set_mode((640, 480))

    # Then create a couple of balls
    balls = [Ball(350 + 100j, size=3),
             Ball(20  + 200j, size=2),
             Ball(280 + 140j, size=4),
             Ball(400 + 440j, size=3)]

    # And a metaball system (see below for class definition)
    mbs = MetaballSystem(balls, goo=2.0, threshold=0.0004, screen=screen)

    while True:
        # clear screen with black
        screen.fill((0, 0, 0))

        # move ball number 0 according to mouse position
        if pygame.mouse.get_focused():
            balls[0].pos = complex(*pygame.mouse.get_pos())

        # Draw the balls.
        # Try different methods: euler, rungeKutta2 and rungeKutta4
        drawBalls(differentialMethod=rungeKutta2, metaballSystem=mbs,
                  step=20, screen=screen)
        pygame.display.flip()

        # exit when esc is pressed
        for event in pygame.event.get():
            if event.type == QUIT:
                return
            elif event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    return


def drawBalls(differentialMethod, metaballSystem, step, screen):
    mbs = metaballSystem
    balls = mbs.balls

    # First, track the border for all balls and store
    # it to pos0 and edgePos. The latter will move along the border,
    # pos0 stays at the initial coordinates.
    for ball in balls:
        ball.pos0 = mbs.trackTheBorder(ball.pos + 1j)
        ball.edgePos = ball.pos0
        ball.tracking = True

    loopIndex = 0
    while loopIndex < 200:
        loopIndex += 1
        for ball in balls:
            if not ball.tracking:
                continue

            # store the old coordinates
            old_pos = ball.edgePos

            # walk along the tangent, using chosen differential method
            ball.edgePos = differentialMethod(ball.edgePos, step, mbs.calcTangent)

            # correction step towards the border
            ball.edgePos, tmp = mbs.stepOnceTowardsBorder(ball.edgePos)

            pygame.draw.line(screen, (255, 255, 255),
                             (old_pos.real, old_pos.imag),
                             (ball.edgePos.real, ball.edgePos.imag))

            # check if we've gone a full circle or hit some other
            # edge tracker
            for ob in balls:
                if (ob is not ball or loopIndex > 3) and \
                   abs(ob.pos0 - ball.edgePos) < step:
                    ball.tracking = False

        tracking = 0
        for ball in balls:
            if ball.tracking:
                tracking += 1
        if tracking == 0:
            break


class Ball:
    """Single metaball."""
    def __init__(self, pos, size):
        self.pos = pos
        self.size = size


class MetaballSystem:
    """A class that manages the metaballs and can calculate
       several useful values from the system.
    """

    def __init__(self, balls, goo, threshold, screen):
        self.balls = balls
        self.goo = goo
        self.threshold = threshold
        self.minSize = min([ball.size for ball in balls])
        self.screen = screen

    def calcForce(self, pos):
        """Return the metaball field's force at point 'pos'."""
        force = 0
        for ball in self.balls:
            ### Formula (1)
            div = abs(ball.pos - pos)**self.goo
            if div != 0: # to prevent division by zero
                force += ball.size / div
            else:
                force += 10000 #"big number"
        return force

    def calcNormal(self, pos):
        """Return a normalized (magnitude = 1) normal at point 'pos'."""
        np = 0j
        for ball in self.balls:
            ### Formula (3)
            div = abs(ball.pos - pos)**(2 + self.goo)
            np += -self.goo * ball.size * (ball.pos - pos) / div
        return np / abs(np)

    def calcTangent(self, pos):
        """Return a normalized (magnitude = 1) tangent at point 'pos'."""
        np = self.calcNormal(pos)
        ### Formula (7)
        return complex(-np.imag, np.real)

    def stepOnceTowardsBorder(self, pos):
        """Step once towards the border of the metaball field, return
           new coordinates and force at old coordinates.
        """
        force = self.calcForce(pos)
        np = self.calcNormal(pos)
        ### Formula (5)
        stepsize = (self.minSize / self.threshold)**(1 / self.goo) - \
                   (self.minSize / force)**(1 / self.goo) + 0.01
        return (pos + np * stepsize, force)

    def trackTheBorder(self, pos):
        """Track the border of the metaball field and return new
           coordinates.
        """
        force = 9999999
        # loop until force is weaker than the desired threshold
        while force > self.threshold:
            pos, force = self.stepOnceTowardsBorder(pos)
            # show a little debug output (i.e. plot yellow pixels)
            sz = self.screen.get_size()
            if 0 <= pos.real < sz[0] and 0 <= pos.imag < sz[1]:
                self.screen.set_at((int(pos.real), int(pos.imag)), (255, 255, 0))
        return pos


def euler(pos, h, func):
    """Euler's method.
       The most simple way to solve differential systems numerically.
    """
    return pos + h * func(pos)


def rungeKutta2(pos, h, func):
    """Runge-Kutta 2 (=mid-point).
       This is only a little more complex than the Euler's method,
       but significantly better.
    """
    return pos + h * func(pos + func(pos) * h / 2)


def rungeKutta4(pos, h, func):
    """Runge-Kutta 4.
       RK4 is quite a bit more complex than RK2. RK2 with a
       small stepsize is often more useful than this.
    """
    t1 = func(pos)
    t2 = func(pos + t1 * h / 2)
    t3 = func(pos + t2 * h / 2)
    t4 = func(pos + t3 * h)
    return pos + (h / 6) * (t1 + 2*t2 + 2*t3 + t4)


if __name__ == '__main__': main()

我只是像这样修改了代码,谢谢giantenigma

#exit when esc is pressed
for event in pygame.event.get():
   if event.type == QUIT:
       return
   elif event.type == KEYDOWN:
       if event.key == K_ESCAPE:
           pygame.quit()
           return
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

PYTHON 使用退出键退出时出现问题 的相关文章

  • 如何把父母和孩子联系起来?

    有两个简单的类 一个只有parent属性 并且两者兼而有之parent and children属性 这意味着同时具备两者的人parent and children继承自唯一的parent 这是只有parent属性 我们就这样称呼它吧Chi
  • 从 torch.autograd.gradcheck 导入 zero_gradients

    我想复制代码here https github com LTS4 DeepFool blob master Python deepfool py 并且我在 Google Colab 中运行时收到以下错误 ImportError 无法导入名称
  • App Engine 上的 Django 与 webapp2 [关闭]

    就目前情况而言 这个问题不太适合我们的问答形式 我们希望答案得到事实 参考资料或专业知识的支持 但这个问题可能会引发辩论 争论 民意调查或扩展讨论 如果您觉得这个问题可以改进并可能重新开放 访问帮助中心 help reopen questi
  • docker 容器中的“(pygame parachute)分段错误”

    尝试在 docker 容器中使用 pygame 时出现以下错误 我想从容器中获取显示 Fatal Python error pygame parachute Segmentation Fault 重现 Docker已安装 docker ru
  • DynamodB:如何更新排序键?

    该表有两个键 filename 分区键 和eventTime 排序键 我要更新eventTime对于某些filename Tried put item and update item 发送相同的filename与新的eventTime但这些
  • 动态字段取决于 WTForms 的先前字段

    我正在使用 WTForms 制作表格 目前 我有这个 class UploadForm flask wtf Form fichier wtforms fields FileField u Fichier description wtform
  • 使用 Pandas 从 csv 文件读取标题信息

    我有一个包含 14 行标题的数据文件 在标头中 有经纬度坐标和时间的元数据 我目前正在使用 pandas read csv filename delimiter header 14 读取文件 但这只是获取数据 我似乎无法获取元数据 有人知道
  • 为什么需要设置WORKON_HOME环境变量?

    我已经有一段时间没有使用 python 虚拟环境了 但我也安装了虚拟环境包装器 我的问题是 在文档页面中它说要这样做 export WORKON HOME Envs mkdir p WORKON HOME source usr local
  • 获取 Keras model.summary() 作为表

    我在 Keras 中创建了相当大的模型 我正在用 LaTeX 写一篇关于它的文章 为了很好地描述 LaTeX 中的 keras 模型 我想用它创建一个 LaTeX 表 我可以手动实现它 但我想知道是否有任何 更好 的方法来实现这一点 我四处
  • 如何知道python运行脚本的路径?

    sys arg 0 给我 python 脚本 例如 python hello py 返回 sys arg 0 的 hello py 但我需要知道 hello py 位于完整路径中的位置 我怎样才能用Python做到这一点 os path a
  • 无法通过 Android 应用程序访问我的笔记本电脑的本地主机

    因此 我在发布此内容之前做了一项研究 我发现的解决方案不起作用 更准确地说 连接到我的笔记本电脑的 IPv4192 168 XXX XXX 没用 连接到10 0 2 2 加上端口 不起作用 我需要测试使用 Django Rest 框架构建的
  • 如何从 python 脚本执行 7zip 命令

    我试图了解如何使用 os system 模块来执行 7zip 命令 现在我不想用 Popen 或 subprocess 让事情变得复杂 我已经安装了 7zip 并将 7zip exe 复制到我的用户文件夹中 我只想提取我的测试文件 inst
  • multiprocessing.Queue 中的 ctx 参数

    我正在尝试使用 multiprocessing Queue 模块中的队列 实施 https docs python org 3 4 library multiprocessing html exchang objects Between p
  • Flymake的临时文件可以在系统临时目录下创建吗?

    我目前正在使用以下代码在 emacs 中连接 Flymake 和 Pyflakes defun flymake create temp in system tempdir filename prefix make temp file or
  • 哪种方式最适合Python工厂注册?

    这是一个关于这些方法中哪一种被认为是最有效的问题 Pythonic 我不是在寻找个人意见 而是在寻找惯用的观点 我的背景不是Python 所以这会对我有帮助 我正在开发一个可扩展的 Python 3 项目 这个想法类似于工厂模式 只不过它是
  • Python:导入模块一次然后与多个文件共享

    我有如下文件 file1 py file2 py file3 py 假设这三个都使用 lib7 py lib8 py lib9 py 目前 这三个文件中的每一个都有以下行 import lib7 import lib8 import lib
  • 如何将 URL 添加到 Telegram Bot 的 InlineKeyboardButton

    我想制作一个按钮 可以从 Telegram 聊天中在浏览器中打开 URL 外部超链接 目前 我只开发了可点击的操作按钮 update message reply text Subscribe to us on Facebook and Te
  • 将 Django 中的所有视图限制为经过身份验证的用户

    我是 Django 新手 我正在开发一个项目 该项目有一个登录页面作为其索引和一个注册页面 其余页面都必须仅限于登录用户 如果未经身份验证的用户尝试访问这些页面 则必须将他 她重定向到登录页面 我看到 login required装饰器会将
  • 从给定的项目列表创建子列表

    我首先要说的是以下问题不是为了家庭作业目的即使因为我几个月前就完成了软件工程师的工作 无论如何 今天我正在工作 一位朋友向我询问了这个奇怪的排序问题 我有一个包含 1000 行的列表 每行代表一个数字 我想创建 10 个子列表 每个子列表都
  • ProcessPoolExecutor 传递多个参数

    ESPN播放器免费 class ESPNPlayerFree def init self player id match id match id team 团队名单1 277906 cA2i150s81HI3qbq1fzi za1Oq5CG

随机推荐