使用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/zh-tw/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

發表回復

登錄後才能評論