做了不少贪吃蛇游戏,温故而创新。做好任何一件事,整理也是必要的,还包括计算机电脑文件的分门别类与备份等。下次做一个贪吃蛇专辑,应该在2022年元旦后就有点时间做了。这个版本是海龟的纯画笔版本,定义了一个叫Square的类。第一个实例化的方块表示蛇的头,其它的方块表示蛇的身体。默认的海龟负责渲染画面出来。此版本只有蛇,没有蛇吃的食物,能操作蛇上下左右移动,具备贪吃蛇游戏的核心代码。以下是代码:
"""
2021/12/10纯画笔贪吃蛇教学版本.py
"""
import turtle
def draw_rect(length,x,y):
turtle.goto(x,y)
turtle.bk(length/2)
turtle.sety(turtle.ycor()+length/2)
turtle.begin_fill()
for _ in range(4):
turtle.fd(length)
turtle.right(90)
turtle.end_fill()
turtle.sety(turtle.ycor()-length/2)
turtle.fd(length/2)
def draw_snakes():
for snk in Square.bodies:
draw_rect(snk.length,snk.x,snk.y)
class Square:
bodies = []
def __init__(self,length,x,y):
"""length:边长,x,y是中心点坐标"""
self.length = length
self.x = x
self.y = y
self.dx = 2
self.dy = 0
def toward_left(self):
self.dx = -2
self.dy = 0
def toward_right(self):
self.dx = 2
self.dy = 0
def toward_up(self):
self.dx = 0
self.dy = 2
def toward_down(self):
self.dx = 0
self.dy = -2
def move(self):
self.x += self.dx
self.y += self.dy
def stamp(self):
sq = Square(self.length,self.x,self.y)
Square.bodies.append(sq)
def clearstamps(self,n):
Square.bodies = Square.bodies[n:]
turtle.tracer(0,0)
turtle.speed(0)
turtle.penup()
# 以下代码实例化蛇头和初始的40个蛇身体。需要浏览更多吗?
成为会员后,登陆才能继续浏览!联系微信scratch8即可办理会员。
(会员专属:能浏览所有文章,下载所有带链接的Python资源。)
