贪吃蛇列表版

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

class Block(Turtle):
    xspeed = 4
    yspeed = 0
    def __init__(self,position):
        Turtle.__init__(self,shape='square',visible=False)
        self.penup()
        self.width = 20
        self.height = 20
        self.goto(position)
        self.st() 

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
    

You must log in to read the rest of this article. Please log in or register as a user.