# IEH Workshop004:基礎程式設計三
程式設計課程規定(違規視情況扣分,並影響學期末成績。)
1. 上課時請專心,禁止玩遊戲。下課時間可以玩遊戲沒問題。
2. 課程中若需要討論,請控制音量,不要干擾其他同學。
3. 每次的課堂作業,應於當天完成。
4. 課堂中有問題,請舉手發問。
5. 課堂中禁止飲食,只能帶水至教室。
* https://ieh.mattc.art
* https://editor.p5js.org
# 前兩堂作業解答
## Workshop002
印出 1+1=2
```javascript
function setup(){
createCanvas(400,500)
}
function draw(){
background(200)
let num1=1
let num2=1
let str=num1+"+"+num2+"="+(num1+num2)
let x=50
let y=50
text(str, x, y)
}
```
### 更多練習: 請印出 3-2=1
## Workshop003
```javascript
let circleX = 100
let circleY = 100
let circleSize = 30
let velocityX = 5
let velocityY = 5
function setup(){
createCanvas(400,500)
}
function draw(){
background(0)
circle(circleX, circleY, circleSize)
circleY = circleY + velocityY
circleX = circleX + velocityX
if (circleY > height || circleY < 0){
velocityY = -velocityY
}
if (circleX > width || circleX < 0){
velocityX = -velocityX
}
}
```
```javascript
function randomColor(){
// random number between 0 - 255
r = random(255);
g = random(255);
b = random(255);
fill(r, g, b, 255);
}
```
請依據前面範例,讓球在碰撞牆壁時改變顏色
# 基礎程式
## 1. 註解
Ctrl + / (Windows/Linux) or Cmd + / (Mac)
```
//
```
## 2. class 物件
```javascript
class Particle {
constructor(){
this.x = random(0,width);
this.y = random(0,height);
this.r = random(1,8);
this.xSpeed = random(-2,2);
this.ySpeed = random(-1,1.5);
}
createParticle() {
noStroke();
fill('rgba(200,169,169,0.5)');
circle(this.x,this.y,this.r);
}
moveParticle() {
if(this.x < 0 || this.x > width)
this.xSpeed*=-1;
if(this.y < 0 || this.y > height)
this.ySpeed*=-1;
this.x+=this.xSpeed;
this.y+=this.ySpeed;
}
joinParticles(particles) {
particles.forEach(element =>{
let dis = dist(this.x,this.y,element.x,element.y);
if(dis<85) {
stroke('rgba(255,255,255,0.04)');
line(this.x,this.y,element.x,element.y);
}
});
}
}
let particles = [];
function setup() {
createCanvas(720, 400);
for(let i = 0;i<width/10;i++){
particles.push(new Particle());
}
}
function draw() {
background('#0f0f0f');
for(let i = 0;i<particles.length;i++) {
particles[i].createParticle();
particles[i].moveParticle();
particles[i].joinParticles(particles.slice(i));
}
}
```
## 課堂作業
1. 請針對上述範例,改變粒子顏色,並隱藏"連線"
2. Car範例
```javascript
let car;
function setup() {
createCanvas(400, 200);
car = new Car();
}
function draw() {
background(220);
car.move();
car.display();
}
class Car {
constructor() {
this.x = 0;
this.y = height / 2;
this.speed = 2;
}
display() {
rect(this.x, this.y, 50, 30);
}
move() {
this.x += this.speed;
if (this.x > width) {
this.x = -50;
}
}
}
```
請針對上述範例,改成上到下,且新增變色特效
提示:
```javascript
randomColor(){
// random number between 0 - 255
let r = random(255);
let g = random(255);
let b = random(255);
fill(r, g, b, 255);
}
```