用Python如何写一个贪吃蛇游戏
时间: 2024-04-25 17:04:06 浏览: 60
您可以使用 Python 编写一个贪吃蛇游戏,具体实现如下:
1. 导入必要的库:
```python
import turtle
import time
import random
```
2. 创建游戏窗口:
```python
win = turtle.Screen()
win.title("Snake Game")
win.bgcolor("black")
win.setup(width=600, height=600)
```
3. 创建蛇头,食物和分数:
```python
snake = turtle.Turtle()
snake.speed(0)
snake.shape("square")
snake.color("white")
snake.penup()
snake.goto(0, 0)
snake.direction = "stop"
food = turtle.Turtle()
food.speed(0)
food.shape("circle")
food.color("red")
food.penup()
food.goto(0, 100)
score = turtle.Turtle()
score.speed(0)
score.color("white")
score.penup()
score.hideturtle()
score.goto(0, 260)
score.write("Score: 0", align="center", font=("Courier", 24, "normal"))
```
4. 定义蛇的移动函数:
```python
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 == "right":
x = snake.xcor()
snake.setx(x + 20)
if snake.direction == "left":
x = snake.xcor()
snake.setx(x - 20)
```
5. 定义蛇的方向控制函数:
```python
def go_up():
if snake.direction != "down":
snake.direction = "up"
def go_down():
if snake.direction != "up":
snake.direction = "down"
def go_right():
if snake.direction != "left":
snake.direction = "right"
def go_left():
if snake.direction != "right":
snake.direction = "left"
```
6. 绑定键盘事件:
```python
win.listen()
win.onkeypress(go_up, "Up")
win.onkeypress(go_down, "Down")
win.onkeypress(go_right, "Right")
win.onkeypress(go_left, "Left")
```
7. 播放游戏:
```python
while True:
win.update()
if snake.xcor() > 290 or snake.xcor() < -290 or snake.ycor() > 290 or snake.ycor() < -290:
time.sleep(1)
snake.goto(0, 0)
snake.direction = "stop"
score.clear()
score.write("Score: {}".format(0), align="center", font=("Courier", 24, "normal"))
# 隐藏尾巴
for segment in segments:
segment.goto(1000, 1000)
# 清空尾巴列表
segments.clear()
if snake.distance(food) < 20:
x = random.randint(-280, 280)
y = random.randint(-280, 280)
food.goto(x, y)
new_segment = turtle.Turtle()
new_segment.speed(0)
new_segment.shape("square")
new_segment.color("grey")
new_segment.penup()
segments.append(new_segment)
score_count += 10
score.clear()
score.write("Score: {}".format(score_count), align="center", font=("Courier", 24, "normal"))
# 显示尾巴
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"
score.clear()
score.write("Score: {}".format(0), align="center", font=("Courier", 24, "normal"))
# 隐藏尾巴
for segment in segments:
segment.goto(1000, 1000)
# 清空尾巴列表
segments.clear()
score_count = 0
score.clear()
score.write("Score: {}".format(score_count), align="center", font=("Courier", 24, "normal"))
time.sleep(delay)
```
以上就是用 Python 写一个贪吃蛇游戏的详细过程。
阅读全文