贪吃蛇代码
import pygame
import random
import copy
'''
首先设置蛇的一个运行方向 接下来判断键盘事件在决定蛇的运行方向
蛇可以运行起来了 那么接下来就是 吃食物增加自己的长度 和 不吃食物在不同的位置显示
'''
move_up = False
move_down = False
move_left = False
move_right = True
pygame.init()
clock = pygame.time.Clock()
pygame.display.set_caption("贪吃蛇")
screen = pygame.display.set_mode((500, 500))
snake_list = [[10, 10]]
x = random.randint(10, 490)
y = random.randint(10, 490)
food_point = [x, y]
running = True
while running:
clock.tick(20)
screen.fill([255, 255, 255])
for x in range(0, 501, 10):
pygame.draw.line(screen, (195, 197, 199), (x, 0), (x, 500), 1)
pygame.draw.line(screen, (195, 197, 199), (0, x), (500, x), 1)
food_rect = pygame.draw.circle(screen, [255, 0, 0], food_point, 15, 0)
snake_rect = []
for pos in snake_list:
snake_rect.append(pygame.draw.circle(screen, [255, 0, 0], pos, 5, 0))
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, 15, 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] -= 10
if snake_list[pos][1] < 0:
snake_list[pos][1] = 500
if move_down:
snake_list[pos][1] += 10
if snake_list[pos][1] > 500:
snake_list[pos][1] = 0
if move_left:
snake_list[pos][0] -= 10
if snake_list[pos][0] < 0:
snake_list[pos][0] = 500
if move_right:
snake_list[pos][0] += 10
if snake_list[pos][0] > 500:
snake_list[pos][0] = 0
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
move_up = True
move_down = False
move_left = False
move_right = False
if event.key == pygame.K_DOWN:
move_up = False
move_down = True
move_left = False
move_right = False
if event.key == pygame.K_LEFT:
move_up = False
move_down = False
move_left = True
move_right = False
if event.key == pygame.K_RIGHT:
move_up = False
move_down = False
move_left = False
move_right = True
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()