この記事では、pythonのturtleモジュールを使って魚を描く方法をお見せします。
もし、turtleモジュールが何であるかを知らないなら、ここのチュートリアルを見てください。
Pythonに付属しているturtleライブラリをインポートする必要があり、追加でインストールする必要はありません。
import turtle
|
次のステップでは、魚を描くためのキャンバスを作成します。
キャンバスの変数には必要に応じて名前をつけることができます。
とりあえず、画面の名前は fish_scr としました。
以下のコードでは、ユーザーに対して画面の作成と表示を行っています。
また、画面の色やペンの色など、いくつかのプロパティを追加しています。
|
1
2
3
4
|
import turtle
fish_scr = turtle
fish_scr.color('black')
fish_scr.Screen().bgcolor("#85C1E9")
|
では、魚を描いてくれる関数を作ってみましょう。
この関数の名前は Draw_Fish で、魚を画面に描画します。
goto関数はポインタをある位置に持っていきます。
openup と pendown 関数は描画するときとしないときを制御します。
また、forward と backward 関数にはパラメータとして距離が必要で、left と right 関数にはパラメータとして回転角が必要です。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
def Draw_Fish(i,j):
fish_scr.penup()
fish_scr.goto(i,j)
fish_scr.speed(10)
fish_scr.left(45)
fish_scr.pendown()
fish_scr.forward(100)
fish_scr.right(135)
fish_scr.forward(130)
fish_scr.right(130)
fish_scr.forward(90)
fish_scr.left(90)
fish_scr.right(90)
fish_scr.circle(200,90)
fish_scr.left(90)
fish_scr.circle(200,90)
fish_scr.penup()
fish_scr.left(130)
fish_scr.forward(200)
fish_scr.pendown()
fish_scr.circle(10,360)
fish_scr.right(270)
fish_scr.penup()
fish_scr.forward(50)
fish_scr.pendown()
fish_scr.left(90)
fish_scr.circle(100,45)
fish_scr.penup()
fish_scr.forward(300)
fish_scr.left(135)
fish_scr.pendown()
fish_scr.right(180)
|
以下のコードを使って、画面に3匹の魚を描いてみましょう。
魚を描き終わったら、done関数を使ってアプリケーションの画面を閉じます。
|
1
2
3
4
|
Draw_Fish(0,0)
Draw_Fish(150,150)
Draw_Fish(150,-150)
fish_scr.done() |
The Complete Code
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
import turtle
fish_scr = turtle
fish_scr.color('black')
fish_scr.Screen().bgcolor("#85C1E9")
def Draw_Fish(i,j):
fish_scr.penup()
fish_scr.goto(i,j)
fish_scr.speed(10)
fish_scr.left(45)
fish_scr.pendown()
fish_scr.forward(100)
fish_scr.right(135)
fish_scr.forward(130)
fish_scr.right(130)
fish_scr.forward(90)
fish_scr.left(90)
fish_scr.right(90)
fish_scr.circle(200,90)
fish_scr.left(90)
fish_scr.circle(200,90)
fish_scr.penup()
fish_scr.left(130)
fish_scr.forward(200)
fish_scr.pendown()
fish_scr.circle(10,360)
fish_scr.right(270)
fish_scr.penup()
fish_scr.forward(50)
fish_scr.pendown()
fish_scr.left(90)
fish_scr.circle(100,45)
fish_scr.penup()
fish_scr.forward(300)
fish_scr.left(135)
fish_scr.pendown()
fish_scr.right(180)
Draw_Fish(0,0)
Draw_Fish(150,150)
Draw_Fish(150,-150)
fish_scr.done() |
上記のコードを実行すると、システム画面に新しい画面が表示され、アプリケーションの画面に魚が描き始められます。
以下、同様に表示します。
これで、PythonのTurtleモジュールを使って画面に魚を描く方法がわかりました。
お読みいただきありがとうございました。
このチュートリアルが気に入ったら、次のチュートリアルにも目を通すことをお勧めします。
- Python Pygame: 簡単な紹介
- Pythonでランダムな色を生成する方法
- Pythonで簡単なゲーム
もっと学ぶために読み続けてください