2

这个脚本会随机生成一个跟随玩家的外星人,并且玩家可以很好地四处走动,但是我希望当外星人图像移动到玩家图像上时发生一些事情,例如玩家受到伤害。

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()
4

1 回答 1

0

您需要实现某种碰撞检测。最简单的方法是使用边界框来检查两个框是否相交。以下函数接受两个盒子对象,并根据它们是否碰撞返回真/假:

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

您可以在以下位置阅读有关此算法的更多信息: 基本 2D 碰撞检测

有关更多信息,请参阅:StackOverflow - 基本 2D 碰撞检测

于 2013-09-16T08:47:25.537 回答