导入相关的包
import pygame, sys, random
from pygame.locals import *
设置屏幕大小以及基本参数
设置屏幕大小为400*400,mainClock = pygame.time.Clock()用来设置时间同步,不会根据计算机的运行来决定运行多少次, mainClock.tick(1) 一秒只会运行一次,设置了屏幕的底色为白色。
# 定义屏幕的宽高
WIDTH = 400
HEIGHT = 400
# 初始化屏幕 设置窗口
surface = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)
pygame.display.set_caption('贪吃蛇')
pygame.init()
mainClock = pygame.time.Clock()
# 定义使用的颜色
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
WHITE = (255, 255, 255)
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
surface.fill(WHITE)
pygame.display.update()
mainClock.tick(1)
设置贪吃蛇的位置,以及移动的大小
这里设置了贪吃蛇的长度和起始位置,和食物和蛇的宽度,这里必须设置为可以被食物和蛇的宽度整除的数,这样才能保证蛇能到任意的位置
# 设置蛇的初始长度
snakeWidth = 4
# 设置蛇的起始位置为(40,40)
snakeX = 40
snakeY = 40
# 食物和蛇的宽度设置为8
FOODSNAKEWIDTH = 8
# 定义四个方向
moveLeft = False
moveRight = False
moveUp = False
moveDown = False
# 定义初始的方向
moveRight = True
def getSnake():
# 设置蛇的初始长度为4,并设置蛇的初始位置为(40,40)
# 因为贪吃蛇会拐弯,所以将蛇设置为一个列表
snake = []
for i in range(snakeWidth):
snake.append(pygame.Rect(snakeX + i * FOODSNAKEWIDTH, snakeY, FOODSNAKEWIDTH, FOODSNAKEWIDTH))
return snake
# 贪吃蛇
snake = getSnake()
绘制蛇
surface.fill(WHITE)
for s in snake:
pygame.draw.rect(surface, BLACK, s)
让蛇动起来
这里将蛇列表最后一位移除,然后将第一位的位置根据方向加减坐标
snake.pop()
newTop = copy.deepcopy(snake[0])
# 改变蛇的位置
if moveRight:
newTop.left += FOODSNAKEWIDTH
if moveLeft:
newTop.left -= FOODSNAKEWIDTH
if moveUp:
newTop.top -= FOODSNAKEWIDTH
if moveDown:
newTop.top += FOODSNAKEWIDTH
snake.insert(0, newTop)
这样会有一个问题,如果超出屏幕呢,我们将超出屏幕,那么就会消失,我们只需要你移动第一个元素的时候,如果超出则将元素移动另一个位置。
# 改变蛇的位置
if moveRight:
if newTop.right == WIDTH:
newTop.left = 0
else:
newTop.left += FOODSNAKEWIDTH
if moveLeft:
if newTop.left == 0:
newTop.right == WIDTH
else:
newTop.left -= FOODSNAKEWIDTH
if moveUp:
if newTop.top == 0:
newTop.bottom = HEIGHT
else:
newTop.top -= FOODSNAKEWIDTH
if moveDown:
if newTop.bottom == HEIGHT:
newTop.top = 0
else:
newTop.top += FOODSNAKEWIDTH
实现贪吃蛇拐弯
为了实现对应的功能,我们将方向变量改为一个变量,这样我们方便修改方向
# 定义四个方向
# moveLeft moveRight moveUp moveDown
# 定义初始的方向
snakeDirection = "moveRight"
----
省略的代码
----
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_LEFT:
if snakeDirection == "moveRight":
snake.reverse()
snakeDirection = "moveLeft"
if event.key == K_RIGHT:
if snakeDirection == "moveLeft":
snake.reverse()
snakeDirection = "moveRight"
if event.key == K_UP:
if snakeDirection == "moveDown":
snake.reverse()
snakeDirection = "moveUp"
if event.key == K_DOWN:
if snakeDirection == "moveUp":
snake.reverse()
snakeDirection = "moveDown"
为了方便看到效果,我将mainClock.tick(1) 设置为mainClock.tick(3)
实现随机食物
这里用了很啰嗦的代码,我自己也看不下去,有点含糊,这里为了简单只设计了一个食物,遍历屏幕上不是贪吃蛇的可以放食物的集合,然后随机生成一个食物。
if len(foods) < foodnum:
canFoodColl = []
# 获取当前不是贪吃蛇的位置集合
for x in range(sizeNum):
for y in range(sizeNum):
foodExist = True
for sn in snake:
if x * FOODSNAKEWIDTH == sn.left and y * FOODSNAKEWIDTH == sn.top:
foodExist = False
break
if foodExist:
canFoodColl.append({'x': x, 'y': y})
f = canFoodColl[random.randint(0, len(canFoodColl))]
foods.append(pygame.Rect(f['x'], f['y'], FOODSNAKEWIDTH, FOODSNAKEWIDTH))
吃食物
这里用 colliderect判断二者是否相撞,然后食物集合置空,不减去贪吃蛇集合的最后一个元素。
if len(foods) < foodnum:
canFoodColl = []
# 获取当前不是贪吃蛇的位置集合
for x in range(sizeNum):
for y in range(sizeNum):
foodExist = True
for sn in snake:
if x * FOODSNAKEWIDTH == sn.left and y * FOODSNAKEWIDTH == sn.top:
foodExist = False
break
if foodExist:
canFoodColl.append({'x': x, 'y': y})
f = canFoodColl[random.randint(0, len(canFoodColl))]
foods.append(pygame.Rect(f['x'] * FOODSNAKEWIDTH, f['y'] * FOODSNAKEWIDTH, FOODSNAKEWIDTH, FOODSNAKEWIDTH))
print(f['x'])
print(f['y'])
else:
if newTop.colliderect(foods[0]):
foods = []
eatFlg = True
print('xxx')
完整代码
import pygame, sys, random
from pygame.locals import *
import copy
# 定义屏幕的宽高
WIDTH = 400
HEIGHT = 400
# 初始化屏幕 设置窗口
surface = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)
pygame.display.set_caption('贪吃蛇')
pygame.init()
mainClock = pygame.time.Clock()
# 定义使用的颜色
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
WHITE = (255, 255, 255)
# 设置蛇的初始长度
snakeWidth = 4
# 设置蛇的起始位置为(40,40)
snakeX = 40
snakeY = 40
# 食物和蛇的宽度设置为8
FOODSNAKEWIDTH = 8
# 定义四个方向
# moveLeft moveRight moveUp moveDown
# 定义初始的方向
snakeDirection = "moveRight"
# 食物区间
foods = []
# 用去宽度处以对应的 大小,减去1 就是食物矩形起点可以存在的区间
#sizeNum = HEIGHT / FOODSNAKEWIDTH - 1
# 这里为了减少计算
sizeNum = 39
# 为了简单我们只设置一个食物
foodnum = 1
def getSnake():
# 设置蛇的初始长度为4,并设置蛇的初始位置为(40,40)
# 因为贪吃蛇会拐弯,所以将蛇设置为一个列表
snake = []
for i in range(snakeWidth):
snake.append(pygame.Rect(snakeX + i * FOODSNAKEWIDTH, snakeY, FOODSNAKEWIDTH, FOODSNAKEWIDTH))
return snake
# 贪吃蛇
snake = getSnake()
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_LEFT:
if snakeDirection == "moveRight":
snake.reverse()
snakeDirection = "moveLeft"
if event.key == K_RIGHT:
if snakeDirection == "moveLeft":
snake.reverse()
snakeDirection = "moveRight"
if event.key == K_UP:
if snakeDirection == "moveDown":
snake.reverse()
snakeDirection = "moveUp"
if event.key == K_DOWN:
if snakeDirection == "moveUp":
snake.reverse()
snakeDirection = "moveDown"
surface.fill(WHITE)
for s in snake:
pygame.draw.rect(surface, BLACK, s)
for f in foods:
pygame.draw.rect(surface, GREEN, f)
pygame.display.update()
# 是否吃了食物
eatFlg = False
newTop = copy.deepcopy(snake[0])
# 改变蛇的位置
if snakeDirection == "moveRight":
if newTop.right == WIDTH:
newTop.left = 0
else:
newTop.left += FOODSNAKEWIDTH
if snakeDirection == "moveLeft":
if newTop.left == 0:
newTop.right = WIDTH
else:
newTop.left -= FOODSNAKEWIDTH
if snakeDirection == "moveUp":
if newTop.top == 0:
newTop.bottom = HEIGHT
else:
newTop.top -= FOODSNAKEWIDTH
if snakeDirection == "moveDown":
if newTop.bottom == HEIGHT:
newTop.top = 0
else:
newTop.top += FOODSNAKEWIDTH
if len(foods) < foodnum:
canFoodColl = []
# 获取当前不是贪吃蛇的位置集合
for x in range(sizeNum):
for y in range(sizeNum):
foodExist = True
for sn in snake:
if x * FOODSNAKEWIDTH == sn.left and y * FOODSNAKEWIDTH == sn.top:
foodExist = False
break
if foodExist:
canFoodColl.append({'x': x, 'y': y})
f = canFoodColl[random.randint(0, len(canFoodColl))]
foods.append(pygame.Rect(f['x'] * FOODSNAKEWIDTH, f['y'] * FOODSNAKEWIDTH, FOODSNAKEWIDTH, FOODSNAKEWIDTH))
print(f['x'])
print(f['y'])
else:
if newTop.colliderect(foods[0]):
foods = []
eatFlg = True
print('xxx')
snake.insert(0, newTop)
if not eatFlg:
snake.pop()
mainClock.tick(3)
以上就是基于Pygame实现简单的贪吃蛇游戏的详细内容,更多关于Pygame 贪吃蛇游戏的资料请关注编程网其它相关文章!