蛇穿过障碍

时间:2019-04-13 17:55:26

标签: python pygame

我正在做一个游戏,但是当它玩几次时,当它穿过障碍物时,向右按就可以穿过墙壁。我的代码有什么问题?我正在使用python 2.7。

我尝试放入许多代码,例如x> displaywidth + 10。我尝试制作不同的副本。但是蛇仍然穿过。

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

white = (255,255,255)
grey = (128,128,128)
black = (0,0,0)
red = (255,0,0)
orange = (255,128,0)
yellow = (255,255,0)
green = (0,255,0)
Lgreen = (128,255,0)
Dgreen = (0,128,0)
blue = (0,0,255)
Lblue = (0,255,255)
purple = (255,0,255)
Dpurple = (128,0,128)
pink = (255,0,127)
black = (0,0,0)
pygame.display.set_caption('Snake Universe')
icon = pygame.image.load('Graphics/icon.png')
pygame.display.set_icon(icon)
dw = 1280
dh = 720 
at = 40
bs = 20
screen = pygame.display.set_mode((dw, dh))
clock = pygame.time.Clock()
def removedata(path):
    shutil.rmtree(path)
    time.sleep(0.01)
    inst(os.environ['APPDATA']+str('/Snake Universe'))
def save(path, var):
    with open(path, "wb") as f:
        pickle.dump(var, f)
def inst():
    if not os.path.exists((os.environ['APPDATA']+str('/Snake Universe'))):
        os.mkdir(os.environ['APPDATA']+str('/Snake Universe'))
    time.sleep(0.01)
    if not os.path.exists((os.environ['APPDATA']+str('/Snake Universe/h.SNUN'))):
        save(os.environ['APPDATA']+str('/Snake Universe/h.SNUN'), 0)
inst()
time.sleep(0.01)

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)

def score(score):
    text = pygame.font.Font('Fonts/Kuiper_Belt.otf', 25).render("Score: "+str(score), True, black)
    screen.blit(text, [0,0])

def highscore(highscore):
    text = pygame.font.Font('Fonts/Kuiper_Belt.otf', 25).render("Highscore: "+str(highscore), True, black)
    screen.blit(text, [1100,0])

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 text_objects(text,color,fontS):
    font = pygame.font.Font('Fonts/Kuiper_Belt.otf', fontS)
    textSurface = font.render(text, True, color)
    return textSurface, textSurface.get_rect()

def mts(msg,color, y_displace=0, fs=35):
    textSurf, textRect = text_objects(msg,color,fs)
    textRect.center = (dw / 2), (dh / 2)+y_displace
    screen.blit(textSurf, textRect)

#def option():
    #optionExit = False
    #volume = 1
    #screen.fill(Dpurple)
    #while not optionExit:
        #textSurf, textRect = text_objects(str(volume),white,35)
        #textRect.center = (dw / 2), (dh / 2)+0
        #screen.blit(textSurf, textRect)
        #pygame.display.update()
        #clock.tick(60)
        #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_UP and volume < 1 and volume != 0:
                    #volume = volume + 0.1
                    #textSurf, textRect = text_objects(str(volume),white,35)
                    #textRect.center = (dw / 2), (dh / 2)+0
                    #screen.blit(textSurf, textRect)
                #if event.key == pygame.K_DOWN and volume > 0 and volume != 1:
                    #volume = volume - 0.1
                    #textSurf, textRect = text_objects(str(volume),white,35)
                    #textRect.center = (dw / 2), (dh / 2)+0
                    #screen.blit(textSurf, textRect)
                #if event.key == pygame.K_ESCAPE:
                    #menu(volume)

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)

        # the barrier
        if lead_x > dw or lead_x < 0 or lead_y > dh or lead_y < 0:
            gameOver = True

        lead_x += lead_x_change
        lead_y += lead_y_change

        screen.fill(white)

        #at = 40
        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()

        if lead_x > randAppleX and lead_x < randAppleX + at or lead_x + bs > randAppleX and lead_x + bs < randAppleX + at:
            #print("x crossover")
            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
            #elif apple.colliderect():
                #randAppleX,randAppleY = randAppleGen()


        clock.tick(Speed)

    pygame.quit()
    quit()
