zoukankan      html  css  js  c++  java
  • Python贪吃蛇

    #pygame游戏库,sys操控Python运行时的环境
    import pygame,sys,random
    from pygame.locals import *
    redColor=pygame.Color(255,0,0)
    blackColor=pygame.Color(0,0,0)
    whiteColor=pygame.Color(255,255,255)
     
    def gameOver():
        pygame.quit()
        sys.exit()
    def main():
        #初始化
        pygame.init()
        #定义一个变量来控制速度
        fpsClock=pygame.time.Clock()
        #创建pygame显示层
        playSurface=pygame.display.set_mode((640,480))
        pygame.display.set_caption('snake')
        
        snakePosition=[100,100]
        snakeBody=[[100,100],[80,100],[60,100]]
        targetPosition=[300,300]
        targetflag=1
        #初始化方向
        direction='right'
        #定义一个方向变量
        changeDirection=direction
        
        while True:
            
            for event in pygame.event.get():    #从队列当中获取事件
                if event.type==QUIT:
                    pygame.quit()
                    sys.exit()
                elif event.type == KEYDOWN:
                    if (event.key == K_LEFT) and direction !='right':
                        changeDirection ='left' 
                    elif (event.key == K_RIGHT) and direction != 'left':
                        changeDirection = 'right' 
                    elif (event.key == K_UP) and direction != 'down':
                        changeDirection =  'up' 
                    elif (event.key == K_DOWN) and direction != 'up':
                        changeDirection = 'down' 
                    elif event.key == K_ESCAPE:
                        pygame.event.post(pygame.event.Event(QUIT))
    
            if changeDirection == 'left' :
                direction =changeDirection
            if changeDirection == 'right':
                direction =changeDirection
            if changeDirection == 'up': 
                direction =changeDirection
            if changeDirection == 'down': 
                direction =changeDirection
             
            #根据方向移动蛇头
            if direction == 'right':
                snakePosition[0] += 20
            if direction == 'left':
                snakePosition[0] -= 20
            if direction == 'up':
                snakePosition[1] -= 20
            if direction == 'down':
                snakePosition[1] += 20
            #增加蛇长度
            snakeBody.insert(0,list(snakePosition))
            if snakePosition[0] == targetPosition[0] and snakePosition[1] == targetPosition[1]:
                targetflag=0
            else:
                snakeBody.pop()
            
            if  targetflag == 0:
                x=random.randrange(1,32)
                y=random.randrange(1,24)
                targetPosition = [int(x*20),int(y*20)]
                targetflag = 1
    
            playSurface.fill(blackColor)
            
            for position in snakeBody:
                
                pygame.draw.rect(playSurface,whiteColor,Rect(position[0],position[1],20,20))
                pygame.draw.rect(playSurface,redColor,Rect(targetPosition[0],targetPosition[1],20,20))
            #第一个参数surface:指定一个surface编辑区,在这个区域内绘制,界面
            #第二个参数color:颜色
            #第三个参数Rect:返回一个矩形((x,y),(width,height))
            #第四个参数 表示线条的粗细 width=0填充 实心   width=1 空心
    
            #更新显示
            pygame.display.flip()
            #判断是否游戏结束
            if snakePosition[0] >620 or snakePosition[0] <0:
                gameOver()
            elif snakePosition[1] >460 or snakePosition[1]<0:
                gameOver()
            #控制游戏速度
            fpsClock.tick(5)
    
    if __name__=='__main__': 
        main()
            
    
    ## encoding: utf-8
    #import pygame
    #import sys
    #import random
    
    ## 全局定义
    #SCREEN_X = 600
    #SCREEN_Y = 600
    
    
    ## 蛇类
    ## 点以25为单位
    #class Snake(object):
    #    # 初始化各种需要的属性 [开始时默认向右/身体块x5]
    #    def __init__(self):
    #        self.dirction = pygame.K_RIGHT
    #        self.body = []
    #        for x in range(5):
    #            self.addnode()
    
    #    # 无论何时 都在前端增加蛇块
    #    def addnode(self):
    #        left,top = (0,0)
    #        if self.body:
    #            left,top = (self.body[0].left,self.body[0].top)
    #        node = pygame.Rect(left,top,25,25)
    #        if self.dirction == pygame.K_LEFT:
    #            node.left -= 25
    #        elif self.dirction == pygame.K_RIGHT:
    #            node.left += 25
    #        elif self.dirction == pygame.K_UP:
    #            node.top -= 25
    #        elif self.dirction == pygame.K_DOWN:
    #            node.top += 25
    #        self.body.insert(0,node)
    
    #    # 删除最后一个块
    #    def delnode(self):
    #        self.body.pop()
    
    #    # 死亡判断
    #    def isdead(self):
    #        # 撞墙
    #        if self.body[0].x  not in range(SCREEN_X):
    #            return True
    #        if self.body[0].y  not in range(SCREEN_Y):
    #            return True
    #        # 撞自己
    #        if self.body[0] in self.body[1:]:
    #            return True
    #        return False
    
    #    # 移动!
    #    def move(self):
    #        self.addnode()
    #        self.delnode()
    
    #    # 改变方向 但是左右、上下不能被逆向改变
    #    def changedirection(self,curkey):
    #        LR = [pygame.K_LEFT,pygame.K_RIGHT]
    #        UD = [pygame.K_UP,pygame.K_DOWN]
    #        if curkey in LR+UD:
    #            if (curkey in LR) and (self.dirction in LR):
    #                return
    #            if (curkey in UD) and (self.dirction in UD):
    #                return
    #            self.dirction = curkey
    
    
    ## 食物类
    ## 方法: 放置/移除
    ## 点以25为单位
    #class Food:  
    #    def __init__(self):  
    #        self.rect = pygame.Rect(-25,0,25,25)  
      
    #    def remove(self):  
    #        self.rect.x=-25  
      
    #    def set(self):  
    #        if self.rect.x == -25:  
    #            allpos = []  
    #            # 不靠墙太近 25 ~ SCREEN_X-25 之间  
    #            for pos in range(25,SCREEN_X-25,25):  
    #                allpos.append(pos)  
    #            self.rect.left = random.choice(allpos)  
    #            self.rect.top  = random.choice(allpos)  
    #            print(self.rect)  
      
      
    #def show_text(screen, pos, text, color, font_bold = False, font_size = 60, font_italic = False):  
    #    #获取系统字体,并设置文字大小  
    #    cur_font = pygame.font.SysFont("宋体", font_size)  
    #    #设置是否加粗属性  
    #    cur_font.set_bold(font_bold)  
    #    #设置是否斜体属性  
    #    cur_font.set_italic(font_italic)  
    #    #设置文字内容  
    #    text_fmt = cur_font.render(text, 1, color)  
    #    #绘制文字  
    #    screen.blit(text_fmt, pos)  
      
      
    #def main():  
    #    pygame.init()  
    #    screen_size = (SCREEN_X,SCREEN_Y)  
    #    screen = pygame.display.set_mode(screen_size)  
    #    pygame.display.set_caption('Snake')  
    #    clock = pygame.time.Clock()  
    #    scores = 0  
    #    isdead = False  
      
    #    # 蛇/食物  
    #    snake = Snake()  
    #    food = Food()  
      
    #    while True:  
    #        for event in pygame.event.get():  
    #            if event.type == pygame.QUIT:  
    #                sys.exit()  
    #            if event.type == pygame.KEYDOWN:  
    #                snake.changedirection(event.key)  
    #                # 死后按space重新  
    #                if event.key == pygame.K_SPACE and isdead:  
    #                    return main()  
      
      
    #        screen.fill((255,255,255))  
      
    #        # 画蛇身 / 每一步+1分  
    #        if not isdead:  
    #            #scores+=1  
    #            snake.move()  
    #        for rect in snake.body:  
    #            pygame.draw.rect(screen,(20,220,39),rect,0)  
      
    #        # 显示死亡文字  
    #        isdead = snake.isdead()  
    #        if isdead:  
    #            show_text(screen,(100,200),'YOU DEAD!',(227,29,18),False,100)  
    #            show_text(screen,(150,260),'press space to try again...',(0,0,22),False,30)  
      
    #        # 食物处理 / 吃到+50分  
    #        # 当食物rect与蛇头重合,吃掉 -> Snake增加一个Node  
    #        if food.rect == snake.body[0]:  
    #            scores+=50  
    #            food.remove()  
    #            snake.addnode()  
      
    #        # 食物投递  
    #        food.set()  
    #        pygame.draw.rect(screen,(136,0,21),food.rect,0)  
      
    #        # 显示分数文字  
    #        show_text(screen,(50,500),'Scores: '+str(scores),(223,223,223))  
      
    #        pygame.display.update()  
    #        clock.tick(10)  
      
      
    #if __name__ == '__main__':  
    #    main()  
    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    import random
    import pygame
    import sys
    from pygame.locals import *
     
    Snakespeed = 10
    Window_Width = 800
    Window_Height = 500
    Cell_Size = 20  # Width and height of the cells
    # Ensuring that the cells fit perfectly in the window. eg if cell size was
    # 10     and window width or windowheight were 15 only 1.5 cells would
    # fit.
    assert Window_Width % Cell_Size == 0, "Window width must be a multiple of cell size."
    # Ensuring that only whole integer number of cells fit perfectly in the window.
    assert Window_Height % Cell_Size == 0, "Window height must be a multiple of cell size."
    Cell_W = int(Window_Width / Cell_Size)  # Cell Width
    Cell_H = int(Window_Height / Cell_Size)  # Cell Height
     
     
    White = (255, 255, 255)
    Black = (0, 0, 0)
    Red = (255, 0, 0)  # Defining element colors for the program.
    Green = (0, 255, 0)
    DARKGreen = (0, 155, 0)
    DARKGRAY = (40, 40, 40)
    YELLOW = (255, 255, 0)
    Red_DARK = (150, 0, 0)
    BLUE = (0, 0, 255)
    BLUE_DARK = (0, 0, 150)
     
     
    BGCOLOR = Black  # Background color
     
     
    UP = 'up'
    DOWN = 'down'   # Defining keyboard keys.
    LEFT = 'left'
    RIGHT = 'right'
     
    HEAD = 0    # Syntactic sugar: index of the snake's head
     
     
    def main():
        global SnakespeedCLOCK, DISPLAYSURF, BASICFONT
     
        pygame.init()#pygame初始化
        SnakespeedCLOCK = pygame.time.Clock()
        DISPLAYSURF = pygame.display.set_mode((Window_Width, Window_Height))
        BASICFONT = pygame.font.Font('freesansbold.ttf', 36)
        pygame.display.set_caption('Snake')
     
        showStartScreen()
        while True:
            runGame()
            showGameOverScreen()
     
     
    def runGame():
        # Set a random start point.
        startx = random.randint(5, Cell_W - 6)
        starty = random.randint(5, Cell_H - 6)
        wormCoords = [{'x': startx, 'y': starty},
                      {'x': startx - 1, 'y': starty},
                      {'x': startx - 2, 'y': starty}]
        direction = RIGHT
     
        # Start the apple in a random place.
        apple = getRandomLocation()
     
        while True:  # main game loop
            for event in pygame.event.get():  # event handling loop
                if event.type == QUIT:
                    terminate()
                elif event.type == KEYDOWN:
                    if (event.key == K_LEFT) and direction != RIGHT:
                        direction = LEFT
                    elif (event.key == K_RIGHT) and direction != LEFT:
                        direction = RIGHT
                    elif (event.key == K_UP) and direction != DOWN:
                        direction = UP
                    elif (event.key == K_DOWN) and direction != UP:
                        direction = DOWN
                    elif event.key == K_ESCAPE:
                        terminate()
     
            # check if the Snake has hit itself or the edge
            if wormCoords[HEAD]['x'] == -1 or wormCoords[HEAD]['x'] == Cell_W or wormCoords[HEAD]['y'] == -1 or wormCoords[HEAD]['y'] == Cell_H:
                return  # game over
            for wormBody in wormCoords[1:]:
                if wormBody['x'] == wormCoords[HEAD]['x'] and wormBody['y'] == wormCoords[HEAD]['y']:
                    return  # game over
     
            # check if Snake has eaten an apply
            if wormCoords[HEAD]['x'] == apple['x'] and wormCoords[HEAD]['y'] == apple['y']:
                # don't remove worm's tail segment
                apple = getRandomLocation()  # set a new apple somewhere
            else:
                del wormCoords[-1]  # remove worm's tail segment
     
            # move the worm by adding a segment in the direction it is moving
            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)
            drawApple(apple)
            #drawScore(len(wormCoords) - 3)
            pygame.display.update()
            SnakespeedCLOCK.tick(Snakespeed)
     
     
    def drawPressKeyMsg():
        pressKeySurf = BASICFONT.render('Press a key to play.', True, White)
        pressKeyRect = pressKeySurf.get_rect()
        pressKeyRect.topleft = (Window_Width - 200, Window_Height - 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():
        titleFont = pygame.font.Font('freesansbold.ttf', 100)
        titleSurf1 = titleFont.render('Snake!', True, White, DARKGreen)
        degrees1 = 0
        degrees2 = 0
        while True:
            DISPLAYSURF.fill(BGCOLOR)
            rotatedSurf1 = pygame.transform.rotate(titleSurf1, degrees1)
            rotatedRect1 = rotatedSurf1.get_rect()
            rotatedRect1.center = (Window_Width / 2, Window_Height / 2)
            DISPLAYSURF.blit(rotatedSurf1, rotatedRect1)
     
            drawPressKeyMsg()
     
            if checkForKeyPress():
                pygame.event.get()  # clear event queue
                return
            pygame.display.update()
            SnakespeedCLOCK.tick(Snakespeed)
            degrees1 += 3  # rotate by 3 degrees each frame
            degrees2 += 7  # rotate by 7 degrees each frame
     
     
    def terminate():
        pygame.quit()
        sys.exit()
     
     
    def getRandomLocation():
        return {'x': random.randint(0, Cell_W - 1), 'y': random.randint(0, Cell_H - 1)}
     
     
    def showGameOverScreen():
        gameOverFont = pygame.font.Font('freesansbold.ttf', 100)
        gameSurf = gameOverFont.render('Game', True, White)
        overSurf = gameOverFont.render('Over', True, White)
        gameRect = gameSurf.get_rect()
        overRect = overSurf.get_rect()
        gameRect.midtop = (Window_Width / 2, 10)
        overRect.midtop = (Window_Width / 2, gameRect.height + 10 + 25)
     
        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 = (Window_Width - 120, 10)
    #    DISPLAYSURF.blit(scoreSurf, scoreRect)
     
     
    def drawWorm(wormCoords):
        for coord in wormCoords:
            x = coord['x'] * Cell_Size
            y = coord['y'] * Cell_Size
            wormSegmentRect = pygame.Rect(x, y, Cell_Size, Cell_Size)
            pygame.draw.rect(DISPLAYSURF, DARKGreen, wormSegmentRect)
            wormInnerSegmentRect = pygame.Rect(
                x + 4, y + 4, Cell_Size - 8, Cell_Size - 8)
            pygame.draw.rect(DISPLAYSURF, Green, wormInnerSegmentRect)
     
     
    def drawApple(coord):
        x = coord['x'] * Cell_Size
        y = coord['y'] * Cell_Size
        appleRect = pygame.Rect(x, y, Cell_Size, Cell_Size)
        pygame.draw.rect(DISPLAYSURF, Red, appleRect)
     
    
    def drawGrid():
        for x in range(0, Window_Width, Cell_Size):  # draw vertical lines
            pygame.draw.line(DISPLAYSURF, DARKGRAY, (x, 0), (x, Window_Height))
        for y in range(0, Window_Height, Cell_Size):  # draw horizontal lines
            pygame.draw.line(DISPLAYSURF, DARKGRAY, (0, y), (Window_Width, y))
    
    
    if __name__ == '__main__':
        try:
            main()
        except SystemExit:
            pass
    
  • 相关阅读:
    CentOS优化
    C++ 与OpenCV 学习笔记
    常用ubuntu命令
    对极几何笔记
    DBoW2 词袋模型笔记
    OKVIS(一)初始化流程及代码结构
    二进制描述子 BRIEF(ORB), BRISK, FREAK
    VIO 初始化小结
    VINS(十)FeatureManager(未完待续)
    VINS(九)Ceres Solver优化(未完待续)
  • 原文地址:https://www.cnblogs.com/xingkongcanghai/p/11656918.html
Copyright © 2011-2022 走看看