发布网友 发布时间:2022-04-22 11:31
共3个回答
热心网友 时间:2022-05-18 09:44
前天写的猜数字游戏,yong i控制猜测次数,有详细解析,用黑窗口可以直接运行,
我试验过了,没问题
import javax.swing.Icon;热心网友 时间:2022-05-18 09:44
import javax.swing.* ;
import java.awt.* ;
import java.awt.event.* ;
public class ZiMu extends JFrame {
ZiMu(){
this.setSize(300 , 600) ;
this.setResizable(false) ;
this.setTitle("打字游戏") ;
this.setBackground(Color.BLACK) ;
MyPanel mp = new MyPanel() ;
this.add(mp) ;
this.addKeyListener(mp) ;
Thread t = new Thread (mp) ;
t.start() ;
}
public static void main(String args[]){
ZiMu w = new ZiMu () ;
w.setVisible(true) ;
}
}
class MyPanel extends JPanel implements Runnable, KeyListener {
int x[] = new int[10] ;
int y[] = new int[10] ;
int sum = 0 ;
String z[] = new String[10] ;
MyPanel(){
for(int i=0;i<10;i++){
x[i] = (int)(Math.random()*300) ;
y[i] = (int)(Math.random()*300) ;
z[i] = new String(""+(char)(Math.random()*25+65)) ;
}
}
public void paint(Graphics g) {
super.paint(g) ;
this.setBackground(Color.black) ;
g.setColor(Color.WHITE) ;
g.drawString("一分钟正确打对的字母: "+sum , 10 , 560) ;
for(int i=0;i<10;i++){
g.drawString(z[i] , x[i] , y[i]) ;
}
}
public void run(){
long g = System.currentTimeMillis() ;
while(System.currentTimeMillis()-g<=60000) {
for(int i=0;i<10;i++){
y[i] ++ ;
if(y[i]>= 600){
sum -= 1 ;
y[i] = (int)(Math.random()*50) ;
x[i] = (int)(Math.random()*280) ;
z[i] = new String(""+(char)(Math.random()*25+65)) ;
}
}
try{
Thread.sleep(20) ;
}
catch(Exception e){
}
this.repaint() ;
}
}
public void keyTyped(KeyEvent e) {
// TODO: Add your code here
}
public void keyPressed(KeyEvent e) {
String keychar = new String(""+e.getKeyChar()) ;
int yy = 0 ;
int j = -1 ;
for(int i=0;i<10;i++){
if(keychar.equals(z[i])){
if(yy<y[i]){
yy = y[i] ;
j = i ;
}
}
}
if(j!=-1){
z[j] = new String(""+(char)(Math.random()*25+65)) ;
y[j] = 0 ;
sum += 1 ;
}else{
sum -= 1 ;
}
}
public void keyReleased(KeyEvent e) {
// TODO: Add your code here
热心网友 时间:2022-05-18 09:45
有什么需求吗?要做什么类型的游戏?