使用Python写贪吃蛇游戏

贪吃蛇游戏是一款经典的小游戏,玩家通过控制蛇的移动来吃食物,蛇的身体会随着吃到的食物越来越多而变长。本文将介绍如何使用Python来创建一个简单的贪吃蛇游戏。

代码解析

1. 设置窗口

首先,我们需要设置游戏窗口。使用 turtle.Screen() 创建一个窗口,并设置窗口的标题、背景颜色和大小。通过 window.tracer(0) 关闭自动更新屏幕,以提高性能。

python 复制代码
import turtle
import time
import random

window = turtle.Screen()

window.title("XXX")

window.bgcolor("black")

window.setup(width=800, height=600)

window.tracer(0)

2. 创建蛇头

接下来,我们创建蛇头。使用 turtle.Turtle() 创建一个 Turtle 对象,设置其速度、形状、颜色,并将其移动到屏幕中央。

python 复制代码
head = turtle.Turtle()
head.speed(0)

head.shape("square")

head.color("white")

head.direction = "stop"

3. 创建蛇身体和食物

我们使用一个列表 segments 来存储蛇的身体部分。食物也是一个 Turtle 对象,随机生成在屏幕上。

python 复制代码
segments = []

food = turtle.Turtle()
food.speed(0)

food.goto(random.randint(-14, 14) * 20, random.randint(-14, 14) * 20)

4. 移动函数

定义一个 move 函数来控制蛇的移动。根据蛇头的方向,更新其坐标。

python 复制代码
def move():
    if head.direction == "up":

    elif head.direction == "down":

    elif head.direction == "left":

    elif head.direction == "right":

5. 键盘绑定

通过键盘绑定函数来控制蛇的移动方向。使用 window.listen() window.onkeypress() 来监听键盘事件。

python 复制代码
def go_up():
    if head.direction != "down":
        head.direction = "up"
def go_down():
    if head.direction != "up":
        head.direction = "down"
def go_left():
    if head.direction != "right":
        head.direction = "left"
def go_right():
    if head.direction != "left":
        head.direction = "right"

window.listen()
window.onkeypress(go_up, "Up")
window.onkeypress(go_down, "Down")
window.onkeypress(go_left, "Left")
window.onkeypress(go_right, "Right")

6. 主循环

在主循环中,我们更新屏幕、检查边界碰撞、食物碰撞,并移动蛇的身体。通过 time.sleep(0.1 / speed) 来控制游戏速度。

python 复制代码
while True:
    window.update()

    
ruby 复制代码
if head.xcor() > 290 or head.xcor() < -290 or head.ycor() > 290 or head.ycor() < -290:
        time.sleep(1)
        head.goto(0, 0)
        head.direction = "stop"

        for segment in segments:
            segment.goto(1000, 1000)
        segments.clear()
python 复制代码
if head.distance(food) < 20:
    food.goto(random.randint(-14, 14) * 20, random.randint(-14, 14) * 20)
    new_segment = turtle.Turtle()
    new_segment.speed(0)
    new_segment.shape("square")
    new_segment.color("grey")
    new_segment.penup()
    segments.append(new_segment)
python 复制代码
for index in range(len(segments) - 1, 0, -1):
    x = segments[index - 1].xcor()
    y = segments[index - 1].ycor()
    segments[index].goto(x, y)
python 复制代码
if len(segments) > 0:
    x = head.xcor()
    y = head.ycor()
    segments[0].goto(x, y)

move()
    
python 复制代码
for segment in segments:

    if segment.distance(head) < 20:
        time.sleep(1)
        head.goto(0, 0)
        head.direction = "stop"

        for segment in segments:
            segment.goto(1000, 1000)
        segments.clear()

time.sleep(0.1 / speed)

完整代码

python 复制代码
import turtle
import time
import random

window = turtle.Screen()
window.title("贪吃蛇小游戏")
window.bgcolor("black")
window.setup(width=800, height=600)
window.tracer(0)

head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("white")
head.penup()
head.goto(0, 0)
head.direction = "stop"

segments = []

food = turtle.Turtle()
food.speed(0)
food.shape("circle")
food.color("red")
food.penup()
food.goto(random.randint(-14, 14) * 20, random.randint(-14, 14) * 20)

def move():
    if head.direction == "up":
        y = head.ycor()
        head.sety(y + 20)
    elif head.direction == "down":
        y = head.ycor()
        head.sety(y - 20)
    elif head.direction == "left":
        x = head.xcor()
        head.setx(x - 20)
    elif head.direction == "right":
        x = head.xcor()
        head.setx(x + 20)

def go_up():
    if head.direction != "down":
        head.direction = "up"
def go_down():
    if head.direction != "up":
        head.direction = "down"
def go_left():
    if head.direction != "right":
        head.direction = "left"
def go_right():
    if head.direction != "left":
        head.direction = "right"

window.listen()
window.onkeypress(go_up, "Up")
window.onkeypress(go_down, "Down")
window.onkeypress(go_left, "Left")
window.onkeypress(go_right, "Right")

speed = 0.7
while True:
    window.update()

    if head.xcor() > 290 or head.xcor() < -290 or head.ycor() > 290 or head.ycor() < -290:
        time.sleep(1)
        head.goto(0, 0)
        head.direction = "stop"

        for segment in segments:
            segment.goto(1000, 1000)
        segments.clear()

    if head.distance(food) < 20:
        food.goto(random.randint(-14, 14) * 20, random.randint(-14, 14) * 20)

        new_segment = turtle.Turtle()
        new_segment.speed(0)
        new_segment.shape("square")
        new_segment.color("grey")
        new_segment.penup()
        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 = head.xcor()
        y = head.ycor()
        segments[0].goto(x, y)

    move()

    for segment in segments:
        if segment.distance(head) < 20:
            time.sleep(1)
            head.goto(0, 0)
            head.direction = "stop"

            for segment in segments:
                segment.goto(1000, 1000)
            segments.clear()

    time.sleep(0.1 / speed)

通过以上步骤,我们成功创建了一个简单的贪吃蛇游戏。后续可以根据需要进一步优化和扩展游戏功能,例如增加得分系统、难度级别等!

相关推荐
懒大王爱吃狼39 分钟前
Python教程:python枚举类定义和使用
开发语言·前端·javascript·python·python基础·python编程·python书籍
秃头佛爷2 小时前
Python学习大纲总结及注意事项
开发语言·python·学习
待磨的钝刨2 小时前
【格式化查看JSON文件】coco的json文件内容都在一行如何按照json格式查看
开发语言·javascript·json
深度学习lover3 小时前
<项目代码>YOLOv8 苹果腐烂识别<目标检测>
人工智能·python·yolo·目标检测·计算机视觉·苹果腐烂识别
XiaoLeisj4 小时前
【JavaEE初阶 — 多线程】单例模式 & 指令重排序问题
java·开发语言·java-ee
API快乐传递者4 小时前
淘宝反爬虫机制的主要手段有哪些?
爬虫·python
励志成为嵌入式工程师5 小时前
c语言简单编程练习9
c语言·开发语言·算法·vim
逐·風5 小时前
unity关于自定义渲染、内存管理、性能调优、复杂物理模拟、并行计算以及插件开发
前端·unity·c#
捕鲸叉5 小时前
创建线程时传递参数给线程
开发语言·c++·算法
Devil枫5 小时前
Vue 3 单元测试与E2E测试
前端·vue.js·单元测试