使用 pygame.transform.rotate 时内存不足

2024-02-01

我写了一个脚本,允许用户控制老鹰的精灵飞来飞去以学习pygame。看起来很好,直到我实现了一个旋转函数,使精灵根据其飞行方向旋转。移动一小会儿后,精灵变得非常模糊,很快就会弹出一个错误:内存不足(在这一行:eagle_img = pygame.transform.rotate(eagle_img,new_angle-angle))

My code:

# eagle movement script
import pygame, math, sys
from pygame.locals import *
pygame.init()
clock = pygame.time.Clock()

# terminate function
def terminate():
    pygame.quit()
    sys.exit()

# incircle function, check if mouse click is inside controller
def incircle(coordinates,cir_center,cir_out_rad):
    if math.sqrt((coordinates[0]-cir_center[0])**2+\
                 (coordinates[1]-cir_center[1])**2) <= cir_out_rad:
        return True
    return False

# speed function, translates the controller movement into eagle movement
def speed(position,cir_center,eagle_speed):
    x_dist = position[0] - cir_center[0]
    y_dist = position[1] - cir_center[1]
    dist = math.sqrt(x_dist**2+y_dist**2)   # distance from controller knob to center
    if dist != 0:
        return [(x_dist/dist)*eagle_speed,(y_dist/dist)*eagle_speed]
    else:
        return [0,0]

# rotation function, rotates the eagle image
def rotation(position,cir_center):
    x_dist = position[0] - cir_center[0]
    y_dist = position[1] - cir_center[1]
    new_radian = math.atan2(-y_dist,x_dist)
    new_radian %= 2*math.pi
    new_angle = math.degrees(new_radian)
    return new_angle

# screen
screenw = 1000
screenh = 700
screen = pygame.display.set_mode((screenw,screenh),0,32)
pygame.display.set_caption('eagle movement')

# variables
green = (0,200,0)
grey = (100,100,100)
red = (255,0,0)
fps = 60

# controller
cir_out_rad = 150    # circle controller outer radius
cir_in_rad = 30     # circle controller inner radius
cir_center = [screenw-cir_out_rad,int(screenh/2)]
position = cir_center    # mouse position

# eagle
eaglew = 100
eagleh = 60
eagle_speed = 3
eagle_pos = [screenw/2-eaglew/2,screenh/2-eagleh/2]
eagle = pygame.Rect(eagle_pos[0],eagle_pos[1],eaglew,eagleh)
eagle_img = pygame.image.load('eagle1.png').convert()
eagle_bg_colour = eagle_img.get_at((0,0))
eagle_img.set_colorkey(eagle_bg_colour)
eagle_img = pygame.transform.scale(eagle_img,(eaglew,eagleh))

# eagle controls
stop_moving = False # becomes True when player stops clicking
rotate = False      # becomes True when there is input
angle = 90          # eagle is 90 degrees in the beginning

# game loop
while True:
    # controls
    for event in pygame.event.get():
        if event.type == QUIT:
            terminate()
        if event.type == MOUSEBUTTONUP:
            stop_moving = True
            rotate = False

    mouse_input = pygame.mouse.get_pressed()
    if mouse_input[0]:
        coordinates = pygame.mouse.get_pos()    # check if coordinates is inside controller
        if incircle(coordinates,cir_center,cir_out_rad):
            position = pygame.mouse.get_pos()
            stop_moving = False
            rotate = True
        else:
            cir_center = pygame.mouse.get_pos()
            stop_moving = False
            rotate = True
    key_input = pygame.key.get_pressed()
    if key_input[K_ESCAPE] or key_input[ord('q')]:
        terminate()

    screen.fill(green)

    [dx,dy] = speed(position,cir_center,eagle_speed)
    if stop_moving:
        [dx,dy] = [0,0]
    if eagle.left > 0:
        eagle.left += dx
    if eagle.right < screenw:
        eagle.right += dx
    if eagle.top > 0:
        eagle.top += dy
    if eagle.bottom < screenh:
        eagle.bottom += dy

    if rotate:
        new_angle = rotation(position,cir_center)
        if new_angle != angle:
            eagle_img = pygame.transform.rotate(eagle_img,new_angle-angle)
            eagle = eagle_img.get_rect(center=eagle.center)
        rotate = False
        angle = new_angle

    outer_circle = pygame.draw.circle(screen,grey,(cir_center[0],cir_center[1]),\
                                  cir_out_rad,3)
    inner_circle = pygame.draw.circle(screen,grey,(position[0],position[1]),\
                                  cir_in_rad,1)
    screen.blit(eagle_img,eagle)
    pygame.display.update()
    clock.tick(fps)

请告诉我这里出了什么问题以及如何改进。请随意使用名为“eagle1.png”的精灵尝试代码。谢谢!


你的鹰图片变得模糊的原因是因为你不断地旋转同一个png,而不是制作副本并旋转该副本,同时始终保留未编辑的图片。这是我在旋转方形图像时一直使用的函数

def rot_center(image, angle):
    """rotate an image while keeping its center and size"""
    orig_rect = image.get_rect()
    rot_image = pygame.transform.rotate(image, angle)
    rot_rect = orig_rect.copy()
    rot_rect.center = rot_image.get_rect().center
    rot_image = rot_image.subsurface(rot_rect).copy()
    return rot_image

这是一个适合任何形状的图片的

def rot_center(image, rect, angle):
        """rotate an image while keeping its center"""
        rot_image = pygame.transform.rotate(image, angle)
        rot_rect = rot_image.get_rect(center=rect.center)
        return rot_image,rot_rect

来源自here http://www.pygame.org/wiki/RotateCenter?parent=CookBook%22here%22

