java的物理世界-01入門案例1

聲明:本教程參考代碼本色學習做的筆記,但也會有很多自己個人的體會與經驗分享。只要有高中基礎並且至少學習過一門編程語言即可學習本教程。這裏給出一個processing函數查詢網站

java的物理世界-01入門案

一.安裝

首先是環境的搭建,點擊官網下載,該網站需要翻牆,考慮到可能你不會翻牆(我也不可能教你),於是我將Windows64的版本上傳到了網盤

鏈接:https://pan.baidu.com/s/1oqR54J1fUvbfg1HTr8Wupw
提取碼:6nuo

請看這裏安裝教程

二.案例

1.遊走

class Walker{
  int x,y;
  Walker(){
    //width and height are the width and height of the window you create
    x=width/4;
    y=height/4;
  }
  
  void display(){
    //set color of point
    stroke(150);
    point(x,y);
  }
  void step(){
    int choice  = (int)random(4);
    if(choice==0){
      x++;
    }else if(choice ==1){
      x--;
    }else if(choice==2){
      y++;
    }else{
      y--;
    }
  }
}

//Now We hava finished the class Walker,the next work is for Sketch--setup() and draw()
Walker walker;
void setup(){
  size(500,600);
  walker  = new Walker();
//set color of background of the window
  background(0);
}
void draw(){
  walker.step();
  walker.display();
}

程序從setup函數開始,一般放的是初始化的代碼,接下來循環執行draw函數
在這裏插入圖片描述

2.隨機函數測試

void setup(){
  size(600,600);
  background(0);
}
int counts[] = new int[10];
void draw(){
  int index = (int)random(10);
  counts[index]++;
  int w = width/10;
  fill(255);
  //開始循環繪製
  for(int i=0;i<10;i++)
  {
    rect(i*w,0,w,counts[i]);
  }
}

在這裏插入圖片描述

3.90%朝鼠標方向移動

class Walker{
  int x = width/2;
  int y = height/2;
  //該函數的作用是讓點朝着(x,y)的方向移動
  void step(int x,int y){
    if((x-this.x)!=0){
    float gradient = (float)(y-this.y)/(x-this.x);
    stroke(150);
    this.x+=1;
    this.y+=gradient;
    point(this.x,this.y);
    }
    else{
      stepRandom();
    }
  }
  void stepRandom(){
    int choice  = (int)random(4);
    if(choice==0){
      x++;
    }else if(choice ==1){
      x--;
    }else if(choice==2){
      y++;
    }else{
      y--;
    }
    stroke(150);
    point(x,y);
  }
}
//walker對象的創建應該寫在setup裏面否者此時的
//width和height還是默認值100,100
Walker walker;
void setup(){
  size(600,600);
  background(0);
  walker = new Walker();
}
void draw(){
  int x = mouseX;
  int y = mouseY;
  int result = (int)random(10);
  if(result<=8){
    walker.step(x,y);
  }else{
    walker.stepRandom();
  }
}

在這裏插入圖片描述
最後的突變是由於此時斜率太大了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章