質問

this script spawns a random alien that follows the player and the player wak around fine, but i want something to happen when the aliens image moves over the players image e.g the player takes damage.

import pygame, sys, random, time, math, funt
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()

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 = -1.5
        elif event.key == K_s:
            movey = +1.5
        elif event.key == K_a:
            movex = -1.5
        elif event.key == K_d:
            movex = +1.5

    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)
    if chpos == alpos:
        pygame.quit()
        sys.exit()




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

    pygame.display.update()
役に立ちましたか?

解決

You need to implement some kind of collision detection. The simplest way to do this is to use bounding boxes to check if two boxes intersects. The following function takes two box objects, and returns true/false based on if they collide or not:

def collides(box1, box2):
    return !((box1.bottom < box2.top) or
        (box1.top > box2.bottom) or
        (box1.left > box2.right) or
        (box1.right < box2.left))


class Box(top, bottom, left, right):
   def __init__(self, top, bottom, left, right):
       self.top = top
       self.bottom = bottom
       self.left = left
       self.right = right

You can read more about this algorithm at: Basic 2D Collision Detection.

For more info see: StackOverflow - Basic 2D Collision Detection.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top