python-3.x - Python/Pygame - 获取一个正方形以通过类改变颜色

标签 python-3.x pygame

我正在为战舰游戏制作一个小项目,但是当我单击对象时,我在让代码理解时遇到了一些麻烦,我希望它改变颜色。

到目前为止我有这个类(class):

class Tile:
def __init__(self, xstart, ystart, game_display, colour):
    self.tile = pygame.Rect(xstart, ystart, 50, 50)
    pygame.draw.rect(game_display, colour,  self.tile, 1)
    print(self.tile)

def ChangeColour(self, game_display, colour):
    pygame.draw.rect(game_display, colour,  self.tile, 0)

我使用我制作的这个函数创建了板:

def new_board():
global board
xstart = 70
ystart = 50
#pygame.draw.rect(game_display, BLACK, (70, 50, 500, 500), 3)
for square in range(PLAYER_NUMBER_SQUARES):
    board.append(Tile(xstart, ystart, game_display, BLACK))
    xstart += 50
    if xstart == 570:
        ystart += 50
        xstart = 70
return board

到目前为止,我已将正方形/矩形对象添加到列表“板”中,当玩家单击时,我获取像素并使用此方法来获取已单击的正方形:

def get_x_number(x):
index = None
if x >= 70 and x < 120:
    index = 70
if x >= 120 and x < 170:
    index = 120
if x >= 170 and x < 220:
    index = 170
if x >= 220 and x < 270:
    index = 220
if x >= 270 and x < 320:
    index = 270
if x >= 320 and x < 370:
    index = 320
if x >= 370 and x < 420:
    index = 370
if x >= 420 and x < 470:
    index = 420
if x >= 470 and x < 520:
    index = 470
return index

def get_y_number(y):
index = None
if y >= 50 and y < 100:
    index = 70
if y >= 100 and y < 150:
    index = 120
if y >= 150 and y < 200:
    index = 170
if y >= 200 and y < 250:
    index = 220
if y >= 250 and y < 300:
    index = 270
if y >= 300 and y < 350:
    index = 320
if y >= 350 and y < 400:
    index = 370
if y >= 400 and y < 450:
    index = 420
if y >= 450 and y < 500:
    index = 470
return index

(我知道这是一个稍微冗长的方法,但如果有更好的方法,请告诉我,尝试了循环,无法让它工作。)

最后,我到达了它将获得单击的方 block 的位置,但是它不会更改方 block ,这是因为当我从列表中索引方 block 时,它会返回:<__main__.Tile object at 0x068A5590>

如何让它返回 pygame.Rect 而不是这个?我查看了类(class),尝试过__repr____str__并没有什么喜悦,如果有人能帮助我,那就太好了!

谢谢!

最佳答案

我建议将您的 Tile 类设置为 pygame.sprite.Sprite子类,然后将所有图 block 添加到 sprite group 。这允许您通过调用 sprite_group.update()sprite_group.draw(screen) 来更新和绘制所有 Sprite 。 Pygame sprites 需要一个 image (必须是一个 pygame.Surface 实例)和一个 rect 属性。

要检查碰撞,您可以首先迭代 sprite 组中的 sprite,然后使用 sprite 的 rectcollidepoint 方法来查看它是否与鼠标发生碰撞位置,例如sprite.rect.collidepoint(event.pos)pygame.mouse.get_pos()。如果它与鼠标发生碰撞,请调用 change_color 方法并用新颜色填充 Sprite 的图像(或者您也可以替换图像)。

import pygame as pg


GREEN = pg.Color(0, 200, 90)
BLUE = pg.Color(0, 90, 200)


class Tile(pg.sprite.Sprite):

    def __init__(self, position):
        super().__init__()
        self.image = pg.Surface((50, 50))
        self.color = GREEN
        self.image.fill(self.color)
        self.rect = self.image.get_rect(topleft=position)

    def change_color(self, color):
        self.color = color
        self.image.fill(self.color)


def main():
    screen = pg.display.set_mode((800, 600))
    clock = pg.time.Clock()
    all_sprites = pg.sprite.Group()
    # Create the tiles and add them to the all_sprites group.
    for y in range(10):
        for x in range(12):
            all_sprites.add(Tile((x*51, y*51)))

    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            # If a mouse button was pressed.
            elif event.type == pg.MOUSEBUTTONDOWN:
                # Iterate over the sprites in the group.
                for sprite in all_sprites:
                    # Check if the sprite's rect collides with the mouse pos.
                    if sprite.rect.collidepoint(event.pos):
                        # Finally change the color.
                        sprite.change_color(BLUE)

        all_sprites.update()
        screen.fill((30, 30, 30))
        all_sprites.draw(screen)

        pg.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()

关于python-3.x - Python/Pygame - 获取一个正方形以通过类改变颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47443008/

相关文章:

python-3.x - Pandas groupby,如何对多列进行多重聚合?

python - 在python中创建一个按钮

android - Python、Kivy 和 Android 游戏

python - pygame,如何在调整窗口大小时更新窗口大小

python-3.x - Adafruit 树莓派 neopixel 库抛出错误 "ImportError: No module named _rpi_ws281x"

Python - 同时运行代码(TTS 和打印功能)

python3.6 : equivalent of %d %s using the format: f("string {var1} {var2})

python - Dash(Python) - dash-daq 仪表中的较厚环

python - 图像未显示在 pygame 屏幕上

python - pygame.camera 不工作?