# 贪吃蛇
import pygame
import random
import copy# 蛇身,蛇头在最后
snake_list = [[10, 10]]# 移动方向
move_up = False
move_down = True
move_left = False
move_right = False# 苹果 随机
apple_point = [random.randrange(20, 780, 20), random.randrange(20, 580, 20)] # 20~780随机生成一个数,不能生成到外面去"""初始化游戏"""
pygame.init()
# fps 刷新帧率
clock = pygame.time.Clock()
# 设置屏幕大小
screen = pygame.display.set_mode((800, 600))
# 绘制标题
pygame.display.set_caption('贪吃蛇')"""进入游戏"""
# 设置游戏开关
running = True
while running:# 设置fps为15clock.tick(15)# 绘制屏幕为黑色screen.fill([0, 0, 0])# 用键盘控制移动方向for event in pygame.event.get():# 判断按键是否按下if event.type == pygame.KEYDOWN:# 判断按键类型if event.key == pygame.K_UP and not move_down:move_up = Truemove_down = Falsemove_left = Falsemove_right = Falseif event.key == pygame.K_DOWN and not move_up:move_up = Falsemove_down = Truemove_left = Falsemove_right = Falseif event.key == pygame.K_LEFT and not move_right:move_up = Falsemove_down = Falsemove_left = Truemove_right = Falseif event.key == pygame.K_RIGHT and not move_left:move_up = Falsemove_down = Falsemove_left = Falsemove_right = True# 绘制苹果apple_rect = pygame.draw.circle(screen, [255, 0, 0], apple_point, 20) # 绘制圆点# 绘制蛇snake_rect = [] # 蛇身for snake_point in snake_list:snake_rect.append(pygame.draw.circle(screen, [255, 255, 255], snake_point, 10, 0))# 点碰撞检测,吃苹果if apple_rect.collidepoint(snake_point):# 蛇吃掉苹果,增加一个点snake_list.append(apple_point)# 重新绘制苹果apple_point = [random.randrange(20, 780, 20), random.randrange(20, 580, 20)]apple_rect = pygame.draw.circle(screen, [255, 0, 0], apple_point, 20, 0) # 绘制圆点break"""让蛇移动"""pos = len(snake_list) - 1# 蛇身移动while pos > 0:snake_list[pos] = copy.deepcopy(snake_list[pos - 1]) # 把前一个蛇身赋值给后一个蛇身pos -= 1# 更改蛇头位置,蛇头单独处理,蛇头控制方向if move_up:snake_list[pos][1] -= 20if snake_list[pos][1] < 0:snake_list[pos][1] = 600if move_down:snake_list[pos][1] += 20if snake_list[pos][1] > 600:snake_list[pos][1] = 0if move_left:snake_list[pos][0] -= 20if snake_list[pos][0] < 0:snake_list[pos][0] = 800if move_right:snake_list[pos][0] += 20if snake_list[pos][0] > 800:snake_list[pos][0] = 0# 蛇撞上自己,结束游戏head_rect = snake_rect[0] # 蛇头count = len(snake_rect)while count > 1:# 矩形碰撞检测if head_rect.colliderect(snake_rect[count - 1]):running = Falsecount -= 1# 将绘制的内容显示出来pygame.display.update()pygame.quit()