python - pygame 将图像放置在屏幕上的问题

标签 python image pygame position coordinates

我正在做一门书籍类(class),我必须在左上角放置一张外星飞船的图像。我按照指导使用了相同的代码,但我的图像放置得太低。我无法弄清楚问题的根源是什么,我使用的是透明 png 图像。这是我的 Alien 、设置和主类的代码。非常感谢您的帮助。

外星人等级:

import pygame
from pygame.sprite import Sprite

class Alien(Sprite):
    """A class to represent a single alien in the fleet."""
    def __init__(self, ai_settings, screen):
        """Initialize the alien and set its starting position."""
        super(Alien, self).__init__()
        self.screen = screen
        self.ai_settings = ai_settings

        # Load the alien image and set its rect attribute.
        self.image = pygame.image.load('Images/alien.png')
        self.rect = self.image.get_rect()

        # Start each new alien near the top left of the screen.
        self.rect.x = self.rect.width
        self.rect.y = self.rect.height

        # Store the alien's exact position.
        self.x = float(self.rect.x)

    def blitme(self):
        """Draw the alien at its current location."""
        self.screen.blit(self.image, self.rect)

设置类:

class Settings():

    """A class to store all settings for Alien Invasion."""
    def __init__(self):
        """Initialize the game's settings."""
        # Screen settings
        self.screen_width = 1200
        self.screen_height = 800
        self.bg_color = (230, 230, 230)
        #Ship setting
        self.ship_speed_factor = 1.5

        # Bullet settings
        self.bullet_speed_factor =1
        self.bullet_width = 3
        self.bullet_height = 15
        self.bullet_color = 60 ,60, 60
        self.bullets_allowed = 3

主类:

from settings import Settings
import pygame
from ship import Ship
from alien import Alien
from pygame.sprite import Group

import game_functions as gf



def run_game():
    # Initialize game and create a screen object.
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")
    # Make a ship
    ship = Ship( ai_settings, screen)
    # Make a group to store bullets in.
    bullets = Group()
    # Make an alien.
    alien = Alien(ai_settings, screen)
    # Start the main loop for the game.
    while True:
        gf.check_events(ai_settings, screen, ship, bullets)
        ship.update()
        # Get rid of bullets that have disappeared.
        gf.update_bullets(bullets)
        gf.update_screen(ai_settings, screen, ship, alien, bullets)


run_game()

最佳答案

要设置Alien Sprite 在左上角的坐标,您应该使用:

self.rect.x = 0
self.rect.y = 0

关于python - pygame 将图像放置在屏幕上的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46879491/

相关文章:

Treebank 的 Python 数据结构?

python - 如何使用 Python 通过 HTTP 发送文件?

python - 将元素列表分配到具有不同排除项的 3 个列表中

python - Django:让管理员获取图像文件,但将其存储为 base64 字符串

java - View 太大,无法放入绘图缓存

python - 如何阻止调用打印?

python - Sprite 不工作/不显示(Python/Pygame)

python - 如何在一个窗口中获取多个面板 - GTK+

css - 默认模糊图像,悬停时显示?

python - Pygame 按下按键时移动物体