游戏蛇系列的Pygame教程(十三)--娱乐版Wormy贪吃蛇(半成品有バグ)

10925 ワード

前のチュートリアル編「蛇遊びシリーズのPygameチュートリアル(十一)--Wormy蛇食い」を参考にしてください.
以前ネット上で1つの動図を見たことがあって、とても面白くて、蛇を貪って自分でりんごを食べて、それから全画面をいっぱい占めて、感じは確かにとてもクールで、私达のこのバージョンも蛇を貪って自動的に食べ物を探すことができるかどうかと思っています.
  • 時間の関係でまだバグがあるので、ヘビを貪ると自分を囲みやすく、出られなくなります.

  • 実装も比較的簡単で、ゲームのメインサイクルで毎回最高のbest_を生成します.moveは、元のプログラムのユーザーの入力に代わっていますが、肝心なのはこのbest_です.moveの生成は、まだ研究されています.私が採用したのは簡単で乱暴な方法です.すべての格子を検索し、その格子からアップルの格子までの距離(重み値)を計算します.
    res=abs(i-a_x)+abs(j-a_y)
    

    そしてヘビの頭の上下左右の4つの四角い格子の重み値を取得し、その中で最も小さいものをbest_として選択する.move.
    バグがあって、各位の大神は思う存分修正することができて、直して私に教えて、膜拝します!
    GitHub:https://github.com/ckdroid/PygameLearning
    コードは次のとおりです.
    # -*- coding: UTF-8 -*-
    '''
    Created on 2017 1 7 
    
    @author:    
    '''
    
    import random, sys, time, pygame
    from pygame.locals import *
    
    FPS = 10 #      (            )
    WINDOWWIDTH = 400 #     
    WINDOWHEIGHT = 300 #     
    CELLSIZE = 20 #       
    
    #   ,                
    assert WINDOWWIDTH % CELLSIZE == 0, "Window width must be a multiple of cell size."
    assert WINDOWHEIGHT % CELLSIZE == 0, "Window height must be a multiple of cell size."
    
    #          
    CELLWIDTH = int(WINDOWWIDTH / CELLSIZE)
    CELLHEIGHT = int(WINDOWHEIGHT / CELLSIZE)
    
    
    FIELD_SIZE = CELLHEIGHT * CELLWIDTH
    
    #          
    # R G B
    WHITE = (255, 255, 255)
    BLACK = ( 0, 0, 0)
    RED = (255, 0, 0)
    GREEN = ( 0, 255, 0)
    DARKGREEN = ( 0, 155, 0)
    DARKGRAY = ( 40, 40, 40)
    BGCOLOR = BLACK
    
    #         
    UP = 'up'
    DOWN = 'down'
    LEFT = 'left'
    RIGHT = 'right'
    
    #    
    ERR = -1111
    
    #      ()
    HEAD = 0 # syntactic sugar: index of the worm's head
    
    
    #       
    mov = [LEFT, RIGHT, UP, DOWN]
    
    board = [[0 for x in range(CELLWIDTH)] for y in range(CELLHEIGHT+1)]
    
    def find_best_move(apple,wormCoords,board,direction):
        
        best_move = ERR
    
        #   
        w_x=wormCoords[HEAD]['x']
        w_y=wormCoords[HEAD]['y']
            
        #   
        a_x=apple['x']
        a_y=apple['y']
        
        
        for i in xrange (CELLWIDTH):
            for j in xrange (CELLHEIGHT):
                
                cell = {'x':i,'y':j}
                cell_free = is_cell_free(cell, wormCoords)
                if(cell_free):
                    #    
                    res=abs(i-a_x)+abs(j-a_y)
                    board[j][i]=res
                else:
                    board[j][i]='x'
                
                
        
        for i in xrange (CELLHEIGHT):
            print board[i]
            
        
        #     
        if(w_y-1<0):
            u=100
        else:
            u=board[w_y-1][w_x]
            
        if(w_y+1>CELLHEIGHT-1):
            d=100
        else:
            d=board[w_y+1][w_x]
            
        if(w_x-1<0):
            l=100
        else:
            l=board[w_y][w_x-1]
        
        if(w_x+1>CELLWIDTH-1):
            r=100
        else:
            r=board[w_y][w_x+1]
            
        
        #        best_move
        m=min(u,d,l,r)
        
        if(m==u):
            best_move=UP
     
        if(m==d):
            best_move=DOWN
            
        if(m==l):
            best_move=LEFT
     
        if(m==r):
            best_move=RIGHT
            
        print u,d,l,r
        print best_move
    
        return best_move
        
    
    
    def main():
        
        #       
        global FPSCLOCK, DISPLAYSURF, BASICFONT
    
        pygame.init() #    pygame
        FPSCLOCK = pygame.time.Clock() #   pygame  
        DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) #       
        BASICFONT = pygame.font.Font('resource/PAPYRUS.ttf', 18) # BASICFONT
        pygame.display.set_caption('Wormy') #        
        
        showStartScreen() #       
        
        while True: 
            
            #                       ,
            #           ,              
            #          return,                 
            
            runGame() #     
            
            showGameOverScreen() #         
            
            
    def runGame():
        #                   
        startx = random.randint(5, CELLWIDTH - 6)
        starty = random.randint(5, CELLHEIGHT - 6)
        
        #        ,       3     (  )
        wormCoords = [{'x': startx, 'y': starty},
                      {'x': startx - 1, 'y': starty},
                      {'x': startx - 2, 'y': starty}]
    
    
        direction = RIGHT #           
    
        #     apple   
        apple = getRandomLocation(wormCoords)
        
        
        while True: #      
            for event in pygame.event.get(): #     
                if event.type == QUIT: #     
                    terminate()
                elif event.type == KEYDOWN: #     
                    #         a ,          ,     ,    
                    if (event.key == K_LEFT or event.key == K_a) and direction != RIGHT:
                        direction = LEFT
                    elif (event.key == K_RIGHT or event.key == K_d) and direction != LEFT:
                        direction = RIGHT
                    elif (event.key == K_UP or event.key == K_w) and direction != DOWN:
                        direction = UP
                    elif (event.key == K_DOWN or event.key == K_s) and direction != UP:
                        direction = DOWN
                    elif event.key == K_ESCAPE:
                        terminate()
    
            
    #         best_move=random.choice(mov)
            best_move=find_best_move(apple,wormCoords,board,direction)
            
            
            
            print best_move
            
            direction=best_move
            
            
    
            #              
            if wormCoords[HEAD]['x'] == -1 or wormCoords[HEAD]['x'] == CELLWIDTH or wormCoords[HEAD]['y'] == -1 or wormCoords[HEAD]['y'] == CELLHEIGHT:
                return # game over
            
            #            
            for wormBody in wormCoords[1:]:
                if wormBody['x'] == wormCoords[HEAD]['x'] and wormBody['y'] == wormCoords[HEAD]['y']:
                    return # game over
                
            #          apple
            if wormCoords[HEAD]['x'] == apple['x'] and wormCoords[HEAD]['y'] == apple['y']:
                #             
                apple = getRandomLocation(wormCoords) #         apple
            else:
                del wormCoords[-1] #            
    
            #     ,        ,           
            if direction == UP:
                newHead = {'x': wormCoords[HEAD]['x'], 'y': wormCoords[HEAD]['y'] - 1}
            elif direction == DOWN:
                newHead = {'x': wormCoords[HEAD]['x'], 'y': wormCoords[HEAD]['y'] + 1}
            elif direction == LEFT:
                newHead = {'x': wormCoords[HEAD]['x'] - 1, 'y': wormCoords[HEAD]['y']}
            elif direction == RIGHT:
                newHead = {'x': wormCoords[HEAD]['x'] + 1, 'y': wormCoords[HEAD]['y']}
                
                
            #              
            wormCoords.insert(0, newHead)
            
            #     
            DISPLAYSURF.fill(BGCOLOR)
            
            #        
            drawGrid()
            
            #      
            drawWorm(wormCoords)
            
            #   apple
            drawApple(apple)
            
            #     (             -3)
            drawScore(len(wormCoords) - 3)
            
            #     
            pygame.display.update()
            
            #     
            FPSCLOCK.tick(FPS)
          
    #               
    def drawPressKeyMsg():
        pressKeySurf = BASICFONT.render('Press a key to play.', True, DARKGRAY)
        pressKeyRect = pressKeySurf.get_rect()
        pressKeyRect.topleft = (WINDOWWIDTH - 200, WINDOWHEIGHT - 30)
        DISPLAYSURF.blit(pressKeySurf, pressKeyRect)        
    
    #            
    def checkForKeyPress():
        if len(pygame.event.get(QUIT)) > 0:
            terminate()
    
        keyUpEvents = pygame.event.get(KEYUP)
        if len(keyUpEvents) == 0:
            return None
        if keyUpEvents[0].key == K_ESCAPE:
            terminate()
        return keyUpEvents[0].key
    
    #       
    def showStartScreen():
        
        DISPLAYSURF.fill(BGCOLOR)
        
        titleFont = pygame.font.Font('resource/PAPYRUS.ttf', 100)
        
        titleSurf = titleFont.render('Wormy!', True, GREEN)
        
        titleRect = titleSurf.get_rect()
        titleRect.center = (WINDOWWIDTH / 2, WINDOWHEIGHT / 2)
        DISPLAYSURF.blit(titleSurf, titleRect)
            
        drawPressKeyMsg()
        
        pygame.display.update()
        
        while True:
            
            if checkForKeyPress():
                pygame.event.get() # clear event queue
                return
            
    
    #   
    def terminate():
        pygame.quit()
        sys.exit()
    
    #     cell        ,      free,  true
    def is_cell_free(idx, psnake):
        return not (idx in psnake) 
    
    #               
    def getRandomLocation(wormCoords):
        cell_free = False
        while not cell_free:
            w = random.randint(0, CELLWIDTH - 1)
            h = random.randint(0, CELLHEIGHT - 1)
            food = {'x':w,'y':h}
            cell_free = is_cell_free(food, wormCoords)
    #     return {'x': random.randint(0, CELLWIDTH - 1), 'y': random.randint(0, CELLHEIGHT - 1)}
        return food
    
    #         
    def showGameOverScreen():
        gameOverFont = pygame.font.Font('resource/PAPYRUS.ttf', 50)
        gameSurf = gameOverFont.render('Game', True, WHITE)
        overSurf = gameOverFont.render('Over', True, WHITE)
        gameRect = gameSurf.get_rect()
        overRect = overSurf.get_rect()
        gameRect.midtop = (WINDOWWIDTH / 2, WINDOWHEIGHT / 2-gameRect.height-10)
        overRect.midtop = (WINDOWWIDTH / 2, WINDOWHEIGHT / 2)
    
        DISPLAYSURF.blit(gameSurf, gameRect)
        DISPLAYSURF.blit(overSurf, overRect)
        drawPressKeyMsg()
        pygame.display.update()
        pygame.time.wait(500)
        checkForKeyPress() # clear out any key presses in the event queue
    
        while True:
            if checkForKeyPress():
                pygame.event.get() # clear event queue
                return
            
    #             
    def drawScore(score):
        scoreSurf = BASICFONT.render('Score: %s' % (score), True, WHITE)
        scoreRect = scoreSurf.get_rect()
        scoreRect.topleft = (WINDOWWIDTH - 120, 10)
        DISPLAYSURF.blit(scoreSurf, scoreRect)
    
    
    #    wormCoords        
    def drawWorm(wormCoords):
        for coord in wormCoords:
            x = coord['x'] * CELLSIZE
            y = coord['y'] * CELLSIZE
            wormSegmentRect = pygame.Rect(x, y, CELLSIZE, CELLSIZE)
            pygame.draw.rect(DISPLAYSURF, DARKGREEN, wormSegmentRect)
            wormInnerSegmentRect = pygame.Rect(x + 4, y + 4, CELLSIZE - 8, CELLSIZE - 8)
            pygame.draw.rect(DISPLAYSURF, GREEN, wormInnerSegmentRect)
    
    
    #    coord    apple 
    def drawApple(coord):
        x = coord['x'] * CELLSIZE
        y = coord['y'] * CELLSIZE
        appleRect = pygame.Rect(x, y, CELLSIZE, CELLSIZE)
        pygame.draw.rect(DISPLAYSURF, RED, appleRect)
        
    #         
    def drawGrid():
        for x in range(0, WINDOWWIDTH, CELLSIZE): # draw vertical lines
            pygame.draw.line(DISPLAYSURF, DARKGRAY, (x, 0), (x, WINDOWHEIGHT))
        for y in range(0, WINDOWHEIGHT, CELLSIZE): # draw horizontal lines
            pygame.draw.line(DISPLAYSURF, DARKGRAY, (0, y), (WINDOWWIDTH, y))
    
    
    if __name__ == '__main__':
        main()