苹果在蛇里面产卵

时间:2019-04-13 22:46:09

标签: python pygame

我在做游戏,我发现一些让我烦恼的东西。苹果在蛇里面产卵。我定义了蛇头(sh),这是与苹果互动的唯一功能。不是蛇的其他部分。那么,您如何避免这种情况发生?

我尝试使用Pygame Snake - Apple spawning inside snake并对其进行编辑以使其正常运行。而且我尝试在pygame矩形碰撞代码上做出if语句。

import pygame
import os
import sys
pygame.mixer.pre_init()
pygame.mixer.init(44100, 16, 2, 262144)
pygame.init()
from pygame.locals import*
import cv2
import time
import random
import pickle
import shutil
import OpenGL

dw = 1280
dh = 720 
at = 40
bs = 20
screen = pygame.display.set_mode((dw, dh))
clock = pygame.time.Clock()
def pause():

    paused = True

    while paused:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    paused = False
                elif event.key == pygame.K_SPACE:
                    menu(1)
        screen.fill(white)
        mts("Paused", black, -100, 100)
        mts("Press esc to go back to the game or press space to go back to the menu", black, 25, 45)
        pygame.display.update()
        clock.tick(60)

#define the apple to spawn in a random place
def randAppleGen():
    randAppleX = random.randrange(0, dw-at, bs)
    randAppleY = random.randrange(0, dh-at, bs)

    return randAppleX,randAppleY

def snake(bs, sl):
    for XnY in sl:
        pygame.draw.rect(screen, Dgreen, [XnY[0],XnY[1],bs,bs])

def gameLoop():
    global at
    global bs
    hs = pickle.load( open( os.getenv('APPDATA')+str('/Snake Universe/h.SNUN'), "rb" ) )
    gameExit = False
    gameOver = False
    gameHack = False
    Speed = 20
    lead_x = dw/2
    lead_y = dh/2

    lead_x_change = 0
    lead_y_change = 0
    pygame.mixer.music.load(os.path.join(os.getcwd(), 'Sounds', 'music1.ogg'))
    pygame.mixer.music.play(-1) 

    slist = []
    sl = 0
    if sl > 2304:
        gameHack = True

    randAppleX,randAppleY = randAppleGen()

    while not gameExit:

        while gameOver == True:
            screen.fill(white)
            mts("Game over", red, -50,100)
            mts("Press enter to play again or press space to go back to the menu", black, 50,50)
            pygame.display.update()
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    gameOver = False
                    gameExit = True
                    pygame.quit()
                    sys.exit()
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_KP_ENTER or event.key==pygame.K_RETURN:
                        gameLoop()
                    if event.key == pygame.K_SPACE:
                        gameExit = False
                        gameOver = False
                        menu(1)
        while gameHack == True:
            pygame.mixer.music.stop()
            screen.fill(white)
            mts("Hacked", red, -50,100)
            mts("You hacked or exploit the game, press enter to quit the game", black, 50,50)
            pygame.display.update()
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    gameOver = False
                    gameExit = True
                    pygame.quit()
                    sys.exit()
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_KP_ENTER or event.key==pygame.K_RETURN:
                        pygame.quit()
                        sys.exit()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                gameExit = True
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT and lead_x_change != bs:
                    lead_x_change = -bs
                    lead_y_change = 0
                elif event.key == pygame.K_RIGHT and lead_x_change != -bs:
                    lead_x_change = bs
                    lead_y_change = 0
                elif event.key == pygame.K_UP and lead_y_change != bs:
                    lead_y_change = -bs
                    lead_x_change = 0
                elif event.key == pygame.K_DOWN and lead_y_change != -bs:
                    lead_y_change = bs
                    lead_x_change = 0
                elif event.key == pygame.K_ESCAPE:
                    pause()
                elif event.key == pygame.K_s and Speed >= 10 and Speed < 60:
                    Speed += 10
                    clock.tick(Speed)
                elif event.key == pygame.K_d and Speed <= 60 and Speed > 10:
                    Speed -= 10
                    clock.tick(Speed)

        if not pygame.Rect(0, 0, dw, dh).contains(lead_x, lead_y, bs, bs):
            gameOver = True

        lead_x += lead_x_change
        lead_y += lead_y_change

        screen.fill(white)

        #draw the apple
        apple = pygame.draw.rect(screen, red, [randAppleX,randAppleY,at,at])

        sh = []
        sh.append(lead_x)
        sh.append(lead_y)
        slist.append(sh)
        snake(bs, slist)

        if len(slist) > sl:
            del slist[0]

        for eachSegment in slist[:-1]:
            if eachSegment == sh:
                gameOver = True

        score(sl)
        highscore(hs)

        if sl > hs:
            hs += 1
            os.remove( os.getenv('APPDATA')+str('/Snake Universe/h.SNUN') )
            pickle.dump( sl, open( os.getenv('APPDATA')+str('/Snake Universe/h.SNUN'), "wb" ) )
            hs = pickle.load( open( os.getenv('APPDATA')+str('/Snake Universe/h.SNUN'), "rb" ) )


        pygame.display.update()

        #make the apple spawn
        if lead_x > randAppleX and lead_x < randAppleX + at or lead_x + bs > randAppleX and lead_x + bs < randAppleX + at:
            if lead_y > randAppleY and lead_y < randAppleY + at:
                randAppleX,randAppleY = randAppleGen()
                sl += 1
            elif lead_y + bs > randAppleY and lead_y + bs < randAppleY + at:
                randAppleX,randAppleY = randAppleGen()
                sl += 1


        clock.tick(Speed)

    pygame.quit()
    quit()

我希望它不会在蛇中产卵,但是确实如此。

1 个答案:

答案 0 :(得分:0)

被苹果覆盖的区域大于蛇的一部分。
您必须使用pygame.Rect.collidepoint()验证蛇是否在苹果附近:

appleRect = pygame.Rect(randAppleX, randAppleY, at, at)
if appleRect.collidepoint(lead_x, lead_y):
    # [...]

蛇由头部 身体部分的列表组成。如果为苹果生成了一个新的随机位置,那么您必须验证苹果是否遮盖了 而不是 { 3}}部分

if not appleRect.collidepoint(lead_x, lead_y) and \
   not any(appleRect.collidepoint(*p) for p in slist):
    # [...]

生成新苹果的代码可能如下所示:

appleRect = pygame.Rect(randAppleX, randAppleY, at, at)
if appleRect.collidepoint(lead_x, lead_y):
    while True:
        randAppleX, randAppleY = randAppleGen()
        appleRect = pygame.Rect(randAppleX, randAppleY, at, at)
        if not appleRect.collidepoint(lead_x, lead_y) and \
           not any(appleRect.collidepoint(*p) for p in slist):
            break
    sl += 1