def menu(volume):
    stream = 'Video/bg.avi'

    cap = cv2.VideoCapture(stream)

    ret, img = cap.read()
    if not ret:
        print("Can't read stream")

    img = cv2.transpose(img)
    surface = pygame.surface.Surface((1280, 720))

    def fade(width, height): 
        fade = pygame.Surface((width, height))
        fade.fill((0,0,0))
        for alpha in range(0, 300):
            fade.set_alpha(alpha)
            screen.blit(fade, (0,0))
            pygame.display.update()
            pygame.time.delay(1)

    pygame.mixer.music.load(os.path.join(os.getcwd(), 'Sounds', 'intro.ogg'))
    pygame.mixer.music.set_volume(volume)
    pygame.mixer.music.play(-1) 

    enter_sfx = pygame.mixer.Sound('Sounds/select.wav')
    move_sfx = pygame.mixer.Sound('Sounds/menu_move.ogg')

    Title = pygame.image.load('Graphics/Title.png')
    Play = pygame.image.load('Graphics/Play.png')
    Option = pygame.image.load('Graphics/Option.png')
    Exit = pygame.image.load('Graphics/Exit.png')
    LinePX = pygame.image.load('Graphics/LinePX.png')
    LineO = pygame.image.load('Graphics/LineO.png')

    screen.set_alpha(0)
    blacki = pygame.image.load('Graphics/black.png')

    y = 384
    y1 = 3000

    xb = 10000
    yb = 10000


    playing = True
    while playing:
        for event in pygame.event.get():
            if event.type == pygame.KEYDOWN:
                if event.key==pygame.K_KP_ENTER or event.key==pygame.K_RETURN:
                    #pygame.mixer.Channel(2).play(enter_sfx)
                    pygame.mixer.music.stop()
                    #pygame.mixer.Channel(2).set_volume(1)
                    y += 1
                    #fade(1280, 720)
                    #xb = 0
                    #yb = 0
                    if y == 285:
                        playing = False
                        gameLoop()
                    #if y == 3236:
                        #menu(1)
                    if y == 385:
                        playing = False
                        pygame.quit()
                        sys.exit()
                if event.key == pygame.K_UP:
                    pygame.mixer.Channel(3).play(move_sfx)
                    pygame.mixer.Channel(3).set_volume(volume)
                    y += 1
                    #if y == 3236:
                        #y = 235
                        #y1 = 3000
                    #if y == 236:
                        #y = 435
                        #y1 = 3000
                    #if y == 436:
                        #y = 235
                        #y1 =335
                        #y = 3235
                    if y == 285:
                        y = 384
                    if y == 385:
                        y = 284


                if event.key == pygame.K_DOWN:
                    pygame.mixer.Channel(4).play(move_sfx)
                    pygame.mixer.Channel(4).set_volume(volume)
                    y += 1
                    #if y == 236:
                        #y = 3235
                        #y = 435
                        #y1 = 335
                    #if y == 3236:
                        #y1 = 3000
                        #y = 435
                    #if y == 436:
                        #y1 = 3000
                        #y = 235
                    if y == 285:
                        y = 384
                    if y == 385:
                        y = 284
                if event.key == pygame.K_TAB:
                    removedata(os.environ['APPDATA']+str('/Snake Universe'))
            if event.type == pygame.QUIT:
                playing = False
                pygame.quit()
                sys.exit() 

        ret, img = cap.read()
        if not ret:
            cap = cv2.VideoCapture(stream)
            ret, img = cap.read()

        img = cv2.transpose(img)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        pygame.surfarray.blit_array(surface, img)
        screen.blit(surface, (0,0))
        screen.blit(Title, (360, 0))
        #screen.blit(Play, (460, 250))
        #screen.blit(Exit, (460, 450))
        screen.blit(Play, (460, 300))
        screen.blit(Exit, (460, 400))
        screen.blit(LinePX, (482.5, y))
        screen.blit(LineO, (482.5, y1))
        #screen.blit(Option, (460, 350))
        screen.blit(blacki, (xb, yb))
        pygame.display.update()
        clock.tick(60)
menu(1)

我希望屏幕上显示游戏的输出,但实际输出是通过的蛇。

1 个答案:

答案 0 :(得分:0)

lead_x >= dwlead_y >= dh而不是lead_x > dw lead_y > dh时,蛇超出范围。
绑定检查必须为:

if lead_x >= dw or lead_x < 0 or lead_y >= dh or lead_y < 0:
    gameOver = True 

但是我建议改用pygame.Rect.contains.contains()验证一个矩形是否完全在另一个矩形内:

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