converting an image to a rect

2019-06-11 03:51发布

问题:

this script spawns a alien that follows the player, i just want to know how to make the alien (nPc) and the player (mouse_c) a rect so i make the alien kill the player when the imagers overlap. any help would really help

thanks

import pygame, sys, random, time, math
from pygame.locals import *
pygame.init()

bifl = 'screeing.jpg'
milf = 'character.png'
alien = 'alien_1.png'

screen = pygame.display.set_mode((640, 480))
background = pygame.image.load(bifl).convert()
mouse_c = pygame.image.load(milf).convert_alpha()
nPc = pygame.image.load(alien).convert_alpha()


mouse_c = pygame.Rect((10, 10))
nPc = pygame.Rect((10, 10))

x, y = 0, 0
movex, movey = 0, 0

z, w = random.randint(10, 480), random.randint(10, 640)
movez, movew = 0, 0

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    if event.type == KEYDOWN:
        if event.key == K_w:
            movey = -4
        elif event.key == K_s:
            movey = +4
        elif event.key == K_a:
            movex = -4
        elif event.key == K_d:
            movex = +4

    if event.type == KEYUP:
        if event.key == K_w:
            movey = 0
        elif event.key == K_s:
            movey = 0
        elif event.key == K_a:
            movex = 0
        elif event.key == K_d:
            movex = 0



    if w < x:
        movew =+ 0.4
    if w > x:
        movew =- 0.4
    if z < y:
        movez =+ 0.4
    if z > y:
        movez =- 0.4

    x += movex
    y += movey
    w += movew
    z += movez



    print('charecter pos: ' + str(x) + str(y))
    print('alien pos: ' + str(w) + str(z))
    chpos = x + y
    alpos = w + z
    print(alpos, chpos)


    screen.blit(background, (0, 0))
    screen.blit(mouse_c, (x, y))
    screen.blit(nPc, (w, z))

    pygame.display.update()

回答1:

You could use Pygame Sprites

mouse_c = pygame.sprite.Sprite()
mouse_c.image = pygame.image.load(milf).convert_alpha()
mouse_c.rect = mouse_c.image.get_rect()
mouse_c.rect.move_ip(10,10)

nPc = pygame.sprite.Sprite()
nPc.image = pygame.image.load(milf).convert_alpha()
nPc.rect = nPc.image.get_rect()
nPc.rect.move_ip(10,10)

Then blit:

screen.blit(mouse_c.image, mouse_c.rect.topleft)
screen.blit(nPc.image, nPc.rect.topleft)