1 PackageMyTest;2 3 Importjava.awt.*;4 Importjava.awt.event.KeyEvent;5 ImportJava.awt.event.KeyListener;6 7 Importjavax.swing.*;8 9 Public classChargame {Ten Public Static voidMain (String args[]) { OneJFrame W =NewJFrame (); AW.setbounds (0, 0, 300, 520); - -Charpanel CP =NewCharpanel (); the W.add (CP); - - Cp.setbackground (color.black); - W.setbackground (color.black); + -Thread T =NewThread (CP); + T.start (); A at W.addkeylistener (CP); - Cp.addkeylistener (CP); - -W.setvisible (true); - - } in - } to classCharpanelextendsJPanelImplementsrunnable,keylistener{ + int[]X =New int[10]; - int[]y =New int[10]; the Char[]C =New Char[10]; * int[]r =New int[255]; $ int[]a =New int[255];Panax Notoginseng int[]B =New int[255]; - intScore = 100; the Charpanel () { + for(inti=0;i<10;i++){ AX[i] = (int) (Math.random () *300); theY[i] = (int) (Math.random () *500); +C[i] = (Char) (Math.random () *26+97); -R[i] = (int) (Math.random () *255); $A[i] = (int) (Math.random () *255); $B[i] = (int) (Math.random () *255); - } - } the Public voidPaint (Graphics g) { - Super. Paint (g);WuyiFont F2 =NewFont ("", font.bold,20); the G.setfont (F2); - G.setcolor (color.red); Wu if(score<0){ -g.DrawString ("Game over", 100, 200); About return; $ } -g.DrawString ("Your score is:" +score, 10, 20); -Font F1 =NewFont ("", font.bold,25); - G.setfont (F1); A for(inti=0;i<10;i++){ +G.setcolor (NewColor (R[i],a[i],b[i])); theg.DrawString ("" + (Char) C[i], x[i], y[i]); - } $ } the Public voidrun () { the //TODO auto-generated Method Stub the while(true){ the for(inti=0;i<10;i++){ -y[i]++; in if(y[i]>500){ theY[i]=0; thescore-=10; About } the } the Try{ theThread.Sleep (30); +}Catch(Exception e) {} - repaint (); the }Bayi } the Public voidkeypressed (KeyEvent e) { the intyy =-1; - intindex =-1; - //TODO auto-generated Method Stub the for(inti=0;i<10;i++){ the if(E.getkeychar () = =C[i]) { the if(yy<Y[i]) { theyy=Y[i]; -index=i; the } the the }94 } the if(index>-1){ theY[index]=0; theX[index]= (int) (Math.random () *300);98C[index]= (Char) (Math.random () *10+97); Aboutscore+=10; - }101 }102 Public voidkeyreleased (KeyEvent arg0) {103 //TODO auto-generated Method Stub104 the }106 Public voidkeytyped (KeyEvent arg0) {107 //TODO auto-generated Method Stub108 109 } the}
Java Implementation play Alphabet game