用ji写一个贪吃蛇代码
时间: 2023-03-15 15:15:18 浏览: 93
import turtlescreen = turtle.Screen()
screen.title('贪吃蛇')
screen.bgcolor('green')snake = turtle.Turtle()
snake.speed(0)
snake.penup()
snake.shape('square')
snake.color('white')
snake.goto(0, 0)
snake.direction = 'stop'food = turtle.Turtle()
food.speed(0)
food.penup()
food.shape('circle')
food.color('red')
food.goto(0, 100)segments = []def go_up():
snake.direction = 'up'def go_down():
snake.direction = 'down'def go_left():
snake.direction = 'left'def go_right():
snake.direction = 'right'def move():
if snake.direction == 'up':
y = snake.ycor()
snake.sety(y + 20) if snake.direction == 'down':
y = snake.ycor()
snake.sety(y - 20) if snake.direction == 'left':
x = snake.xcor()
snake.setx(x - 20) if snake.direction == 'right':
x = snake.xcor()
snake.setx(x + 20)screen.listen()
screen.onkeypress(go_up, 'Up')
screen.onkeypress(go_down, 'Down')
screen.onkeypress(go_left, 'Left')
screen.onkeypress(go_right, 'Right')while True:
screen.update() if snake.distance(food) < 20:
x = random.randint(-290, 290)
y = random.randint(-290, 290)
food.goto(x, y) new_segment = turtle.Turtle()
new_segment.speed(0)
new_segment.penup()
new_segment.shape('square')
new_segment.color('grey')
segments.append(new_segment) for index in range(len(segments)-1, 0, -1):
x = segments[index-1].xcor()
y = segments[index-1].ycor()
segments[index].goto(x, y) if len(segments) > 0:
x = snake.xcor()
y = snake.ycor()
segments[0].goto(x, y) move() for segment in segments:
if segment.distance(snake) < 20:
time.sleep(1)
snake.goto(0, 0)
snake.direction = 'stop' for segment in segments:
segment.goto(1000, 1000)
segments.clear() time.sleep(delay)screen.mainloop()
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)