Pythonで亀型全自動お掃除ロボットを作る

「Eclipse 上でPythonのプログラムを書くためのプラグインPyDev」から続く

辻真吾『Pythonスタートブック』(技術評論社, 2010)4774142298を読みました。

この本は、最初に学ぶプログラミング言語がPythonだという人のために書かれた入門書ですが、全10章の最終章つまり第10章はかなりハードでした。とりあえず、初心者は飛ばしていいと思うのですが、私にとっては昔遊んだLOGOを思い出させる懐かしい内容だったので、途中まで自分なりに作ってみました。本文よりはずいぶん手を抜いたつもりですが、それでもまだこの章だけは初心者お断りかもしれません。

参照:24.4 turtle (Python Documentation)

#coding:utf-8
import turtle
import random

class Kame(turtle.Turtle):
    def __init__(self):
        super(Kame, self).__init__()
        self.xmax = 200
        self.ymax = 200
        self.getscreen().setup(2 * self.xmax + 2, 2 * self.ymax + 2, 0, 0) #ウィンドウサイズ
        self.getscreen().screensize(2 * self.xmax, 2 * self.ymax, 'gray') #キャンバスサイズ
        self.pencolor('white')
        self.width(10)
        self.left(random.randint(1, 360))

    def run(self):
        while True:
            self.forward(10)
            if self.xcor() > self.xmax: #右の壁にぶつかった
                self.rotate(90)
            if self.ycor() > self.ymax: #上の壁にぶつかった
                self.rotate(180)
            if self.xcor() < -self.xmax: #左の壁にぶつかった
                self.rotate(270)
            if self.ycor() < -self.ymax: #下の壁にぶつかった
                self.rotate(360)

    def rotate(self, t): #tはheading()の基準を変換するためのパラメータ
        self.undo()
        self.left(t - self.heading() + random.randint(0, 180))

kame = Kame()
kame.run()