当外星人移动到玩家身上时让他承受伤害

2024-04-26 22:56:32 发布

您现在位置:Python中文网/ 问答频道 /正文

这个脚本会产生一个随机的外星人,它跟随玩家,玩家可以随意移动,但是我希望当外星人图像移动到玩家图像上时会发生一些事情,比如玩家受到伤害。你知道吗

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

Tags: keyeventifsys玩家randomscreenpygame
1条回答
网友
1楼 · 发布于 2024-04-26 22:56:32

你需要实现某种碰撞检测。 最简单的方法是使用边界框来检查两个框是否相交。 以下函数获取两个长方体对象,并根据它们是否碰撞返回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。你知道吗

相关问题 更多 >