2017-05-18 10 views
1

선생님을위한 테스트를하고 있는데, 동시대를 시뮬레이트하면 아래 프로그램이 어떻게 더 빨리 진행될 수 있는지 알고 싶어합니다. (완벽하게 동시적일 수는 없습니다. 이것은 여러 거북이의 움직임을 배우고 연습하기위한 실험 일뿐입니다). 나는 다중 처리, 스레딩, 심지어 시간과 지연에 대한 미친 어리석은 시도조차도 사용했다. (나는 고등학생이다. 나는 지난 주에 내가 생각했던 이전 질문 때문에 파이썬 수업을 배웠다.) 그래서 사람이 시도하는 그 밖의 무엇의 몇 가지 아이디어, 또는동시에 움직이는 파이썬 다중 거북이

수입 거북이 거북이 수입 거북이에서 거북이의 동시 동작을 시뮬레이션에 갈 수있는 방향이있는 경우 많은 시도 실패 후 내가 부탁 해요

turtle.getscreen().delay(0) 
class MyTurtle(Turtle): 
    def petal(self): 
     for i in range(90): 
      self.fd(1) 
      self.rt(1) 
     self.rt(90) 
     for i in range(90): 
      self.fd(1) 
      self.rt(1) 

    def stem(self): 
     self.pencolor('green') 
     self.fd(250) 

    def flowerhead(self): 
     for i in range(9): 
      self.pencolor('red') 
      self.begin_fill() 
      self.petal() 
      self.lt(230) 
      self.end_fill() 

    def stempetal(self): 
     self.seth(90) 
     self.rt(15) 
     self.fillcolor('green') 
     self.begin_fill() 
     self.petal() 
     self.end_fill() 



tony = MyTurtle(shape='turtle') 
todd = MyTurtle(shape='turtle') 
tina = MyTurtle(shape='turtle') 
tiny = MyTurtle(shape='turtle') 
tweeny = MyTurtle(shape='turtle') 


def flower1(): 
    todd.speed('fastest') 
    todd.fillcolor('blue') 
    todd.flowerhead() 
    todd.seth(270) 
    todd.stem() 
    todd.stempetal() 

def flower2(): 
    tony.speed('fastest') 
    tony.setpos(80, -15) 
    tony.pencolor('green') 
    tony.goto(0, -200) 
    tony.fillcolor('purple') 
    tony.goto(80,-15) 
    tony.rt(40) 
    tony.flowerhead() 


def flower3(): 
    tina.speed('fastest') 
    tina.setpos(-80, -15) 
    tina.pencolor('green') 
    tina.goto(0, -200) 
    tina.fillcolor('teal') 
    tina.goto(-80,-15) 
    tina.lt(40) 
    tina.flowerhead() 


def flower4(): 
    tiny.speed('fastest') 
    tiny.setpos(160, -25) 
    tiny.pencolor('green') 
    tiny.goto(0, -200) 
    tiny.fillcolor('black') 
    tiny.goto(160, -25) 
    tiny.flowerhead() 


def flower5(): 
    tweeny.speed('fastest') 
    tweeny.setpos(-160, -25) 
    tweeny.pencolor('green') 
    tweeny.goto(0, -200) 
    tweeny.fillcolor('pink') 
    tweeny.goto(-160,-25) 
    tweeny.lt(40) 
    tweeny.flowerhead() 


flower2() 
tony.hideturtle() 
flower4() 
tiny.hideturtle() 
flower3() 
tina.hideturtle() 
flower5() 
tweeny.hideturtle() 
flower1() 
todd.hideturtle() 

시간 내 주셔서 감사합니다

답변

2

'빠른 실행'과 '동시 동작 시뮬레이션'의 두 가지를 요청했습니다. 나는 우리가 둘 다 (별도로) 할 수 있다고 믿지만 나는 하지 않는다.은 실제 문제를 다루기위한 반창고 일 뿐이므로 tracer()update()이이 상황에서의 답이라고 생각한다.

아래의 프로그램이 가능하게 실행할 수있는 방법을보고 싶어 당신이이 petal() 함수 인 병목를 수정, 빠르게 실행하려면

빨리. 거북이 내장 된 circle() 기능을 사용하는 것으로 교체하십시오. 예를 들면 다음과 같습니다.

def petal(self): 
    self.circle(-60, 90) 
    self.rt(90) 
    self.circle(-60, 90) 

이렇게하면 다른 변경 사항없이 코드 속도가 25 배 빨라집니다.

이는 거북이의 자신의 ontimer() 이벤트 투수와 몇 가지주의 프로그래밍을 수행 할 수 있습니다 거북이

동시에 움직임을 시뮬레이션 할 수 있습니다.우리가 다른 시간 제한 이벤트에 처리를 끌 수있는 사이에 분 단계에 그래픽 깨진다 놀랍게도, 우리는 원래 petal() 논리를 사용

from random import randint 
from turtle import Turtle, Screen 

class MyTurtle(Turtle): 

    def petals(self, size=30, count=8, speed=100): 
     if size == 30: 
      self.begin_fill() 

     if size > 0: # drawing leading edge of petal 
      self.fd(3) 
      self.rt(3) 

      screen.ontimer(lambda: self.petals(size - 1, count, speed), speed) 
      return 

     if size == 0: # switch to other edge of petal 
      self.rt(90) 

     if size > -30: # drawing trailing edge of petal 
      self.fd(3) 
      self.rt(3) 

      screen.ontimer(lambda: self.petals(size - 1, count, speed), speed) 
      return 

     self.end_fill() # finish this petal 
     self.lt(230) # prepare for the next petal 

     if count > 0: # drawing the next petal 
      screen.ontimer(lambda: self.petals(count=count - 1, speed=speed), speed) 
      return 

     self.hideturtle() # finished drawing 

    def stem(self): 
     self.pencolor('green') 
     self.fd(250) 

    def flowerhead(self): 
     self.pencolor('red') 

     self.petals(speed=randint(50, 250)) 

def flower2(): 
    tony.color('green', 'purple') 
    tony.penup() 
    tony.goto(0, -200) 
    tony.pendown() 
    tony.showturtle() 
    tony.goto(80, -15) 
    tony.rt(40) 
    tony.flowerhead() 

def flower3(): 
    tina.color('green', 'turquoise') 
    tina.penup() 
    tina.goto(0, -200) 
    tina.pendown() 
    tina.showturtle() 
    tina.goto(-80, -15) 
    tina.lt(40) 
    tina.flowerhead() 

def flower5(): 
    tweeny.color('green', 'pink') 
    tweeny.penup() 
    tweeny.goto(0, -200) 
    tweeny.pendown() 
    tweeny.showturtle() 
    tweeny.goto(-160, -25) 
    tweeny.lt(40) 
    tweeny.flowerhead() 

tony = MyTurtle(shape='turtle', visible=False) 
tina = MyTurtle(shape='turtle', visible=False) 
tweeny = MyTurtle(shape='turtle', visible=False) 

screen = Screen() 

screen.ontimer(flower2, 100) 
screen.ontimer(flower3, 120) 
screen.ontimer(flower5, 100) 

screen.mainloop() 

RUNNING 이미지

enter image description here

를이 시뮬레이션만큼이나 빠르지는 않을 것입니다. (속도가 느려지면 페달 드로잉을 약간 더 가볍게 만들었으므로 조금 더 빨라집니다.) 자세히 살펴보면 거북이가 각각의 속도로 (의도적으로) 움직이는 것을 볼 수 있습니다.

+0

이것이 바로 내가 찾고있는 것입니다. 정말 고마워요. – jester5537

5

해결책은입니다을 입력 한 다음 새 위치를 계산하면 화면 전체가 강제로 업데이트됩니다.

import turtle 

# our two turtle instances 
first, second = turtle.Turtle(), turtle.Turtle() 

first.tracer(False) # disable updating view on screen for this turtle! 
second.tracer(False) 

# make one move - note this will not appear on screen. 
first.forward(50) 
second.left(20) 

# when you are ready to see the whole screen update 
turtle.update() 

당신은 하는 모든 새로운 액션이 turtle.update() 전에 완료되도록 기본적으로 그것을해야 할 것이다, 당신이 원하는 일을합니다. 지금하고있는 것처럼 직렬 실행으로 유지할 수 없습니다. 즉, flower1을 실행 한 다음 flower2을 순차적으로 실행할 수 없습니다. 여기

동시에 화면에 임의 패턴을 생성 거북 한 쌍의 예 :

import turtle 
import random 

# our two turtle instances 
turtles = [turtle.Turtle(), turtle.Turtle()] 
for turtle_object in turtles: 
    turtle_object.tracer(False) 

for _ in range(10000): # make ten thousand moves. 

    for t in turtles: 
     # list the possible moves available 
     possible_moves = [t.forward, t.back, t.right, t.left] 
     # give it a random value 
     random_value = random.randint(0, 100) 
     # make a random move 
     random.choice(possible_moves)(random_value) 

    # update the whole screen now that the new positions have been calculated 
    turtle.update() 
여기 트릭 각 거북 마다 새로운 위치가 계산 유의한다

, 화면 전체가 업데이트하라는 메시지가 표시되고 그 다음에 만 다음 단계로 넘어갑니다. 모든 이동은 최대한 세분화되어야합니다.

+0

이 코드는 파이썬 3에서 제시된 것처럼 작동하지 않습니다. 문제는 'tracer()'메소드가 실제로 개별 거북이가 아니라 화면의 메소드라는 것입니다. 파이썬 2에서, 거북이'tracer()'메소드는 화면 인스턴스에서 그것을 재 표현 만하기 때문에 다중 거북이를 위해 그것을 수행하면 아무 것도 추가되지 않습니다. 파이썬 3에서는 메소드의 거북이 버전이 사라졌고 대신 화면 인스턴스에서 직접 호출합니다. 나는. 같은 코드가 작동하도록하는 간단한 수정. – cdlane