1 PackageCom.java7.mychar.main;2 ImportJava.awt.Color;3 ImportJava.awt.Frame;4 ImportJava.awt.Graphics;5 ImportJava.awt.Panel;6 Importjava.awt.event.KeyEvent;7 ImportJava.awt.event.KeyListener;8 ImportJavax.swing.JFrame;9 ImportJavax.swing.JPanel;Ten One Public classMyChar { A Public Static voidMain (string[] args) { -JFrame W =NewJFrame (); -W.setsize (600, 800); the -Mypanel MP =NewMypanel (); - W.add (MP); - +Thread T =NewThread (MP); - T.start (); + A W.addkeylistener (MP); at Mp.addkeylistener (MP); - -W.setvisible (true); - } - } - in classMypanelextendsJPanelImplementsRunnable, KeyListener { - intX[] =New int[10]; to intY[] =New int[10]; + CharC[] =New Char[10]; - intScore = 1000; the //Structure Method * Mypanel () { $ for(inti = 0; I < 10; i++) {Panax NotoginsengX[i] = (int) (Math.random () * 580); -Y[i] = (int) (Math.random () * 600); theC[i] = (Char) (Math.random () * 26 + 97); + } A } the Public voidPaint (Graphics g) { + Super. Paint (g); - for(inti = 0; I < 10; i++) { $ G.setcolor (color.blue); $g.DrawString (NewCharacter (C[i]). toString (), X[i], y[i]); - } - G.setcolor (color.red); theg.DrawString ("Your grades are:" + score, 5, 15); - }Wuyi //use the thread's Repaint method to slide the letters from top to bottom the Public voidrun () { - while(true) { Wu for(inti = 0; I < 10; i++) { -y[i]++; About //if the letter slip to the bottom is not eliminated, then return to the top to generate random letters, and buckle 100 points $ if(Y[i] > 700) { -Y[i] = 0; -X[i] = (int) (Math.random () * 550); -C[i] = (Char) (Math.random () * 26 + 97); AScore-= 100; + } the } - Try { $Thread.Sleep (30); the}Catch(Exception e) { the the } the repaint (); - } in } the @Override the Public voidkeypressed (KeyEvent arg0) { About //deposit user input characters into KEYC the CharKEYC =Arg0.getkeychar (); the intNowy =-1; the intNowindex =-1; + //scan the entire array to see if there are any matching characters - for(inti = 0; I < 10; i++) { the if(KEYC = = C[i]) {//if match (may match multiple simultaneously)Bayi if(Y[i] > Nowy) {//Scan the index from 0-9 to find the maximum y-coordinate the //if a larger y-coordinate is found, assign the coordinate value to Nowy until Nowy = Y[i] theNowy =Y[i]; -Nowindex =i; - } the } the } the //eliminate the bottom match letters and regenerate random letters from the top the if(Nowindex! =-1) { -Y[nowindex] = 0; theX[nowindex] = (int) (Math.random () * 580); theC[nowindex] = (Char) (Math.random () * 26 + 97); theScore + = 10;94}Else{// theScore-= 100; the } the }98 @Override About Public voidkeytyped (KeyEvent e) { - //TODO auto-generated Method Stub101 102 }103 @Override104 Public voidkeyreleased (KeyEvent e) { the //TODO auto-generated Method Stub106 107 }108}
Practice. Play Alphabet Games