#参考Excel表格布局
import copy
import random
import pygame
# 游戏初始化
pygame.init()
pygame.display.set_caption('贪吃蛇')
# 屏幕对象
screen = pygame.display.set_mode((500,500)) #窗口大小
clock = pygame.time.Clock() #时钟对象
#食物出现的位置随机
x = random.randint(10,490)
y = random.randint(10,490)
food_point = [x,y]
#蛇可以在网格移动吃掉食物
#蛇的移动
move_up = False
move_down = True
move_left = False
move_right = False
# 蛇固定的位置
snake_list = [[10,10]]
# 游戏循环
running = True #开关
while running:
#一秒刷新多少次 20fps 帧率
clock.tick(15)
screen.fill([255,255,255]) #背景改为白色
#update 将绘制的内容
food_rect = pygame.draw.circle(screen,[255,0,0],food_point,12)
#绘制蛇的身子
snake_rect = []
#遍历蛇的身子(点)
for pos in snake_list:
#绘制蛇的每一个点
snake_rect.append(pygame.draw.circle(screen,[255,0,0],pos,7))
# 当蛇与食物碰撞,吃掉食物,蛇变长,重新生成食物
if food_rect.collidepoint(pos): #碰撞检测
snake_list.append(food_point) #蛇吃食物
#重新生成食物
food_point = [random.randint(10,490), random.randint(10,490)]
food_rect = pygame.draw.circle(screen, [255, 0, 0], food_point, 12)
break
"""移动蛇的位置"""
# pos = snake_list[0] #蛇头
pos = len(snake_list) - 1
while pos > 0:
snake_list[pos] = copy.deepcopy(snake_list[pos - 1])
pos -= 1
pos = snake_list[0]
if move_right:
pos[0] = pos[0] + 10
if pos[0] >500:
pos[0] =0
elif move_left:
pos[0] = pos[0] - 10
if pos[0] <0:
pos[0] = 500
elif move_up:
pos[1] = pos[1] - 10
if pos[1] <0:
pos[1] = 500
elif move_down:
pos[1] = pos[1] + 10
if pos[1] <0:
pos[1] = 0
"""通过键盘控制移动"""
for event in pygame.event.get():
#键盘控制
#
if event.type == pygame.KEYDOWN:
print(event)
#获取上下左右
if event.key == pygame.K_UP:
print('上')
move_up = True
move_down = False
move_left = False
move_right = False
elif event.key == pygame.K_DOWN:
print('下')
move_up = False
move_down = True
move_left = False
move_right = False
elif event.key == pygame.K_RIGHT:
print('右')
move_up = False
move_down = False
move_left = False
move_right = True
elif event.key == pygame.K_LEFT:
print('左')
move_up = False
move_down = False
move_left = True
move_right = False
#蛇撞到自己
head_rect = snake_rect[0]
count = len(snake_rect)
'''
while count > 1:
if head_rect.colliderect(snake_rect[count - 1]):
running = False
count -= 1
'''
pygame.display.update()