#pygame游戲庫,sys操控python運行的環境
import pygame,sys,random
#這個模塊包含所有pygame所使用的常亮
from pygame.locals import *
#1,定義顏色變數
#0-255 0黑色 255白色
redColor = pygame.Color(255,0,0)
#背景為黑色
blackColor = pygame.Color(0,0,0)
#貪吃蛇為白色
whiteColor = pygame.Color(255,255,255)
#定義游戲結束的函式
def gameover():
pygame.quit()
sys.exit()
#定義main函式--》定義我們的入口函式
def main():
#初始化pygame
pygame.init()
#定義一個變數來控制速度
fpsClock=pygame.time.Clock()
#創建pygame顯示層,創建一個界面
playsurface=pygame.display.set_mode((640,480))
pygame.display.set_caption('貪吃蛇')
#初始化變數
#貪吃蛇初始坐標位置 (先以100,100為基準)
snakePosition = [100,100]
#初始化貪吃蛇的長度串列中有個元素就代表有幾段身體
snakeBody = [[100,100],[80,100],[60,100]]
#初始化目標方向額位置
targetPosition = [300,300]
#目標方塊的標記 目的:判斷是否吃掉了這個目標方塊1 就是沒有吃 0就是吃掉
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_d:
changeDirection = 'right'
if event.key == K_a:
changeDirection = 'left'
if event.key ==K_w:
changeDirection = 'up'
if event.key ==K_s:
changeDirection = 'down'
#對應鍵盤上的esc檔案
if event.key == K_ESCAPE:
pygame.event.post(pygame.event.Event(QUIT))
#確定方向
if changeDirection =='left' and not direction =='right':
direction = changeDirection
if changeDirection =='right' and not direction =='left':
direction = changeDirection
if changeDirection =='up' and not direction =='down':
direction = changeDirection
if changeDirection =='down' and not direction =='up':
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:
#第一個引數serface指定一個serface編輯區,在這個區域內繪制
#第二個引數color:顏色
#第三個引數:rect:回傳一個矩形(xy),(width,height)
#第四個引數:width:表示線條的粗細 width0填充 實心
#化蛇
pygame.draw.rect(playsurface,redColor,Rect(position[0],position[1],20,20))
pygame.draw.rect(playsurface, whiteColor, 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()
#控制游戲速度
fpsClock.tick(2)
# 啟動入口函式
if __name__ =='__main__':
main()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/325843.html
標籤:其他
上一篇:Python:數字游戲
下一篇:Unity 人物上坡貼地移動
