第9回 課題の模範解答

課題の模範解答です。
   
課題1
<例:〇が左から右に移動する>のプログラムで、右端に達したら左端に戻るように修正しなさい
int x; // 〇の水平位置を示す変数

void setup()
{
  size( 400, 400 );
  x = 0; // 初期値は 0
}

void draw()
{
  background( 255 ); // これが無いと、残像が残る
  ellipse( x, 200, 40, 40 );
  x += 1; // 〇の位置を少し右にずらす
  if( x>400 ){ // 〇が右端に達した
    x = 0;
  }
}

 

課題2
課題1のプログラムで、左上隅から右下端まで斜めに移動するように修正しなさい。また、右下隅に達したら、左上隅に移動するようにしなさい。
int x; // 〇の水平位置を示す変数
int y; // 〇の垂直位置を示す変数

void setup()
{
  size( 400, 400 );
  x = 0;
  y = 0;
}

void draw()
{
  background( 255 );
  ellipse( x, y, 40, 40 );
  x += 1; // 〇の位置を少し右にずらす
  y += 1; // 〇の位置を少し下にずらす
  if( x>400 ){
    x = y = 0;
  }
}
 
 
課題3
黒-->黄色のグラデーションで同心円を描く(10個の円)
size( 400, 400 );
background(255);
noStroke(); // 枠線は描画しない

for(int i=0;i<10;i++){ // 10回繰り返す
  float deg = (float)i/9;
  fill( deg*255, deg*255, 0  );
  ellipse( 200, 200, 400-i*40, 400-i*40 );
}
  
 
課題4
2本の直線(赤色、青色)を例のように動くようにしなさい。
int x;
int dir;

void setup() //最初に1度だけ実行される
{
  size( 400, 400 );
  x = 0; // 初期値は 0
  dir = 1; // 移動方向
}

void draw() // 自動的に1秒間に60回実行される
{
  background( 255 );
  stroke(255,0,0); // 赤色
  line( x, 0, 400-x, 400 );
  stroke(0,0,255); // 青色
  line( 400-x, 0, x, 400 );
  x += dir; // 位置をずらす
  if( x>400 ){
    dir = -1;
  }
  if( x<0 ){
    dir = 1;
  }
}

    
 
課題5
星が回転しながら拡大・縮小を繰り返し、かつ虹色に変化するプログラムを作成しなさい。
float r_dif; // 半径の変化量
float radius; // 半径
float h_ang; // 色相の色角度
float s_ang; // 回転角度

void setup()
{
  size( 400, 400 );
  strokeWeight(4);
  colorMode( HSB,360,100,100 );
  radius = 100.0; // 初期値は 0
  h_ang = 0.0;
  s_ang = 0.0;
  r_dif = 0.5; // 正:大きくなる 負:小さくなる
}

void draw()
{
  background( 0,0,0 );
  stroke(h_ang,100,100);
 
  float x1,y1,x2,y2,rad1,rad2;
  for(int i=0;i<5;i++){
    rad1 = ((float)i*144 + s_ang)/180.0*PI;
    rad2 = ((float)(i+1)*144 + s_ang)/180.0*PI;
    // 1辺の端点の2座標の計算
    x1 = radius*cos(rad1) + 200;
    y1 = radius*sin(rad1) + 200;
    x2 = radius*cos(rad2) + 200;
    y2 = radius*sin(rad2) + 200;
    line( x1,y1, x2,y2 );
  }
  s_ang += 1.0; // 星の角度
  h_ang += 1.1; // 色相の角度
  if( h_ang>360.0 ) h_ang -= 360.0;
  radius += r_dif;
  if(radius>=200) r_dif = -0.5;
  if(radius<50) r_dif = 0.5;
}