使用turtle模块的贪食蛇游戏

蛇是一款街机迷宫游戏,由格莱姆林工业公司开发,世嘉公司于 1976 年 10 月出版。它被认为是一款优秀的游戏,已经在大众中流行了好几代。蛇的游戏可以通过四个方向按钮来控制方向。玩这个游戏的目的是通过抓取食物或水果来获得最高分。如果蛇撞到墙或自己,玩家就倒霉了。

对于 Python 初学者和那些试图在自己的领域创造更简单的东西的人来说,可以测试这个程序。这个名为turtle的模块是专门为初学者设计的,他们可以玩这个项目并提交一个项目的程序。本项目使用 Python 3.0 编写。

因此,我们将用这些模块创建一个基于 Python 的游戏。

  • Turtle: 这是一个安装好的 Python 库,通过为用户提供一个虚拟画布,用户可以绘制图案和图像。
  • 时间:用于计算事件发生之日起的秒数。
  • Random: 这是一个通过使用random模块在 Python 中创建随机数的函数。

支持

下面的代码可以通过使用专门为 Python 程序设计的崇高文本应用轻松工作。

此外,还可以使用 VSCode 来使用这个程序。利用 VSCode 的扩展安装 Python3。然后,以您的 _filename.py 格式保存 Python3 程序

以下是使用turtle模块制作贪食蛇游戏的分步方法:

第一步。给程序增加模块,然后给每个游戏一个初始值。


import turtle as ttl
import time
import random as rdm

delay = 0.1
score = 0
high_score = 0

第二步:我们将创建这个游戏的显示,也就是游戏的屏幕,在这里我们将创建蛇的头部和食物项目,供蛇在游戏中食用,并将分数显示在游戏的顶部。


# Here we will creating a window screen
w_n = ttl.Screen()
w_n.title("Snake Game JavaTpoint")
w_n.bgcolor("black")

# The width and height can be put as user's choice
w_n.setup(width = 650, height = 650)
w_n.tracer(0)

# Here, we will create the head of the snake
head1 = ttl.Turtle()
head1.shape("circle")
head1.color("white")
head1.penup()
head1.goto(0, 0)
head1.direction = "Stop"

# Here, we will create the food in the game
food1 = ttl.Turtle()
colors = rdm.choice(['pink', 'yellow', 'blue'])
shapes = rdm.choice(['triangle', 'square', 'circle'])
food1.speed(0)
food1.shape(shapes)
food1.color(colors)
food1.penup()
food1.goto(0, 100)

pen1 = ttl.Turtle()
pen1.speed(0)
pen1.shape("square")
pen1.color("white")
pen1.penup()
pen1.hideturtle()
pen1.goto(0, 250)
pen1.write("Score: 0  High Score: 0", align ="center",
          font = ("Consolas", 22, "bold"))

输出:

第三步:我们来验证控制蛇运动的按键。当我们点击游戏中常用的术语,如“e”、“s”、“f”和“v”,我们将能够控制蛇在屏幕上的移动。


# Here, we will assign the key directions
def group1():
    if head1.direction != "down":
        head1.direction = "up"

def go_down():
    if head1.direction != "up":
        head1.direction = "down"

def go_left():
    if head1.direction != "right":
        head1.direction = "left"

def go_right():
    if head1.direction != "left":
        head1.direction = "right"

def move1():
    if head1.direction == "up":
        y1 = head1.ycor()
        head1.sety(y1 + 20)
    if head1.direction == "down":
        y1 = head1.ycor()
        head1.sety(y1 - 20)
    if head1.direction == "left":
        x1 = head1.xcor()
        head1.setx(x1 - 20)
    if head1.direction == "right":
        x1 = head1.xcor()
        head1.setx(x1 + 20)

w_n.listen()
w_n.onkeypress(group1, "e")
w_n.onkeypress(go_down, "v")
w_n.onkeypress(go_left, "s")
w_n.onkeypress(go_right, "f")

第四步:我们将设计一个游戏,其中会发生以下事情:

  • 吃了水果后,蛇的身体会膨胀。
  • 给蛇的尾巴上色。
  • 当水果吃完后,分数就会被记录下来。
  • 检查蛇的头部是否与身体或屏幕侧面碰撞。
  • 碰撞后游戏会立即自动重启。
  • 每次打开窗户,这种水果的新设计和形状就会显现出来。
  • 分数将被重置为零,最高分数将一直保持到窗口没有关闭。