至于“内存不足”错误,我不确定,但我认为泄漏是由于一遍又一遍地旋转同一个 png 文件引起的。从一些研究来看,这似乎经常发生在其他人身上。

希望这有助于澄清一些事情:)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 pygame.transform.rotate 时内存不足 的相关文章

  • 使用多个具有不同日志级别的处理程序时出现意外的 python 记录器输出

    我正在尝试将数据记录到 stderr 并记录到文件中 该文件应包含all日志消息 并且 stderr 应该只转到命令行上配置的日志级别 这在日志记录指南中多次描述 但它似乎对我不起作用 我创建了一个小测试脚本来说明我的问题 usr bin
  • 如何在 Python 中使用 .format() 打印“for”循环中的列表?

    我是 Python 新手 我正在编写一段非常简单的代码 使用 for 循环打印列表的内容 format 我想要如下的输出 但我收到此错误 names David Peter Michael John Bob for i in names p
  • Flask/Apache 提交按钮用于文件上传

    我有一个在 apache 后面运行的 Flask 应用程序 在我的 index html 页面上有一个文件上传按钮和一个提交按钮 如下所示
  • 使用 for 循环 Python 为数组赋值

    我正在尝试将字符串的值分配给不同的数组索引 但我收到一个名为 列表分配超出范围 的错误 uuidVal distVal uuidArray distArray for i in range len returnedList for beac
  • 为什么具有复杂无穷大的 NumPy 运算会导致有趣的结果?

    我注意到复杂的无穷大的有趣结果 In 1 import numpy as np In 2 np isinf 1j np inf Out 2 True In 3 np isinf 1 1j np inf Out 3 True In 4 np
  • python 类的属性不在 __init__ 中

    我想知道为什么下面的代码有效 usr bin env python3 import sys class Car def init self pass if name main c Car c speed 3 c time 5 print c
  • 类型错误:只有长度为 1 的数组可以转换为 Python 标量

    我是 openCV 的初学者 正在尝试分析数独求解器的现有代码 有这一段代码会引发错误 samples np float32 np loadtxt feature vector pixels data responses np float3
  • 生产环境的 Flask-Login 与 Flask-Security

    我正在构建一个功能 供用户注册 登录 验证和授权自己 特别是使用 Python Flask 作为后端 我找到了一些解决方案 例如flask login and flask security 据我了解 flask login实际上并没有进行任
  • 在 PyCharm 中运行命令行命令

    你好 我正在使用Python 但之前从未真正使用过它 我收到一些命令 需要在终端中运行 基本上 python Test py GET feeds 我正在使用 PyCharm 我想知道是否有办法从该 IDE 中运行这些相同的命令 按 Alt
  • 替换 pandas 数据框中的点

    我有一个如图所示的数据框 数字实际上是对象 正在做df treasury rate pd to numeric df treasury rate 可预见的炸弹 然而 做df replace np nan 似乎没有摆脱这个点 所以我很困惑 有
  • 将多个 isinstance 检查转换为结构模式匹配

    我想转换此现有代码以使用模式匹配 if isinstance x int pass elif isinstance x str x int x elif isinstance x float Decimal x round x else r
  • 安装python启动文件

    我如何安装pythonstartup文件 以便它在命令上运行 例如python myfile py 我尝试将其安装到我的 home myuserUbuntu的目录 但它说我没有足够的权限 此外 不同的地方交替说它应该全部大写或全部小写 前面
  • Python:如何使用生成器来避免 sql 内存问题

    我有以下方法来访问 mysql 数据库 并且查询在服务器中执行 我无权更改有关增加内存的任何内容 我对生成器很陌生 并开始阅读更多有关它的内容 并认为我可以将其转换为使用生成器 def getUNames self globalUserQu
  • 在 Django 中翻译文件时的 Git 命令

    我在 Django 中有一个现有的应用程序 我想在页面上添加翻译 在页面上我有 trans Projects 在 po 文件中我添加了 templates staff site html 200 msgid Projects msgid P
  • 使用多行选项和编码选项读取 CSV

    在 azure Databricks 中 当我使用以下命令读取 CSV 文件时multiline true and encoding SJIS 似乎编码选项被忽略了 如果我使用multiline选项 Spark 使用默认值encoding那
  • 检测计算机何时解锁 Windows

    我用过这个优秀的方法 https stackoverflow com questions 20733441 lock windows workstation using python 20733443锁定 Windows 计算机 那部分工作
  • Django:在单独的线程中使用相同的测试数据库

    我正在使用具有以下数据库设置的测试数据库运行 pytests DATABASES default ENGINE django db backends postgresql psycopg2 NAME postgres USER someth
  • 为什么 Python exec 中的模块级变量无法访问?

    我正在尝试使用Pythonexec in a project https github com arjungmenon pypage执行嵌入的Python代码 我遇到的问题是在模块级 in an exec声明是难以接近的来自同一模块中定义的
  • 有效积累稀疏 scipy 矩阵的集合

    我有一个 O N NxN 的集合scipy sparse csr matrix 每个稀疏矩阵都有 N 个元素集 我想将所有这些矩阵加在一起以获得一个常规的 NxN numpy 数组 N 约为 1000 矩阵内非零元素的排列使得所得总和肯定不
  • Scrapy - 持续从数据库中获取要爬取的url

    我想不断地从数据库中获取要爬行的网址 到目前为止 我成功地从基地获取了 url 但我希望我的蜘蛛继续从该基地读取 因为该表将由另一个线程填充 我有一个管道 一旦爬行 工作 就会从表中删除 url 换句话说 我想使用我的数据库作为队列 我尝试

随机推荐