python - pygame中绘制的图像与给出的位置不匹配
问题描述
大家好,我正在学习pygame的基础知识。我最近遇到了一个问题;我决定加载一个图像并在 pygame 窗口中给它一个随机位置。但问题是有时它不会出现在窗口中。所以我在要加载图像的地方画了一个黑色的指针。然后我发现黑色指针与图像不一致,因此图像没有出现在我想要的位置。所以我想帮助解决这个问题。先感谢您。代码:
import pygame
import random
pygame.init()
#Pygame starters
display_width = 800
display_height = 600
game_display = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Blob runner")
clock = pygame.time.Clock()
targetpng = pygame.image.load("target.png")
#Quit checker
crashed = False
#COLOURS
white = (255, 255, 255)
black = (0, 0, 0)
def draw_environment(x,y):
game_display.fill(white)
#Image
game_display.blit(targetpng,(x, y))
#Black pointer
pygame.draw.circle(game_display, black, (x, y), 5 )
pygame.display.update()
x, y = random.randrange(0,display_width), random.randrange(0,display_height)
while not crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
# print(event)
draw_environment(x,y)
clock.tick(30)
pygame.quit()
quit()
解决方案
图像有大小。图像可能会出现在右侧或底部的窗口之外。的原点blit
将图像的左上角放置到指定位置。
如果您希望图像以(x, y)为中心,则必须获取pygame.Rect
图像大小 ( get_rect
) 并将矩形的中心设置为指定位置(关键字参数)。使用矩形指定blit
操作的位置。
img_rect = targetpng.get_rect(center = (x, y))
game_display.blit(targetpng, img_rect)
图像具有大小,因此图像的随机位置必须在[image_size/2, window_sizw - image_size/2]范围内。
a 的宽度和高度pygame.Surface
可以通过get_width()
/get_height()
或获得get_size()
。例如:
img_size = targetpng.get_size()
x = random.randrange(img_size[0]//2, display_width - img_size[0]//2)
y = random.randrange(img_size[1]//2, display_height - img_size[1]//2)
推荐阅读
- sql - 考勤SQL查询
- xamarin.forms - Xamarin Forms AppShell - 子页面过早调用 OnAppearing
- java - 我无法通过 ViewPager 正确地将项目编号传递给片段
- android - React Native + Android 原生模块:HMRClient 不是注册的可调用模块
- vb.net - 数据网格视图仅在单元格中显示一个字母
- azure - 在管道中使用 Get Metadata 活动时,如何为 blob 存储中的任何文件/容器获取自定义元数据参数(键值)?
- android - 如何在 Flutter 中使用 chrome 自定义标签
- c# - Unity 3D 2019:x 位置不断变化
- javascript - Chartjs - destroy() 什么都不做
- javascript - 即使我添加 polyfill,获取对象也不支持属性或方法“条目”错误