# Code for main gameplay
while True:
    w_n.update()
    if head1.xcor() > 295 or head1.xcor() < -295 or head1.ycor() > 290 or head1.ycor() < -295:
        time.sleep(1)
        head1.goto(0, 0)
        head1.direction = "Stop"
        colors = rdm.choice(['pink', 'blue', 'yellow'])
        shapes = rdm.choice(['square', 'circle'])
        for segment1 in segments1:
            segment1.goto(1050, 1050)
        segments1.clear()
        score = 0
        delay = 0.1
        pen1.clear()
        pen1.write("Score : {} High Score : {} ".format(
            score, high_score), align = "center", font = ("Consoles", 22, "bold"))
    if head1.distance(food1) < 20:
        x = rdm.randint(-275, 275)
        y = rdm.randint(-275, 275)
        food1.goto(x, y)

        # Here, we are adding segment
        new_segment1 = ttl.Turtle()
        new_segment1.speed(0)
        new_segment1.shape("square")
        new_segment1.color("orange")  # tail colour
        new_segment1.penup()
        segments.append(new_segment1)
        delay -= 0.001
        score += 10
        if score > high_score:
            high_score = score
        pen1.clear()
        pen1.write("Score: {} High Score: {} ".format(
            score, high_score), align = "center", font = ("Consoles", 22, "bold"))
    # Checking for head collisions with body segments
    for index in range(len(segments1)-1, 0, -1):
        x = segments1[index-1].xcor()
        y = segments1[index-1].ycor()
        segments1[index].goto(x, y)
    if len(segments1) > 0:
        x1 = head1.xcor()
        y1 = head1.ycor()
        segments1[0].goto(x1, y1)
    move()
    for segment1 in segments1:
        if segment1.distance(head1) < 20:
            time.sleep(1)
            head1.goto(0, 0)
            head1.direction = "stop"
            colors = rdm.choice(['pink', 'blue', 'yellow'])
            shapes = rdm.choice(['square', 'triangle'])
            for segment1 in segments1:
                segment1.goto(1050, 1050)
            segment1.clear()

            score = 0
            delay = 0.1
            pen1.clear()
            pen1.write("Score: {} High Score: {} ".format(
                score, high_score), align = "center", font = ("Consoles", 22, "bold"))
    time.sleep(delay)

w_n.mainloop()

下面是贪食蛇游戏代码的完整实现


import turtle as ttl
import time
import random as rdm

delay = 0.1
score = 0
high_score = 0

# Here we will be creating a window screen
w_n = ttl.Screen()
w_n.title("Snake Game JavaTpoint")
w_n.bgcolor("black")

# The width and height can be put as user's choice
w_n.setup(width = 650, height = 650)
w_n.tracer(0)

# Here, we will create the head of the snake
head1 = ttl.Turtle()
head1.shape("circle")
head1.color("white")
head1.penup()
head1.goto(0, 0)
head1.direction = "Stop"

# Here, we will create the food in the game
food1 = ttl.Turtle()
colors = rdm.choice(['pink', 'yellow', 'blue'])
shapes = rdm.choice(['triangle', 'square', 'circle'])
food1.speed(0)
food1.shape(shapes)
food1.color(colors)
food1.penup()
food1.goto(0, 100)

pen1 = ttl.Turtle()
pen1.speed(0)
pen1.shape("square")
pen1.color("white")
pen1.penup()
pen1.hideturtle()
pen1.goto(0, 250)
pen1.write("Score: 0, High Score: 0", align = "center",
          font = ("Consoles", 22, "bold"))
# Here, we will assign the key directions
def group1():
    if head1.direction != "down":
        head1.direction = "up"

def go_down():
    if head1.direction != "up":
        head1.direction = "down"

def go_left():
    if head1.direction != "right":
        head1.direction = "left"

def go_right():
    if head1.direction != "left":
        head1.direction = "right"

def move():
    if head1.direction == "up":
        y1 = head1.ycor()
        head1.sety(y1 + 20)
    if head1.direction == "down":
        y1 = head1.ycor()
        head1.sety(y1 - 20)
    if head1.direction == "left":
        x1 = head1.xcor()
        head1.setx(x1 - 20)
    if head1.direction == "right":
        x1 = head1.xcor()
        head1.setx(x1 + 20)

w_n.listen()
w_n.onkeypress(group1, "e")
w_n.onkeypress(go_down, "v")
w_n.onkeypress(go_left, "s")
w_n.onkeypress(go_right, "f")

segments1 = []

