烏龜賽跑小遊戲
Turtle模組文件介紹 : turtle — Turtle graphics — Python 3.9.1 documentation
主要設定
1.先import turtle 模組 和 random模組
2.設定一個list裡面裝著 紅、橙、黃、綠、藍、紫,共六個顏色
3.將class實體化為object ex: screen = Screen()
4.先製造一個空的list,然後用迴圈將每只我們設定的烏龜裝進去
5.用while loop去偵測是否有烏龜到達邊界(終點),以及每只烏龜該走的隨機步伐(用random模組)
程式碼:
#模組
from turtle import Turtle,Screen
import random
#烏龜顏色設定
color= ["red","orange","yellow","green","blue","purple"]
#將class實體化為object
screen = Screen()
#標題設定
screen.title("turtle running race")
#input視窗設定以及視窗大小設定
guess = screen.textinput("guess which color of turtle will win","guess a color red /orange /yellow /green /blue /purple ?")
screen.setup(width=500,height=400)
#製造6種不同顏色烏龜的function
def all():
all_turtle = []
for i in range(6):
t = Turtle(shape="turtle")
t.color(color[i])
t.penup()
t.goto(-230,-150+i*50)
all_turtle.append(t)
return all_turtle
#迴圈的條件
goon = False
#如果使用者輸入,迴圈就開始
if guess:
goon = True
turtle_list = all()
#偵測烏龜是否到終點以及烏龜每一次走的隨機步伐多大
while goon:
for i in turtle_list:
num = random.randint(1,10)
i.forward(num)
if i.xcor() > 230:
if guess == i.pencolor():
print(f"you got it right the winner is {i.pencolor()}.")
else:
print(f"you got it wrong the winner is {i.pencolor()}.")
again = screen.textinput("try again","yes or no ?")
if again.lower()=='yes':
screen.clearscreen()
screen.reset()
guess = screen.textinput("guess which color of turtle will win","guess a color red /orange /yellow /green /blue /purple ?")
turtle_list = all()
else:
goon = False
#視窗設定
screen.exitonclick()
留言
張貼留言