自己弄的python小游戲,turtle實現海龜賽跑


廢話不多說,直接開始拉~~~

我們總共有 6 只海龜,顏色不同,它們以隨機長度移動。首先,我們應該通過輸入烏龜的顏色來押注烏龜。第一個越線的烏龜被宣布為獲勝者。整個代碼是通過導入海龜和隨機庫在 Python 中完成的。

代碼說明

導入包

from turtle import Turtle, Screen
import random

random 函數用於生成距離(隨機),由海龜移動。最好給出屏幕尺寸,因為我們很容易找到坐標並進行相應的更改。

screen = Screen()
screen.setup(width=500, height=400)

有一個名為 textinput() 的函數,它會打開一個對話框並要求用戶輸入。

user_bet = screen.textinput(title="Place your bet", prompt="Which turtle will win the race? Enter a color: ")

接下來,我們應該給我們的種族海龜顏色。所以,我們可以區分它們。以及然后應該代表比賽的坐標。

colors = ["red", "orange", "yellow", "green", "blue", "purple"]
y_positions = [-100, -60, -20, 20, 60, 100]

通過考慮上述 y 坐標和顏色,使用 for 循環對所有海龜的確切坐標進行分類。

for turtle_index in range(0,6):
    new_turtle = Turtle(shape="turtle")
    new_turtle.color(colors[turtle_index])
    new_turtle.penup()
    new_turtle.goto(x=-230, y= y_positions[turtle_index])
    all_turtles.append(new_turtle)

現在,我們應該做的最后一件事是讓我們的海龜每次移動一個隨機距離。而最先到達屏幕另一端的烏龜就是贏得比賽的烏龜。一開始,我們對烏龜下注,如果烏龜贏了,我們就贏了,如果它輸了,我們也輸了。

while is_race_on:
    for turtle in all_turtles:
        if turtle.xcor() > 230:
            is_race_on = False
            winning_color = turtle.pencolor()
            if winning_color == user_bet:
                print(f"You've won!, The {winning_color} turtle is the winner.")
            else:
                print(f"You've lost!, The {winning_color} turtle is the winner.")
        rand_distance = random.randint(0, 10)
        turtle.forward(rand_distance)

設置屏幕寬度和高度的主要優點是我們可以通過假設屏幕為方格紙輕松計算開始和結束坐標。

輸出圖像

  • A. 將“紅色”作為用戶輸入。

  • B. 海龜如何移動的圖像。

  • C. 游戲結束。這說明我們是贏了還是輸了比賽。

好了~~~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM