Яблоко икры внутри змеи - PullRequest
1 голос
/ 14 апреля 2019

Я создаю игру и нашел то, что меня раздражает.Яблоко нерестится внутри змеия определил голову змеи (sh), которая является единственной функцией, которая взаимодействует с яблоком.Не другие части змеи.Итак, как сделать так, чтобы этого не произошло?

Я попытался использовать Pygame Snake - Apple, порождающуюся внутри змеи , и отредактировать ее, чтобы она работала.И я попытался сделать оператор 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 голосов
/ 14 апреля 2019

Область, которая покрыта яблоком, больше, чем часть змеи.
Вы должны использовать pygame.Rect.collidepoint(), чтобы проверить, находится ли змея в области яблока:

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

Змея состоит из головы и списка тела части.Если генерируется новая случайная позиция для яблока, то вы должны проверить, действительно ли яблоко не покрывает голову , а не any часть тела :

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...