# Code for main gameplay
while True:
    w_n.update()
    if head1.xcor() > 290 or head1.xcor() < -290 or head1.ycor() > 290 or head1.ycor() < -290:
        time.sleep(1)
        head1.goto(0, 0)
        head1.direction = "Stop"
        colors = rdm.choice(['pink', 'blue', 'yellow'])
        shapes = rdm.choice(['square', 'triangle'])
        for segment1 in segments1:
            segment1.goto(1050, 1050)
        segments1.clear()
        score = 0
        delay = 0.1
        pen1.clear()
        pen1.write("Score: {} High Score: {} ".format(
            score, high_score), align = "center", font = ("candara", 24, "bold"))
    if head1.distance(food1) < 20:
        x1 = rdm.randint(-275, 275)
        y1 = rdm.randint(-275, 275)
        food1.goto(x1, y1)

        # Here, we are adding segment
        new_segment1 = ttl.Turtle()
        new_segment1.speed(0)
        new_segment1.shape("square")
        new_segment1.color("orange")  # tail colour
        new_segment1.penup()
        segments1.append(new_segment1)
        delay -= 0.001
        score += 10
        if score > high_score:
            high_score = score
        pen1.clear()
        pen1.write("Score : {} High Score : {} ".format(
            score, high_score), align = "center", font = ("Consoles", 22, "bold"))
    # Checking for head collisions with body segments
    for index in range(len(segments1)-1, 0, -1):
        x1 = segments1[index - 1].xcor()
        y1 = segments1[index - 1].ycor()
        segments1[index].goto(x1, y1)
    if len(segments1) > 0:
        x1 = head1.xcor()
        y1 = head1.ycor()
        segments1[0].goto(x1, y1)
    move()
    for segment1 in segments1:
        if segment1.distance(head1) < 20:
            time.sleep(1)
            head1.goto(0, 0)
            head1.direction = "stop"
            colors = rdm.choice(['pink', 'blue', 'yellow'])
            shapes = rdm.choice(['square', 'triangle'])
            for segment1 in segments1:
                segment1.goto(1050, 1050)
            segment1.clear()

            score = 0
            delay = 0.1
            pen1.clear()
            pen1.write("Score: {} High Score: {} ".format(
                score, high_score), align = "center", font = ("Consoles", 22, "bold"))
    time.sleep(delay)

w_n.mainloop()

输出:


原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/270119.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
小蓝小蓝
上一篇 2024-12-16 13:35
下一篇 2024-12-16 13:35

相关推荐

  • 为什么不用Python开发游戏

    Python是一种高级编程语言,拥有简单易学、代码简洁等优点。同时,Python也是一种多用途的语言,可以用于Web开发、数据分析以及机器学习等领域。然而,对于游戏开发领域,Pyt…

    编程 2025-04-29
  • 光模块异常,SFP未认证(entityphysicalindex=6743835)——解决方案和

    如果您遇到类似optical module exception, sfp is not certified. (entityphysicalindex=6743835)的问题,那么…

    编程 2025-04-29
  • 使用Python制作游戏代码

    Python是一种高级编程语言,因其简洁明了的代码风格、易于学习和使用而备受青睐。Python已经成为游戏制作的热门选择之一,可以通过Pygame、Panda3D等工具来实现游戏制…

    编程 2025-04-29
  • Python模块下载与安装指南

    如果想要扩展Python的功能,可以使用Python模块来实现。但是,在使用之前,需要先下载并安装对应的模块。本文将从以下多个方面对Python模块下载与安装进行详细的阐述,包括使…

    编程 2025-04-29
  • Python Turtle + Tkinter开发用法介绍

    Python是一种高级编程语言,生态繁荣,功能强大。Turtle和Tkinter分别是Python自带的画图和GUI程序开发模块,它们为Python的应用开发提供了许多便利。这篇文…

    编程 2025-04-29
  • Python编程三剑客——模块、包、库

    本文主要介绍Python编程三剑客:模块、包、库的概念、特点、用法,以及在实际编程中的实际应用,旨在帮助读者更好地理解和应用Python编程。 一、模块 1、概念:Python模块…

    编程 2025-04-29
  • 如何使用pip安装模块

    pip作为Python默认的包管理系统,是安装和管理Python包的一种方式,它可以轻松快捷地安装、卸载和管理Python的扩展库、模块等。下面从几个方面详细介绍pip的使用方法。…

    编程 2025-04-28
  • Python如何下载第三方模块

    想要使Python更加强大且具备跨平台性,我们可以下载许多第三方模块。下面将从几个方面详细介绍如何下载第三方模块。 一、使用pip下载第三方模块 pip是Python的软件包管理器…

    编程 2025-04-28
  • import turtle在Python中的用法用法介绍

    本文将从多个方面对import turtle在Python中的用法进行详细的阐述,包括基础操作、图形绘制、颜色设置、图形控制和turtle实例等,帮助读者更好的了解和使用turtl…

    编程 2025-04-28
  • Python datetime和time模块用法介绍

    本文将详细阐述Python datetime和time模块的用法和应用场景,以帮助读者更好地理解和运用这两个模块。 一、datetime模块 datetime模块提供了处理日期和时…

    编程 2025-04-28

发表回复

登录后才能评论