创建蛇类和食物类,并在画布上绘制它们。
时间: 2024-05-02 18:21:44 浏览: 46
以下是Python代码,用于创建蛇类和食物类,并在画布上绘制它们:
```
import turtle
import random
# 创建蛇类
class Snake:
def __init__(self):
self.body = []
self.create_snake()
self.head = self.body[0]
def create_snake(self):
for i in range(3):
segment = turtle.Turtle()
segment.shape("square")
segment.color("white")
segment.penup()
if i != 0:
segment.goto(self.body[i-1].xcor()-20, self.body[i-1].ycor())
self.body.append(segment)
def move(self):
for i in range(len(self.body)-1, 0, -1):
x = self.body[i-1].xcor()
y = self.body[i-1].ycor()
self.body[i].goto(x, y)
self.head.forward(20)
def up(self):
if self.head.heading() != 270:
self.head.setheading(90)
def down(self):
if self.head.heading() != 90:
self.head.setheading(270)
def left(self):
if self.head.heading() != 0:
self.head.setheading(180)
def right(self):
if self.head.heading() != 180:
self.head.setheading(0)
# 创建食物类
class Food:
def __init__(self):
self.food = turtle.Turtle()
self.food.shape("circle")
self.food.color("red")
self.food.penup()
self.food.goto(random.randint(-290, 290), random.randint(-290, 290))
def regenerate(self):
self.food.goto(random.randint(-290, 290), random.randint(-290, 290))
# 创建游戏界面
wn = turtle.Screen()
wn.setup(width=600, height=600)
wn.bgcolor("black")
wn.title("Snake Game")
# 创建蛇和食物对象
snake = Snake()
food = Food()
# 蛇和食物的动作
wn.listen()
wn.onkeypress(snake.up, "Up")
wn.onkeypress(snake.down, "Down")
wn.onkeypress(snake.left, "Left")
wn.onkeypress(snake.right, "Right")
# 游戏循环
while True:
wn.update()
# 判断蛇是否吃到了食物
if snake.head.distance(food.food) < 20:
food.regenerate()
# 加长蛇的身体
segment = turtle.Turtle()
segment.shape("square")
segment.color("white")
segment.penup()
snake.body.append(segment)
snake.move()
# 判断蛇是否撞墙
if snake.head.xcor() > 290 or snake.head.xcor() < -290 or snake.head.ycor() > 290 or snake.head.ycor() < -290:
print("Game Over")
break
# 判断蛇是否撞到了自己
for segment in snake.body[1:]:
if snake.head.distance(segment) < 10:
print("Game Over")
break
turtle.done()
```
在上述代码中,我们使用了turtle模块来创建蛇和食物对象,并在画布上绘制它们。蛇类包含了创建蛇、移动、改变方向等方法,食物类包含了创建食物、重新生成食物等方法。游戏界面的创建和游戏循环的实现也包含在代码中。在游戏循环中,我们不断更新画布,同时判断蛇是否吃到了食物、是否撞墙、是否撞到了自己等情况,以实现游戏的逻辑。最后,我们使用`turtle.done()`来让程序保持运行状态,直到我们手动关闭游戏窗口。
阅读全文