2011-02-24 36 views
2

我剛剛開始使用python,我正在嘗試製作一個小型射箭遊戲。然而,在這一點上它會產生一個錯誤:d = math.sqrt(x * x + y * y)(即新點與圓的原始中心之間的距離)關於爲什麼這不起作用的任何想法?python中的簡單射箭遊戲

def archery(): 

    win = GraphWin("Archery Game", 500,500) 
    win.setCoords(-50, -50, 50, 50) 

    circle1 = Circle(Point(0,0), 40) 
    circle1.setFill("white") 
    circle1.draw(win) 

    circle2 = Circle(Point(0,0), 35) 
    circle2.setFill("black") 
    circle2.draw(win) 

    circle3 = Circle(Point(0,0), 30) 
    circle3.setFill("blue") 
    circle3.draw(win) 

    circle4 = Circle(Point(0,0), 25) 
    circle4.setFill("red") 
    circle4.draw(win) 

    circle5 = Circle(Point(0,0), 20) 
    circle5.setFill("yellow") 
    circle5.draw(win) 

    score = 0 

    for i in range(5): 
     p = win.getMouse() 
     p.draw(win) 
     x = p.getX 
     y = p.getY 

     d = math.sqrt(x*x + y*y) 

     if 40 >= d > 35: 
      score = score + 1 

     elif 35 >= d > 30: 
      score = score + 3 

     elif 30 >= d > 25: 
      score = score + 5 

     elif 25 >= d > 20: 
      score = score + 7 

     elif 20 >= d >= 0: 
      score = score + 9 
     else: 
      score = score + 0 

     print("Your current score is:", score) 

    win.getMouse() 
    win.close() 
+4

你得到了什麼錯誤?你輸入數學嗎? – 2011-02-24 17:48:27

+1

小提示:您可以用'**'在Python中提出一個數字。 – Skurmedel 2011-02-24 17:49:04

+3

它看起來像p.getX和p.getY應該是「p.getX()」和「p.getY()」。我假設你試圖將getX和getY函數相乘並相加,而不是這些函數返回的數字。 – stderr 2011-02-24 17:50:13

回答

4
x = p.getX 
    y = p.getY 

將返回功能getXgetY,而不是執行它。正如Mike Steder所說,試試getX(),那應該會返回一個值。

1

首先,你可能需要做的:

x = p.getX() 
y = p.getY() 

即調用的函數,並使用返回值,而不是使用函數本身。

其次,你可以改變math.sqrt(x*x + y*y)呼籲:

d = math.hypot(x, y) 
+0

''(x * x + y * y)** 0.5'可以由Python編譯器內聯,保存全局查找到hypot和函數調用。 – PaulMcG 2011-09-02 08:32:27

+0

@保羅:是的,它可以內聯,但它呢? 3.1.1+(r311:74480)和2.7.1(r271:86832)都沒有;我不知道以後的版本。 – tzot 2011-09-04 18:07:59

+0

>>> z = lambda x,y:(x * x + y * y)** 0.5 >>> import dis >>> dis.dis(z) – PaulMcG 2011-09-05 23:58:53