Created
June 15, 2020 13:11
-
-
Save mina93612/93167c2651a5247e0b97e68df60623a7 to your computer and use it in GitHub Desktop.
hw 6/15
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.hw; | |
import java.util.Random; | |
public class Horse extends Thread{ | |
Random random = new Random(); | |
int speed; | |
int number; | |
RaceCanvas parent; | |
public Horse(RaceCanvas parent,int number) { | |
this.number= number; | |
this.parent=parent; | |
this.speed=0; | |
this.random=new Random(); | |
} | |
public void run(){ | |
while (this.speed<700){ | |
System.out.println(getName()+":"+this.speed); | |
this.speed +=random.nextInt(10)+1; | |
parent.repaint(); | |
try { | |
Thread.sleep(100); | |
}catch (InterruptedException e){ | |
e.printStackTrace(); | |
} | |
} | |
parent.finish(number); | |
parent.repaint(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.hw; | |
import javax.swing.*; | |
//使用 GUI (JFrame、Canvas) 設計前單元三匹馬賽跑的程式,能在最後顯示那一匹馬獲勝為佳。 | |
//Canvas 類別 通常用作繪圖的畫布。 | |
public class HorseMain extends JFrame{ | |
public HorseMain(){ | |
setSize(800,400); | |
RaceCanvas raceCanvas =new RaceCanvas(); | |
JPanel panel = new JPanel(); | |
JButton button = new JButton("Go!"); | |
panel.add(button); | |
add(raceCanvas); | |
setVisible(true); | |
setDefaultCloseOperation(DISPOSE_ON_CLOSE); | |
} | |
public static void main(String[] args) { new HorseMain(); } | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.hw; | |
import com.classing.Snow; | |
import java.awt.*; | |
import java.util.ArrayList; | |
import java.util.List; | |
public class RaceCanvas extends Canvas{ | |
List<Horse> horses = new ArrayList<Horse>(); | |
int winner =-1; | |
public RaceCanvas(){ | |
for (int i =1 ; i<4 ; i++){ | |
Horse horse =new Horse(this,i); | |
horse.start(); | |
horses.add(horse); | |
} | |
} | |
public void finish(int number){ | |
if (winner != -1){ | |
return; | |
} | |
winner =number; | |
} | |
@Override | |
public void paint(Graphics graphics){ | |
for (int i=0; i<horses.size();i++){ | |
Horse horse = horses.get(i); | |
graphics.setColor(Color.black); | |
graphics.drawString("馬",horse.speed,i*50+20); | |
if (winner!= -1){ | |
graphics.drawString("第一名:"+winner+"號",0,300); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment