2012-07-17 4 views
3

저는 일반적으로 프로그래밍에 익숙하지 않습니다. 숙제와 같아 보이지만, 누군가를위한 것 같지만 스스로 가르치기 때문에 "스스로 숙제"가됩니까?파이썬에서 함수 내에서 조건이 충족되는 시간은 어떻게 계산합니까?

어쨌든 거북이가 무작위로 사각형을 만들 때 창이 떠나는 횟수를 계산하고 싶습니다. 나는 또한 그것이 화면을 빠져 나가는 모든 지점에 점을 찍고 싶었지만 그것은 단지 나의 재미를위한 것입니다.

나는 매번 0을 출력한다는 것을 알고 있지만, 이미 값을 반환해야하는 이와 같은 함수 내에서 누적 기 패턴을 만드는 방법을 알 수는 없다. . 어떤 조언을 주시면 감사하겠습니다

import random 
import turtle 

def isInScreen(w,t): 

    leftBound = - w.window_width()/2 
    rightBound = w.window_width()/2 
    topBound = w.window_height()/2 
    bottomBound = -w.window_height()/2 

    turtleX = t.xcor() 
    turtleY = t.ycor() 


    stillIn = True 
    outs = 0 

    if turtleX > rightBound or turtleX < leftBound: 
     t.dot() 
     t.right(180) 
     t.forward(50) 
     outs += 1 
     print(outs) 
     return outs 

    if turtleY > topBound or turtleY < bottomBound: 
     t.dot() 
     t.right(180) 
     t.forward(50) 
     outs += 1 
     print(outs) 
     return outs 

    if outs == 4: 
     stillIn = False 

    return stillIn 

t = turtle.Turtle() 
wn = turtle.Screen() 

t.shape('turtle') 
while isInScreen(wn,t): 
    coin = random.randrange(0,2) 
    if coin == 0: 
     t.left(90) 
    else: 
     t.right(90) 

    t.forward(50) 

wn.exitonclick() 

:

여기 내 코드입니다.

답변

0

'stillIn'값과 누적 기 값이있는 목록 개체를 반환 할 수 있습니다.

3

이 작업을 수행하는 가장 쉬운 방법은 거북이가 기능 범위를 벗어나는 화면의 횟수를 추적하는 것입니다 (단, while 루프 내부).

거북이가 4 회 나왔는지 여부를 반환하는 대신, 그 단계에서 거북이가 나간 경우 반환해야합니다.

outs = 0 
while outs < 4: 
    if isScreen: 
     outs += 1 
+0

죄송하지만 답변이 제대로 작동하지 않는 것 같습니다. 4 이후 드로잉 루프가 끝나거나 끝나지 않습니다. – theSchap

0

한 가지 방법은이다 : 당신이 당신의 while 루프에서 사라 얼마나 많은 시간을 추적 할 수 있습니다 그리고

def isScreen(w, t): 
    if turtleX > rightBound or turtleX < leftBound: 
     return True 
    if turtleY > topBound or turtleY < bottomBound: 
     return True 
    else: 
     return False 

:처럼 당신은 무언가를보고 당신의 기능을 변경해야 할 것 outs을 캡슐화

outs = 0 
def isInScreen(w,t): 
    ... 

약간 더 좋은 방법은 그것을 속성을 확인하는 것입니다 : 단지 outs를 글로벌 변수 (권장하지 않음)를 만들 함수 자체의 이 방법은 일종의 글로벌 변수처럼 작동합니다.

def isInScreen(w,t): 

    leftBound = - w.window_width()/2 
    rightBound = w.window_width()/2 
    topBound = w.window_height()/2 
    bottomBound = -w.window_height()/2 

    turtleX = t.xcor() 
    turtleY = t.ycor() 


    stillIn = True 

    if turtleX > rightBound or turtleX < leftBound: 
     t.dot() 
     t.right(180) 
     t.forward(50) 
     isInScreen.outs += 1 
     print(isInScreen.outs) 
     return isInScreen.outs 

    # rest of the function 

isInScreen.outs = 0 

기본적으로, 당신은, 함수의 몸을 통하여 isInScreen.outsouts 대체 함수가 정의 된 후 초기화. (안타깝게도 함수 내부에서 값을 초기화 할 수 없거나 호출 할 때마다 값이 초기화되지 않습니다.)

이것은 일반적인 관용구가 아닙니다. 대부분의 경우, 당신은 outs을 속성으로 갖는 클래스와 isInScreen 속성을 업데이트하는 클래스를 가질 것입니다.

+1

"공통 관용구가 아니라"는 "독자를 혼동시킬 수밖에 없다"고 대체해야합니다. PEP20은 "이행을 설명하기가 어렵다면 그것은 나쁜 생각이다." 외부에서 함수 네임 스페이스를 사용하는 것은 인터프리터에게 설명하기가 어렵습니다 ("불행히도"경고가 필요한 이유입니다). – msw

1

특정 항목을 참조하는 변수를 클래스에 넣는 것은 어떻습니까?

class MyTurtle(object): 

    def __init__(self): 
     self.outs = 0 

    def isInScreen(self, w, t): 
     leftBound = - w.window_width()/2 
     rightBound = w.window_width()/2 
     topBound = w.window_height()/2 
     bottomBound = -w.window_height()/2 

     turtleX = t.xcor() 
     turtleY = t.ycor() 

     stillIn = True 

     if turtleX > rightBound or turtleX < leftBound: 
      t.dot() 
      t.right(180) 
      t.forward(50) 
      self.outs += 1 
      print(self.outs) 
      return outs 

     if turtleY > topBound or turtleY < bottomBound: 
      t.dot() 
      t.right(180) 
      t.forward(50) 
      self.outs += 1 
      print(self.outs) 
      return outs 

     if self.outs == 4: 
      stillIn = False 

     # for some reason i think this line was missing 
     return stillIn 
     # or this 
     return outs 


t = turtle.Turtle() 
wn = turtle.Screen() 

myThing = MyTurtle() 
t.shape('turtle') 

# now you know WHAT is located "in screen" 
# and you could now have lots of turtlely 
# things running off the screen too with a 
# little modification where each "myturtle" 
# keeps track of its own "outs" 

while myThing.isInScreen(wn, t): 
    coin = random.randrange(0,2) 
    if coin == 0: 
     t.left(90) 
    else: 
     t.right(90) 
    t.forward(50) 
wn.exitonclick() 
+0

그리고 코드의 세 줄만 더 확장 할 수 있지만 더 확장 할 수 있습니다 – DevPlayer

+0

고마워요!나는이 작업을하고 클래스를 사용하기 시작 했으므로 재미있게 활용할 수있었습니다. 유일한 문제는 내가 바꿔야한다는 것입니다 :ifs == 4 : to if self.outs == 4 : 정의되어야합니다. – theSchap

+0

outs == 4가 self.outs == 4로 업데이트되었습니다. 상승세가 좋다. – DevPlayer

관련 문제