pygame对象碰撞

时间:2018-08-29 00:00:25

标签: python

当另一个物体与另一个物体完全在同一位置时,我试图退出游戏。 我写了一段代码,说如果坐标x ==坐标y然后用白色填充屏幕,只是描绘了一条消息然后退出,但是我遇到了两个错误: 一个是文本屏幕的闪电位置不是有效位置,另一个是当坐标相同时什么也没有发生,为什么? 这是代码:

import pygame
import time
from random import randint

pygame.init()

white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
width = 800
height = 600
FPS = 100
color = black
font = pygame.font.SysFont(None, 25)

gameDisplay = pygame.display.set_mode((width, height))
pygame.display.set_caption("Second snake game.")
clock = pygame.time.Clock()

def gameloop():

    yellow = (255, 255, 0)
    white = (255, 255, 255)
    black = (0, 0, 0)
    red = (255, 0, 0)
    width = 800
    height = 600
    FPS = 100
    color = black
    color2 = yellow
    exitGame = False
    lead_x = width/2
    lead_y = height/2
    lead_x2 = randint(0, 800)
    lead_y2 = randint(0, 600)
    lead_x_change = 0
    lead_y_change = 0
    block_size = 10
    velocity = 0.2


    while not exitGame:
        gameDisplay.fill(white)
        pygame.draw.rect(gameDisplay, color, [lead_x, lead_y, block_size, block_size])
        pygame.draw.rect(gameDisplay, color2, [lead_x2, lead_y2, block_size, block_size])
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exitGame = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_w:
                    lead_y_change += -velocity
                    lead_x_change = 0
                if event.key == pygame.K_s:
                    lead_y_change += velocity
                    lead_x_change = 0
                if event.key == pygame.K_a:
                    lead_x_change += -velocity
                    lead_y_change = 0
                if event.key == pygame.K_d:
                    lead_x_change += velocity
                    lead_y_change = 0
                if event.key == pygame.K_SPACE:
                   color = red
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_a or event.key == pygame.K_d:
                    lead_x_change = 0
                if event.key == pygame.K_w or event.key == pygame.K_s:
                    lead_y_change = 0


        lead_x += lead_x_change
        lead_y += lead_y_change
        if lead_x == lead_x2 and lead_y == lead_y2:
            gameDisplay.fill(white)
            message_to_screen("You win", red)
            exitGame = True

        if lead_x > width or lead_x < 0 or lead_y > height or lead_y < 0:
            myfont = pygame.font.SysFont('Comic Sans MS', 25)
            textsurface = myfont.render('You loose', False, (red))
            gameDisplay.blit(textsurface, width/2, height/2)
            time.sleep(2)
            exitGame = True
            pygame.quit()
            quit()

        pygame.display.update()

clock.tick(FPS)
gameloop()

0 个答案:

没有答案