我已经编写了一个代码而我正试图让我的图像显示在中心,但是当我运行它时,图像根本没有出现,我出错的地方有任何想法吗?
(顺便说一句,我测试了不同的代码,图像加载得很好,所以python或pygame本身没有任何问题)
from __future__ import division
import math
import sys
import pygame
class MyGame(object):
def __init__(self):
pygame.mixer.init()
pygame.mixer.pre_init(44100, -16, 2, 2048)
pygame.init()
self.width = 800
self.height = 600
self.screen = pygame.display.set_mode((self.width, self.height))
self.bg_color = 0, 0, 0
self.alien_img = pygame.image.load('alien.png')
self.alien_pos = ((self.width-rect.width)//4,
(self.height-rect.height)//4)
self.FPS = 30
self.REFRESH = pygame.USEREVENT+1
pygame.time.set_timer(self.REFRESH, 1000//self.FPS)
def run(self):
running = True
while running:
event = pygame.event.wait()
if event.type == pygame.QUIT:
running = False
elif event.type == self.REFRESH:
self.draw()
else:
pass # an event type we don't handle
def draw(self):
self.screen.fill(self.bg_color)
rect = self.alien_img.get_rect()
rect = rect.move(self.alien_pos)
self.screen.blit(self.alien_img, rect)
pygame.display.flip()
MyGame().run()
pygame.quit()
sys.exit()
答案 0 :(得分:1)
你需要搬家:
rect = self.alien_img.get_rect()
到以下行之前的init:
self.alien_pos = ((self.width-rect.width)//4,
(self.height-rect.height)//4)
之后:
self.alien_img = pygame.image.load('alien.png')
以下是您的代码,其中包含将图片放入框架中的更改:
from __future__ import division
import math
import sys
import pygame
class MyGame(object):
def __init__(self):
pygame.mixer.init()
pygame.mixer.pre_init(44100, -16, 2, 2048)
pygame.init()
self.width = 800
self.height = 600
self.screen = pygame.display.set_mode((self.width, self.height))
self.bg_color = 0, 0, 0
self.alien_img = pygame.image.load('alien.png')
rect = self.alien_img.get_rect()
self.alien_pos = ((self.width-rect.width)//4,
(self.height-rect.height)//4)
self.FPS = 30
self.REFRESH = pygame.USEREVENT+1
pygame.time.set_timer(self.REFRESH, 1000//self.FPS)
def run(self):
running = True
while running:
event = pygame.event.wait()
if event.type == pygame.QUIT:
running = False
elif event.type == self.REFRESH:
self.draw()
else:
pass # an event type we don't handle
def draw(self):
self.screen.fill(self.bg_color)
rect = self.alien_img.get_rect()
rect = rect.move(self.alien_pos)
self.screen.blit(self.alien_img, rect)
pygame.display.flip()
MyGame().run()
pygame.quit()
sys.exit()
在您定义之前尝试访问rect之前。我添加了下面创建的窗口的图片:
会指出你计划将这张照片放在中间位置并不是你需要做的改变:
self.alien_pos = ((self.width-rect.width)//4,
(self.height-rect.height)//4)
要:
self.alien_pos = (self.width//2 - rect.width//2,
self.height//2 - rect.height//2)
这给出了所需的结果: