1. 用物件導向的概念做猜金幣程式
Code:
Cup[] cup = new Cup[3]; // 存杯子的陣列
int guess; // 表示哪個杯子裡有放金幣
void setup() {
size(400, 300);
// 初始化三個杯子
for (int i=0; i<3; i++) {
cup[i] = new Cup(100+i*100, 100);
}
// 隨機產生亂數
guess = (int) random(3);
cup[guess].coin = true; // 在亂數位置的杯子放金幣
println(guess);
}
void draw() {
background(255);
for (int i=0; i<3; i++) {
cup[i].draw();
// 如果杯子裡有金幣且滑鼠有點擊,則將金幣畫出來
if (mousePressed && cup[i].coin==true) {
fill(255, 255, 0);
ellipse(cup[i].pos.x, cup[i].pos.y, 30, 30);
}
}
}
class Cup {
PVector pos; // 杯子的座標位置
PVector v; // 杯子的移動速度
boolean coin = false; // 杯子裡有沒有錢
Cup(float x, float y) {
// 建構子,初始化杯子的位置和移動速度
pos = new PVector(x, y);
v = new PVector(random(4), random(3));
}
void draw() {
pos.add(v);
// 如果超出邊界就反彈
if (pos.x<0 || pos.x>400) v.x *= -1;
if (pos.y<0 || pos.y>300) v.y *= -1;
fill(255);
ellipse(pos.x, pos.y, 90, 60);
}
}
沒有留言:
張貼留言