制作贪吃蛇游戏,使用pygame是一个很好的项目。下面是一个简单的贪吃蛇游戏的代码实现。这个代码创建了一个基本的游戏窗口、一个蛇和一个食物。你可以使用键盘的方向键来控制蛇的移动方向。按上下左右键就可以开始玩了。注意,这个实现非常简单,并没有包含太多的游戏特性,如得分等。
↓ 源码如下 ↓
import sys
import random
import copy
import pygame
from pygame.locals import *
# 定义屏幕的宽高
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)