Created
November 5, 2011 09:05
-
-
Save tetsurokitahara/1341297 to your computer and use it in GitHub Desktop.
抽象クラスの概念を教えるとき用のサンプル.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.awt.* | |
import javax.swing.* | |
import static java.lang.Math.* | |
/** 抽象クラスの概念を教えるとき用のサンプル. | |
Personクラスのmoveメソッドを繰り返し呼び出すことで, | |
画面に表示されるキャラクターが動くようになっているが, | |
Personクラスにはmoveメソッドの中身(キャラクターの | |
動き方)は定義されておらず,各サブクラスで定義されている.*/ | |
abstract class Person { | |
def x, y | |
void draw(Graphics g) { | |
g.setColor(Color.BLACK) | |
draw2(g) | |
} | |
void clear(Graphics g) { | |
g.setColor(Color.WHITE) | |
draw2(g) | |
} | |
void draw2(Graphics g) { | |
g.drawOval(x, y, 30, 30) | |
g.drawLine(x+15, y+30, x+15, y+70) | |
g.drawLine(x-5, y+45, x+40, y+45) | |
g.drawLine(x+15, y+70, x, y+90) | |
g.drawLine(x+15, y+70, x+30, y+90) | |
} | |
abstract void move() | |
} | |
class SleepingPerson extends Person { | |
void move() { | |
// do nothing | |
} | |
} | |
class RandomPerson extends Person { | |
void move() { | |
x += (int)(random() * 21) - 10 | |
y += (int)(random() * 21) - 10 | |
} | |
} | |
class StraightPerson extends Person { | |
void move() { | |
x += 10 | |
if (x > 640) | |
x = 0 | |
} | |
} | |
class MyFrame extends JFrame implements Runnable { | |
def people | |
MyFrame() { | |
people = [new SleepingPerson(x:100, y:40), | |
new RandomPerson(x: 400, y:300), | |
new StraightPerson(x: 200, y:200)] | |
} | |
void run() { | |
while (true) { | |
repaint() | |
sleep(100) | |
} | |
} | |
void paint(Graphics g) { | |
people.each { | |
it.clear(g) | |
it.move() | |
it.draw(g) | |
} | |
} | |
} | |
f = new MyFrame(size: [640, 480], background: Color.WHITE, | |
visible: true, | |
defaultCloseOperation: JFrame.EXIT_ON_CLOSE) | |
(new Thread(f)).start() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment