如何在pygame中将图像附加到这些矩形?

时间:2019-04-21 07:55:14

标签: python python-3.x pygame

我有一个运行正常的游戏,例如frogger,但是目前只有矩形和正方形。我想知道是否有一种方法可以简单地用图像(而不是RGB颜色)将矩形“蒙皮”。

import random
import pygame
from pygame.locals import *

class Rectangle:

    def __init__(self, x, y, w, h):
        self.x = x
        self.y = y
        self.w = w
        self.h = h
class Frog(Rectangle):

    def __init__(self, x, y, w):
        super(Frog, self).__init__(x, y, w, w)
        self.x0 = x
        self.y0 = y
        self.color = (34, 177, 76)
        self.attached = None

    def reset(self):
        self.x = self.x0
        self.y = self.y0
        self.attach(None)

    def move(self, xdir, ydir):
        self.x += xdir * g_vars['grid']
        self.y += ydir * g_vars['grid']

    def attach(self, obstacle): 
        self.attached = obstacle

    def update(self):
        if self.attached is not None:
            self.x += self.attached.speed

        if self.x + self.w > g_vars['width']:
            self.x = g_vars['width'] - self.w

        if self.x < 0:
            self.x = 0
        if self.y + self.h > g_vars['width']:
            self.y = g_vars['width'] - self.w
        if self.y < 0:
            self.y = 0

    def draw(self):
        rect = Rect( [self.x, self.y], [self.w, self.h] )
        pygame.draw.rect( g_vars['window'], self.color, rect )

1 个答案:

答案 0 :(得分:0)

忘记矩形。您不会“蒙皮”矩形。您可以加载图像并直接在屏幕上绘制(变白)。

import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
# Add node A pointing back to itself
G.add_edges_from([('A','A')])
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edges(G, pos, arrows=True)
plt.show()

如果您使用pygame.sprite.Sprite,那么您甚至可以跳过class Frog: def __init__(self, x, y, filename): self.image = pygame.image.load(filename) self.rect = self.sprite.get_rect() self.rect.x = x self.rect.y = y #self.rect.w = w # no need it - rect will use image's width #self.rect.h = h # no need it - rect will use image's height def draw(self, screen): screen.blit(self.image, self.rect) ,因为它已经有了

def draw()

现在您使用class Frog(pygame.sprite.Sprite): def __init__(self, x, y, filename): self.image = pygame.image.load(filename) self.rect = self.sprite.get_rect() self.rect.x = x self.rect.y = y #self.rect.w = w # no need it - rect will use image's width #self.rect.h = h # no need it - rect will use image's height #def draw(self, screen): # screen.blit(self.image, self.rect) # Sprite already has this method self.rect.x而不是self.rect.yself.x,因为其他一些功能使用self.y来检查冲突(pygame.sprite.collide_rect())或绘制(pygame.sprite.Group)组中的所有子画面。

通过self.rect,您还可以将self.rect分配到图像中心

x, y

它将计算 self.rect.centerx = x self.rect.centery = y self.rect.x

文档:pygame.image.load()pygame.sprite.Spritepygame.sprite.collide_rect()pygame.sprite.Group