导入相关的包
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
snakeX = 40
snakeY = 40
FOODSNAKEWIDTH = 8
moveLeft = False
moveRight = False
moveUp = False
moveDown = False
moveRight = True
def getSnake():
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
实现贪吃蛇拐弯
为了实现对应的功能,我们将方向变量改为一个变量,这样我们方便修改方向
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
snakeX = 40
snakeY = 40
FOODSNAKEWIDTH = 8
snakeDirection = "moveRight"
foods = []
sizeNum = 39
foodnum = 1
def getSnake():
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)
这里代码比较粗糙,勉强实现了,之后会优化代码,重新整理一下,继续完善游戏。
|