1.main.py
import pygame
from pygame.locals import *
import sys
import const
from board import Board
from const import *
def main():
board = Board()
myfood = board.initFoodPos()
board.set_food(myfood) # 开始的时候随机生成食物的位置
board.set_head([0, 0]) # 开始的时候蛇头的位置
board.set_tail([]) # 开始的时候没有蛇尾
direction = "right"
# print(board.food)
# 初始化pygame
pygame.init()
# 设置窗口大小
SCREEN_SIZE = (const.BOARD_WIDTH * const.BOX, const.BOARD_HEIGHT * const.BOX)
# 设置显示模式
# 参数1 分辨率 元组 两个值
# 参数2 标志位 如果不需要什么特效 直接写0
# 参数3 色深
playSurface = pygame.display.set_mode(SCREEN_SIZE, 0, 32)
# 修稿窗口标题
pygame.display.set_caption("贪吃蛇")
# 初始化时钟对象
fpsClock = pygame.time.Clock()
# 游戏主循环
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 or event.key == ord('a'):
direction = "left"
if event.key ==K_RIGHT or event.key == ord('d'):
direction = "right"
if event.key ==K_UP or event.key == ord('w'):
direction = "up"
if event.key ==K_DOWN or event.key == ord('s'):
direction = "down"
if event.key == K_ESCAPE: #ESC键退出
pygame.event.post(pygame.event.Event(QUIT))
# 根据方向移动蛇头的坐标
cur_state=board.move_with_tail(direction)
# 绘制背景
playSurface.fill(const.BLACK_COLOR)
# 绘制食物
# 参数1 在哪个surface对象上进行绘制
# 参数2 color颜色pygame.Color对象
# 参数3 Rect
pygame.draw.rect(playSurface, const.YELLOW_COLOR,Rect(board.food[0] * const.BOX, board.food[1] * const.BOX,const.BOX, const.BOX))
# 绘制蛇头
pygame.draw.rect(playSurface, const.RED_COLOR,Rect(board.head[0] * const.BOX, board.head[1]*const.BOX, const.BOX, const.BOX))
for position in board.tailArr:
pygame.draw.rect(playSurface, const.GREEN_COLOR, Rect(position[0]*const.BOX,position[1]*const.BOX,const.BOX,const.BOX))
# 刷新pygame显示器
pygame.display.flip()
# 控制游戏速度
fpsClock.tick(5)
# 判断游戏是否结束
if cur_state == const.STATE_GAMEOVER:
pygame.event.post(pygame.event.Event(QUIT))
if __name__ == "__main__":
main()
2.const.py
# 专门放置程序中的常量
import pygame
class Const:
pass
# 创建类的对象 并写入常量
const = Const()
const.BOX = 20
const.BOARD_WIDTH = 30
const.BOARD_HEIGHT = 30
#颜色常量
const.BLACK_COLOR = pygame.Color(0, 0, 0)
const.RED_COLOR = pygame.Color(255, 0, 0)
const.GREEN_COLOR = pygame.Color(0, 255, 0)
const.BLUE_COLOR = pygame.Color(0, 0, 255)
const.YELLOW_COLOR = pygame.Color(255, 255, 0)
const.CYAN_COLOR = pygame.Color(0, 255, 255)
const.PURPLE_COLOR = pygame.Color(255, 0, 255)
const.WHITE_COLOR = pygame.Color(255, 255, 255)
const.GRAY_COLOR = pygame.Color(127, 127, 127)
#移动一步之后的状态
const.STATE_GAMEOVER = 0
const.STATE_MOVE= 1
const.STATE_EAT_FOOD =2
3.board.py
import random
import math
from const import *
import copy
class Board:
def __init__(self):
pass
# 属性
food = [4, 5]
head = [0, 0]
tailArr = []
# 方法
def set_food(self, food):
self.food = food
def set_head(self, head):
self.head = head
def set_tail(self, tailArr):
self.tailArr = tailArr
def initFoodPos(self):
while True:
x = math.floor(random.random() * const.BOARD_WIDTH)
y = math.floor(random.random() * const.BOARD_HEIGHT)
if [x, y] == self.head:
continue
if [x, y] in self.tailArr:
continue
return [x, y]
# 坐标按照方向找下一个格子
# 参数pos点 用列表表示 列表里面有两个值 分别代表x,y
# 参数position 方向 值 为left,right,up,down为之一
def move(self, pos, direction):
nextPos = copy.deepcopy(pos)
if direction == "left":
nextPos[0] -= 1
elif direction == "right":
nextPos[0] += 1
elif direction == "up":
nextPos[1] -= 1
elif direction == "down":
nextPos[1] += 1
return nextPos
# 蛇头按照方向移动一格
def move_with_tail(self, direction):
if not self.is_move_possible(self.head,direction):
return const.STATE_GAMEOVER
food_eated = False
self.tailArr.insert(0, self.head)
self.head = self.move(self.head, direction)
#吃到食物时,食物重新生成
if self.food == self.head:
self.food = self.initFoodPos()
food_eated =True
else:
#如果是没有吃到食物,则删除蛇尾的最后一部分
self.tailArr.pop()
if food_eated:
return const.STATE_EAT_FOOD
else:
return const.STATE_MOVE
#假设蛇头在pos位置上,检测方向dir移动是否在棋盘上
def is_in_board(self,pos,direction):
nextPos = self.move(pos,direction)
#对nextPos进行越界判断
if nextPos[0]<0 \
or nextPos[0]>=const.BOARD_WIDTH \
or nextPos[1] <0 \
or nextPos[1]>=const.BOARD_HEIGHT:
return False
return True
def is_move_possible(self,pos,direction):
return self.is_in_board(pos,direction)