'''
@Auther : 朱亦奇
@Description : a snake game coded by python.本程序用循环比较食物和蛇身坐标的方法,
解决了随机生成的食物与蛇身重叠导致食物不出现的问题。
'''
import pygame,sys,random
from pygame.locals import *
#初始化pygame库
pygame.init()
height=200
width=200
#初始化一个游戏界面
DISPLAY=pygame.display.set_mode((height,width))
#设置游戏窗口标题
pygame.display.set_caption('贪吃蛇')
#定义一个变量控制游戏速度
FPSCLOCK=pygame.time.Clock()
#定义颜色
black=pygame.Color(0,0,0)
green=pygame.Color(0,255,0)
red=pygame.Color(255,0,0)
yellow=pygame.Color(255,255,0)
#定义一个蛇初始长度,因为格子都是20*20所以长度都是减20
snakeBody=[[40,60],[20,60]]
#定义蛇头初始位置
snakeHead=[60,60]
#蛇初始方向
direction='right'
#定义改变方向的变量,按键
changeDirection = direction
#定义初始食物位置
foodPostion = [100,100]
#初始游戏速度
gameSpeed = 2.5
#绘制贪吃蛇
def drawSnake():
pygame.draw.rect(DISPLAY,yellow,Rect(snakeHead[0],snakeHead[1],20,20))
for body in snakeBody[1:]:
pygame.draw.rect(DISPLAY,green,Rect(body[0],body[1],20,20))
#绘制食物位置
def drawFood():
pygame.draw.rect(DISPLAY,red,Rect(foodPostion[0],foodPostion[1],20,20))
#游戏结束
def gameover():
#退出pygame
pygame.quit()
#退出程序
sys.exit()
#随机生成食物位置,并避开蛇
def foodUpdate():
while True:
foodPostion[0] = random.randint(0,height/20 - 1) * 20
foodPostion[1] = random.randint(0,width/20 - 1) * 20
if foodPostion not in snakeBody:
break
while True:
#增加蛇的长度(头)
snakeBody.insert(0,list(snakeHead))
#渲染底色
DISPLAY.fill(black)
#画出贪吃蛇
drawSnake()
#画出食物位置
drawFood()
#刷新显示层,贪吃蛇与食物每次移动,都会刷新显示层
pygame.display.flip()
FPSCLOCK.tick(gameSpeed)
#监听键盘事件
for event in pygame.event.get():
if event.type == QUIT:
gameover()
elif event.type == KEYDOWN:
# 如果是右箭头或者是d,蛇向右移动
if event.key == K_RIGHT or event.key == K_d:
changeDirection = 'right'
# 如果是左箭头或者是a,蛇向左移动
if event.key == K_LEFT or event.key == K_a:
changeDirection = 'left'
# 如果是上箭头或者是w,蛇向上移动
if event.key == K_UP or event.key == K_w:
changeDirection = 'up'
# 如果是下箭头或者是s,蛇向下移动
if event.key == K_DOWN or event.key == K_s:
changeDirection = 'down'
#判断是否输入了反方向(蛇不能往回走)
if changeDirection == 'right' and not direction == 'left':
direction = changeDirection
if changeDirection == 'left' and not direction == 'right':
direction = changeDirection
if changeDirection == 'up' and not direction == 'down':
direction = changeDirection
if changeDirection == 'down' and not direction == 'up':
direction = changeDirection
#根据方向移动蛇头
if direction=='right':
snakeHead[0]+=20
if direction=='left':
snakeHead[0]-=20
if direction=='up':
snakeHead[1]-=20
if direction=='down':
snakeHead[1]+=20
#如果食物被吃了
if snakeHead == foodPostion:
foodUpdate()
#增加游戏速度
gameSpeed += 0.2
else:
#减少蛇的长度(尾巴)
snakeBody.pop()
#如果碰到墙壁
if (snakeHead[0] > height or snakeHead[0] < 0) or (snakeHead[1] > width or snakeHead[1] < 0):
gameover()
# 如果碰到自己
for body in snakeBody[2:]:
if snakeHead == body:
gameover()
Python简易贪吃蛇游戏
最新推荐文章于 2024-07-12 16:16:27 发布