2014-12-13 64 views
0

我正在做一個使用烏龜模塊的任務,我在其中創建一個基於文本的遊戲。我對一般的代碼和python相當陌生,我想模擬使用鼠標按下的按鈕。從查看其他線程,我相當確定可以通過將烏龜移動到鼠標點擊,然後根據python是否位於指定區域內執行一個操作,這將在視覺上作爲按鈕進行說明。因爲我沒有經驗,所以我不確定如何指定座標並檢查龜是否在其中。Python-Turtle-有效地重新創建按鈕

這是我開始的:

from turtle import * 
import turtle as t 
from time import sleep 
import time as time 

pen= Turtle() 
bt=pen.clone() 
bt.pu() 
bt.setpos(-200,-200) 
menu=0 

pen.pu() 
pen.setpos(0,50) 
pen.write("1.Option1",align="center",font=("Chiller",40)) 
time.sleep(0.5) 

pen.setpos(0,-30) 
pen.write("2.Option2",align="center",font=("Chiller",40)) 
time.sleep(0.5) 

pen.setpos(0,-110) 
pen.write("3.Option3",align="center",font=("Chiller",40)) 
menu=1 

while menu==1: 
    screen= Screen() 
    screen.onscreenclick(bt.goto) 
    bt.getscreen()._root.mainloop() 
while menu==1: 
    if bt.xcor>(-200) and bt.xcor<(200): 
     if bt.ycor>(20) and bt.ycor<(80): 
      pen.clear() 
      pen.write("option 1") 
     elif bt.ycor>(-60) and bt.ycor<(0): 
      pen.clear() 
      pen.write("option 2") 
     elif bt.ycor>(-140) and bt.ycor<(-80): 
      pen.clear() 
      pen.write("option 3") 

正如我所說的,白癡的語言,將不勝感激;有人能告訴我爲什麼這不起作用,並可能提供解決方案。另外,我不完全知道什麼是「屏幕=屏幕()」絲毫,我只是覺得在不同的線程,並實現了它......

預先感謝任何幫助

+0

什麼不起作用?它看起來像你的縮進是關閉的... – 2014-12-13 17:08:48

+1

你見過PyGame了嗎? – 2014-12-13 17:09:35

+0

歡迎來到StackOverflow。 在你的問題中,請具體說明什麼不工作,你的輸出,你想要的輸出以及你可能得到的錯誤(如果有的話)。 – kartikg3 2014-12-13 17:16:14

回答

0

是,這可以做到。 (無論是應該做的是另外一個問題。)下面是當您單擊的三個選項之一演示代碼,改變在屏幕底部的文字:

from turtle import Turtle, Screen 

FONTSIZE = 40 
FONT = ("Ariel", FONTSIZE, "normal") 

turtle = Turtle(visible=False) 
turtle.penup() 

turtle.setpos(0, FONTSIZE*2 - FONTSIZE/2) 
turtle.write("1.Option1", align="center", font=FONT) 

turtle.setpos(0, -FONTSIZE/2) 
turtle.write("2.Option2", align="center", font=FONT) 

turtle.setpos(0, -FONTSIZE*2 - FONTSIZE/2) 
turtle.write("3.Option3", align="center", font=FONT) 

turtle.setpos(-200, -200) 
turtle.write("Select an Option", font=FONT) 

def onclick_handler(x, y): 
    if -100 < x < 100: 
     if FONTSIZE < y < FONTSIZE*3: 
      turtle.undo() 
      turtle.write("Option 1", font=FONT) 
     elif -FONTSIZE < y < FONTSIZE: 
      turtle.undo() 
      turtle.write("Option 2", font=FONT) 
     elif -FONTSIZE*3 < y < -FONTSIZE: 
      turtle.undo() 
      turtle.write("Option 3", font=FONT) 

screen = Screen() 
screen.onscreenclick(onclick_handler) 
screen.mainloop() 

您的原始代碼它有一個無限循環這使事情變得複雜 - 你不應該在烏龜計劃中出現無限循環。您不必讓點擊處理程序移動烏龜,然後通過無限循環檢測烏龜的菜單位置,只需讓您的點擊處理程序確定點擊的菜單位置並避免一些複雜性。

除此之外,硬編碼數字總是很麻煩,你應該總是儘量避免它們。計算你能做什麼,用一個常量變量記錄你不能做什麼。