前言 本文的文字及圖片來(lái)源于網(wǎng)絡(luò),僅供學(xué)習(xí)、交流使用,不具有任何商業(yè)用途,如有問(wèn)題請(qǐng)及時(shí)聯(lián)系我們以作處理。 今天,給大家介紹一個(gè)簡(jiǎn)單易懂的貪吃蛇小游戲 代碼 如下 import pygame,sys,randomfrom pygame.locals import *#定義顏色變量 目標(biāo)方塊的顏色redColor = pygame.Color(250,0,0)#貪吃蛇的顏色whiteColor = pygame.Color(255,255,255)#背景顏色blackColor = pygame.Color(0,0,0) def gameOver(): pygame.quit() sys.exit() def main():#初始化pygame pygame.init()#控制游戲速度 fpsColck = pygame.time.Clock()#創(chuàng)建pygame顯示層 playSurface = pygame.display.set_mode((640,480)) pygame.display.set_caption('貪吃蛇')#初始化貪吃蛇的起始坐標(biāo) snakePosition = [100,100]#初始化貪吃蛇的長(zhǎng)度 snakeBody = [[100,100],[80,100],[60,100]]#初始化目標(biāo)方塊的坐標(biāo) targetPosition = [300,300]#初始化一個(gè)目標(biāo)方塊的標(biāo)記 目的:用來(lái)判斷是否吃掉這個(gè)目標(biāo)方塊 targerflag = 1#初始化方向 direction = 'right'#定義一個(gè)方向變量 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_RIGHT: changeDirection = 'right'if event.key == K_LEFT: changeDirection = 'left'if event.key == K_UP: changeDirection = 'up'if event.key == K_DOWN: changeDirection = 'down'#對(duì)應(yīng)鍵盤Esc鍵if event.key == K_ESCAPE: pygame.event.post(pygame.event.Event(QUIT))#確定方向if changeDirection == 'left' and not direction == 'right': direction = changeDirectionif changeDirection == 'right' and not direction == 'left': direction = changeDirectionif changeDirection == 'up' and not direction == 'down': direction = changeDirectionif changeDirection == 'down' and not direction == 'up': direction = changeDirection #根據(jù)方向移動(dòng)蛇頭的坐標(biāo)if direction == 'right': snakePosition[0] += 20if direction == 'left': snakePosition[0] -= 20if direction == 'up': snakePosition[1] -= 20if direction == 'down': snakePosition[1] += 20 #增加蛇的長(zhǎng)度 snakeBody.insert(0,list(snakePosition)) #判斷目標(biāo)方塊是否被吃掉if snakePosition[0] == targetPosition[0] and snakePosition[1] == targetPosition[1]: targerflag = 0else: snakeBody.pop() if targerflag == 0: x = random.randrange(1,32) y = random.randrange(1,24) targetPosition = [int(x*20),int(y*20)] targerflag = 1#繪制pygame的顯示層 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)) pygame.display.flip() if snakePosition[0]> 620 or snakePosition[0] < 0: gameOver()elif snakePosition[1] > 460 or snakePosition[1] < 0: gameOver()#修改速度 fpsColck.tick(10) if __name__ == '__main__': main() |
|