[123D Circuit] 丟骰子遊戲 – 海大機械作業

上週阿吉老師在海洋大學 Arduino 微處理機課程的作業,用丟骰子遊戲來教隨機數與 if / else 判斷式。按下Arduino 的按鈕之後,會根據莊家與玩家各自的三顆骰子點數合來亮起兩顆 LED 其中之一。本範例感謝海洋大學機械系劉哲甫同學分享。

[iframe width=”725″ height=”448″ src=”http://123d.circuits.io/circuits/652275-hw_0317_throwthedice/embed#breadboard” frameborder=”0″ marginwidth=”0″ marginheight=”0″ scrolling=”no”]

程式碼:

int player1 = 4;
int player2 = 5;
int bsensor = 0;
int bswitch = 7;
int randomMax = 6;
int randommin = 1;
int Point = 0;
int a=0;
int b=0;

void setup() {
  Serial.begin(9600);
  Serial.println("Ready......");
  pinMode(player1, OUTPUT);
  pinMode(player2, OUTPUT);
  pinMode(bswitch, INPUT);
  delay(500);
}

void loop() {
  digitalWrite(player1,HIGH);
  delay(100);
  digitalWrite(player2,HIGH);
  delay(100);
  Serial.println("Player1 throw the dice");
  bsensor=digitalRead(bswitch);
  while(!bsensor){bsensor=digitalRead(bswitch);}
  for(int i=1;i<=3;i++){
    Point=random(randommin,randomMax);
    Serial.print("Dice");
    Serial.print(i);
    Serial.print("=");
    Serial.println(Point);
    a=a+Point;
    delay(100);
  }
  delay(500);
  Serial.println("Player2 throw the dice");
  bsensor=digitalRead(bswitch);
  while(!bsensor){bsensor=digitalRead(bswitch);}
  for(int i=1;i<=3;i++){
    Point=random(randommin,randomMax);
    Serial.print("Dice");
    Serial.print(i);
    Serial.print("=");
    Serial.println(Point);
    b=b+Point;
    delay(100);
  }
  Serial.println("Counting......");
  delay(1000);
  Serial.print("Player1 point=");
  Serial.println(a);
  Serial.print("Player2 point=");
  Serial.println(b);
  Serial.println("Push button to restart......");
  if(a<b){
    digitalWrite(player2,LOW);
    delay(100);
  }
  else{
    digitalWrite(player1,LOW);
    delay(100);
  }
  bsensor=digitalRead(bswitch);
  while(!bsensor){bsensor=digitalRead(bswitch);}
  a=0;
  b=0;
  digitalWrite(player1,HIGH);
  delay(100);
  digitalWrite(player2,HIGH);
  delay(500);           
}

About CAVEDU 阿吉 - 雜工 (2521 Articles)

CAVEDU 教育團隊 打雜

Contact: Website

Leave a comment

Your email address will not be published.


*