贪吃蛇列表版

"""
   贪吃蛇列表版.py
   贪吃蛇游戏真正的原理是维护一个先进先出的列表。不断地在列表末尾删除项目,然后又不断地在列表前面加入新的项目。
   这就是贪吃蛇真正的原理。本程序演示的就是这个原理。
"""
from turtle import *
from time import sleep

本文隐藏内容 登陆 后才可以浏览
screen = Screen() screen.delay(2) all_sprites = [] for i in range(5): # 贪吃蛇初始为5段 position = (-160 - i*24,0) all_sprites.append(Block(position)) sleep(0.001) def move_left(): Block.xspeed = -4 Block.yspeed = 0 def move_right(): Block.xspeed = 4 Block.yspeed = 0 def move_up(): Block.xspeed = 0 Block.yspeed = 4 def move_down(): Block.xspeed = 0 Block.yspeed = -4 def spawn(): """在列表最前面生成一个方块""" x = all_sprites[0].xcor() + Block.xspeed * 6 y = all_sprites[0].ycor() + Block.yspeed * 6 all_sprites.insert(0,Block((x,y))) screen.onkeypress(move_left,"Left") screen.onkeypress(move_right,"Right") screen.onkeypress(move_up,"Up") screen.onkeypress(move_down,"Down") screen.onkeypress(spawn,"space") screen.listen() while True: x = all_sprites[0].xcor() + Block.xspeed * 6 y = all_sprites[0].ycor() + Block.yspeed * 6 body = all_sprites.pop() # 弹出最后的方块 body.ht() del body all_sprites.insert(0,Block((x,y)))# 在最前面添加新方块 sleep(0.1)