这个脚本会产生一个跟随玩家的随机外星人并且玩家可以很好地吵醒,但是当外星人的图像移动到玩家图像上时,我想要发生一些事情,例如玩家受到伤害。
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()
答案 0 :(得分:0)
您需要实现某种碰撞检测。 最简单的方法是使用边界框来检查两个框是否相交。 以下函数接受两个box对象,并根据它们是否发生冲突返回true / false:
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
您可以在以下位置详细了解此算法: Basic 2D Collision Detection
有关详细信息,请参阅:StackOverflow - Basic 2D Collision Detection。