基于pygame的简易贪吃蛇游戏
代码较少,使用了很基础的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()
# 创建界面
playSurface = pygame.display.set_mode((640, 480))
pygame.display.set_caption('贪吃蛇')
# 初始化变量
# 贪吃蛇起始位置
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_RIGHT:
changeDirection = 'right'
if event.key == K_LEFT:
changeDirection = 'left'
if event.key == K_UP:
changeDirection = 'up'
if event.key == K_DOWN:
changeDirection = 'down'
if event.key == K_ESCAPE:
pygame.event.post(pygame.event.Event(QUIT))
# 确定方向
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':
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), 0)
# 画果实
pygame.draw.rect(playSurface, redColor, Rect(targetPosition[0], targetPosition[1], 20, 20), 0)
# 显示到屏幕
pygame.display.flip()
# 游戏结束
if snakePosition[0] > 620 or snakePosition[0] < 0:
print('您撞墙了,游戏结束')
gameOver()
elif snakePosition[1] > 460 or snakePosition[1] < 0:
print('您撞墙了,游戏结束')
gameOver()
else:
flag = 1
for position in snakeBody:
if flag == 1:
flag = 0
continue
if snakePosition[0] == position[0] and snakePosition[1] == position[1]:
print('你把自己咬死了,游戏结束')
gameOver()
# 控制游戏速度
fpsClock.tick(10)
# 启动入口函数
if __name__ == '__main__':
main()
效果图
![](http://www.1990tu.com/i/20200209215431x1h.png)