马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import pygame
import random
import copy
snake_list = [[70,30]]
food_point = [random.randint(10,490),random.randint(10,490)]
#一开始向下移动
move_up = False
move_down = True
move_left = False
move_right = False
'''初始化游戏'''
pygame.init()
clock = pygame.time.Clock()#刷新帧率
screen = pygame.display.set_mode((500,500))#设置屏幕大小颜色
pygame.display.set_caption('贪吃蛇小游戏')#绘制标题
'''进入游戏,玩游戏'''
running = True#设置游戏开关
while running:
clock.tick(20)#20帧
screen.fill([255,255,255])#绘制白色屏幕
# 键盘控制方向
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
food_rect = pygame.draw.circle(screen,[255,0,0],food_point,10,0)#绘制食物
#绘制蛇的body
snake_rect = []
for pos in snake_list:
snake_rect_point = pygame.draw.circle(screen,[0,0,255],pos,10,0)
snake_rect.append(snake_rect_point)
#检测碰撞
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, 10, 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
#撞自己
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()#显示绘制内容
print('游戏结束')
pygame.quit()
第62行.
你吧蛇的位置设置成了食物的位置.
而食物的位置上本来就有蛇.这样他就认为蛇自己撞自己了
|