您好,登錄后才能下訂單哦!
這篇文章主要講解了Java實現打字游戲的方法,內容清晰明了,對此有興趣的小伙伴可以學習一下,相信大家閱讀完之后會有幫助。
新建一個項目,然后在src里面建一個MyGame.java文件,
把代碼粘到剛才新建的MyGame.java,
然后把兩張圖放到src下,就行了
一、代碼
import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.*; import java.awt.event.*; public class MyGame { static UIFrame uiFrame;//主界面 static playGame playgame;//正式游戲開始界面 public static void main(String[] args) { uiFrame = new UIFrame("打字游戲"); playgame = new playGame(); } /*游戲主界面*/ static class UIFrame extends JFrame { int width = 500; int height = 700; Font X = new Font("方正舒體", Font.PLAIN, 30); JLabel playjb = new JLabel("開始游戲"); JLabel rulejb = new JLabel("規則"); JLabel exitjb = new JLabel("退出游戲"); JFrame f1 = new JFrame("規則"); /*主界面設置*/ public UIFrame(String text) { super(text); this.setLayout(null); this.setSize(width, height); this.setLocationRelativeTo(null); this.setResizable(false); this.getLayeredPane().setLayout(null); JPanel imgPanel = (JPanel) this.getContentPane(); imgPanel.setOpaque(false); imgPanel.setBounds(0, 0, width, height); imgPanel.setLayout(null); ImageIcon icon = new ImageIcon("src/bg.jpg"); JLabel label = new JLabel(icon); label.setBounds(0, 0, this.getWidth(), this.getHeight()); icon.setImage(icon.getImage().getScaledInstance(label.getWidth(), label.getHeight(), Image.SCALE_DEFAULT)); this.getLayeredPane().add(label, Integer.valueOf(Integer.MIN_VALUE)); Title title = new Title();//新建一個標題對象 this.add(title);//往窗口中加入標題面板 Thread t = new Thread(title);//將標題面板加入一個線程 t.start();//啟動線程,實現標題面板下落 buildButton(); add_JB_Listener(); setruleJF(); this.setVisible(true); } /*設置按鈕規格*/ public void buildButton() { playjb.setForeground(Color.red); rulejb.setForeground(Color.red); exitjb.setForeground(Color.red); playjb.setFont(X); rulejb.setFont(X); exitjb.setFont(X); playjb.setBounds(width / 3, height * 2 / 6, width / 3, 50); rulejb.setBounds(width / 3, height * 3 / 6, width / 3, 50); exitjb.setBounds(width / 3, height * 4 / 6, width / 3, 50); playjb.setHorizontalAlignment(JLabel.CENTER); rulejb.setHorizontalAlignment(JLabel.CENTER); exitjb.setHorizontalAlignment(JLabel.CENTER); this.add(playjb); this.add(rulejb); this.add(exitjb); } /*設置規則窗口*/ public void setruleJF(){ JLabel text1 = new JLabel("<html><body>"+"基本規則:點擊開始游戲后可以選擇生命值,確認后游戲正式開始游戲開始后會自動下落四個三位"+"<br>"+" "+"數,在輸入框中輸入其中之一會自動消除這個三位數," + "得分增加,并產生新數字,當數字"+"<br>"+" "+"掉落到屏幕底部時生命值減一,生命值為0游戲結束。(PS:在輸入框中輸入空格游戲暫"+"<br>"+" "+"停,輸入任意數字則繼續)" +"<br>"+"<br>"+ "難度介紹:游戲難度會隨著得分的增加而自動增加,也可使用滑塊自己調整數字下落難度等級。"+"<br>"+"<br>"+ "閃爍模式:游戲開始后可以點擊開始閃爍按鈕來開始閃爍模式,此時數字會隔一段時間消失再出現。"+"<br>"+"<br>"+"好好享受吧!"+"</body></html>"); text1.setVerticalAlignment(JLabel.NORTH);//使其文本位于JLabel頂部 text1.setFont(new Font("宋體", Font.PLAIN, 20)); f1.add(text1);//f1為顯示規則的窗口 f1.setResizable(false); f1.setSize(2 * width - 100, height / 2); f1.setLocationRelativeTo(null); } /*按鈕添加監聽器*/ public void add_JB_Listener() { playjb.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { setVisible(false); Chooselife chooselife = new Chooselife(); } @Override public void mouseEntered(MouseEvent e) { playjb.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.LIGHT_GRAY)); } @Override public void mouseExited(MouseEvent e) { playjb.setBorder(null); } }); rulejb.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { f1.setVisible(true); } public void mouseEntered(MouseEvent e) { rulejb.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.LIGHT_GRAY)); } @Override public void mouseExited(MouseEvent e) { rulejb.setBorder(null); } }); exitjb.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { System.exit(0); } public void mouseEntered(MouseEvent e) { exitjb.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.LIGHT_GRAY)); } @Override public void mouseExited(MouseEvent e) { exitjb.setBorder(null); } }); } } /*選擇生命界面*/ static class Chooselife extends JFrame { static Boolean gamePlayflag = false;//第一次開始游戲則為false,否則為true, Chooselife() { setTitle("選擇生命值"); setAlwaysOnTop(true);//置于頂部 setLayout(null); setSize(300, 100); setLocationRelativeTo(null); setResizable(false); setBotton();//設按鈕 setVisible(true); } /*設置按鈕*/ void setBotton() { ButtonGroup lives = new ButtonGroup();//新建按鈕組實現互斥 JRadioButton one = new JRadioButton("1", true);//按鈕默認選擇1 JRadioButton two = new JRadioButton("2", false); JRadioButton three = new JRadioButton("3", false); lives.add(one);//按鈕添加進按鈕組 lives.add(two); lives.add(three); JPanel chooselifejp = new JPanel(); chooselifejp.setBounds(0, 0, getWidth(), getHeight() - 60); chooselifejp.add(one);//按鈕添加進JPanel chooselifejp.add(two); chooselifejp.add(three); add(chooselifejp);//JPanel添加到JFrame JButton play = new JButton("開始"); play.setBounds(getWidth() / 3 + 10, chooselifejp.getHeight(), 70, 25); add(play); /*給開始按鈕添加監聽器,設置選中的生命值*/ play.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (one.isSelected()) { playgame.life = 1;//開始游戲后將生命值設成1 } else if (two.isSelected()) { playgame.life = 2; } else { playgame.life = 3; } /*后面實現重玩再講*/ playgame.templife =playgame.life;//為實現重玩功能而新建的臨時變量templife,用來保存當前的生命值。 if (!gamePlayflag) {//第一次游戲 playgame.begin();//調用begin函數來新設置一些變量和線程、控件規格 gamePlayflag = true; } else { playgame.injp.replay_func();//選擇完生命值之后,使用第一次游戲使用的那些變量、線程、控件, // 然后用重玩的函數功能重置一些變量即可實現開始新一輪游戲的效果 playgame.PlayJF.setVisible(true);//顯示正式游戲界面 } dispose(); } }); } } static class playGame { static int life=1; static int templife=1; static int width = 500; static int height = 700; static int N = 4;//數字列數 static int x[] = new int[N]; static int y[] = new int[N]; static String[] num = new String[N]; JFrame PlayJF = new JFrame("打字游戲"); Image lifeicon = Toolkit.getDefaultToolkit().getImage("src/life.jpg"); static int difficult_level = 1;//下落難度 static int mindifficult_level = 1;//最小下落難度 static int shanshuo_level = 1;//閃爍難度 Boolean terminateflag = false; Boolean beginflag = false; Boolean shanshuoflag = false; Boolean zantingshanshuoflag = false;//閃爍且暫停 Boolean Gameoverflag = false; JTextField in = new JTextField(3); JLabel showtext = new JLabel(); int score; int count = 3; int allcount; int correctcount; int lianjicount; Boolean lianjiflag = false; MyPanel mp; messageJP injp; /*第一次開始游戲調用*/ public void begin() { getrandnum(); PlayJF.setSize(width, height); mp = new MyPanel(); injp = new messageJP(); PlayJF.setResizable(false); PlayJF.setLocationRelativeTo(null); PlayJF.getLayeredPane().setLayout(null); JPanel imgPanel = (JPanel) PlayJF.getContentPane(); imgPanel.setOpaque(false); imgPanel.setBounds(0, 0, width, height); imgPanel.setLayout(null); ImageIcon icon = new ImageIcon("src/bg.jpg"); JLabel label = new JLabel(icon); label.setBounds(0, 0, PlayJF.getWidth(), PlayJF.getHeight()); icon.setImage(icon.getImage().getScaledInstance(label.getWidth(), label.getHeight(), Image.SCALE_DEFAULT)); PlayJF.getLayeredPane().add(label, Integer.valueOf(Integer.MIN_VALUE)); PlayJF.getContentPane().add(mp); PlayJF.getContentPane().add(injp, Integer.valueOf(Integer.MAX_VALUE)); Thread t = new Thread(mp); t.start(); PlayJF.setVisible(true); in.requestFocus(); } /*產生四個隨機三位數*/ public static void getrandnum() { int i, j; for (i = 0; i < N; i++) {//生成數字的字符形式,設置初始橫縱坐標 num[i] = Integer.toString((int) (Math.random() * 900 + 100));//生成100到999之間隨機數 x[i] = (int) (0.1 * width + i * 0.20 * width); y[i] = 50; } for (i = 0; i < N; i++) { for (j = i + 1; j < N; j++) { while (num[j].charAt(0) == num[i].charAt(0)) {//若數字與前面的數字首位相同,則重新生成該數字 num[j] = Integer.toString((int) (Math.random() * 900 + 100)); } } } } /*數字下落面板*/ class MyPanel extends JPanel implements Runnable { int width = PlayJF.getWidth(); int height = 500; long time;//記錄時間,用于閃爍功能的實現 public MyPanel() { setOpaque(false); setBounds(0, 0, width, height); setBackground(Color.BLACK); } public void paint(Graphics g) { super.paint(g); if (Gameoverflag) {//游戲結束 g.setColor(Color.RED); g.setFont(new Font("宋體", Font.BOLD, 35)); g.drawString("游戲結束!", width / 3, height / 2); g.drawString("您的分數為"+score,width / 3-15,height/2+35); gameoverwork(); } else { if (!beginflag) {//倒計時 g.setColor(Color.RED); g.setFont(new Font("宋體", Font.PLAIN, 50)); if (count == 0) { g.drawString("Go!", width / 2, height / 2); in.setEditable(true); } else { in.requestFocus(); g.drawString(String.valueOf(count), width / 2, height / 2); } } else {//數字開始掉落 g.setFont(new Font("宋體", Font.PLAIN, 20)); g.setColor(Color.WHITE); for (int i = 0; i < N; i++) { if (shanshuoflag) {//進入閃爍模式 if (zantingshanshuoflag == false) {//閃爍模式且不在暫停狀態 if (time % 3000 < 500 * shanshuo_level == false) {//閃爍:若時間滿足條件,則繪出數字,否則不繪出數字 g.drawString(num[i], x[i], y[i]); } } else {//閃爍模式且暫停,直接顯示數字 g.drawString(num[i], x[i], y[i]); } } else {//不是閃爍則正常繪出數字 g.drawString(num[i], x[i], y[i]); } } if (terminateflag) {//畫出暫停字樣 g.setColor(Color.BLUE); g.setFont(new Font("宋體", Font.BOLD, 30)); g.drawString("暫停中...", width / 4, height / 2); g.setFont(new Font("宋體", Font.BOLD, 20)); g.drawString("輸入任意數字繼續...", width / 4, height / 2 + 30); if (shanshuoflag) { zantingshanshuoflag = true;//如果是暫停而且是閃爍狀態, } } else {//不暫停,每次數字縱坐標加一,掉落到底部生命值減一,重置所有數字縱坐標。 for (int i = 0; i < N; i++) { y[i] = y[i] + 1; if (y[i] > getHeight()&&templife>0) { templife--; for(int j=0;j<N;j++){ y[j]=50; } } } if(templife==0){//游戲結束 Gameoverflag=true; } } g.setColor(Color.WHITE); g.setFont(new Font("宋體", Font.PLAIN, 20)); g.drawString("得分:" + score, 2, 20); g.drawString("生命值:", 270, 20); for (int i = 0; i < templife; i++) { g.drawImage(lifeicon, 350 + i * 21, 1, 20, 20, this);//在指定位置根據生命值繪出愛心桃 } } } } /*清空輸入框和無法輸入*/ public void gameoverwork(){ in.setText(""); in.setEditable(false); } @Override public void run() { long startTime = System.currentTimeMillis();//記錄游戲開始時間 while (true) { /*倒計時*/ if (!beginflag) { in.setEditable(false); repaint(); try { Thread.sleep(1000); count--; if (count == -1) { beginflag = true; } } catch (InterruptedException e) { e.printStackTrace(); } } else {//繪出數字 repaint(); try { Thread.sleep(40 - difficult_level * 5); } catch (InterruptedException e) { e.printStackTrace(); } long endTime = System.currentTimeMillis(); time = endTime - startTime;//記錄從開始到執行這次重繪函數后總共經歷的時間 } } } } /*功能面板類*/ class messageJP extends JPanel { JSlider difficultJS = new JSlider(1, 5, 1);//游戲難度滑塊 JLabel difficultJL = new JLabel();//顯示“當前游戲難度為多少”的字樣 JSlider shanshuo_levelJS = new JSlider(1, 3, 1);//閃爍難度的滑塊 JLabel shanshuo_levelJL = new JLabel();//顯示“閃爍難度等級”的字樣 JLabel termiJL = new JLabel();//顯示“輸入空格暫停”字樣 JButton replay = new JButton("重玩"); JButton gotomain = new JButton("返回主界面"); JButton shanshuoJB = new JButton("開啟閃爍"); String input; messageJP() { setLayout(null); setBounds(0, mp.getHeight(), PlayJF.getWidth(), PlayJF.getHeight() - mp.getHeight()); set_difficultJS(); set_replay(); set_gotomain(); set_shanshuoJB(); set_in(); set_termiJL(); set_showtext(); } /*設置輸入框的一些功能*/ void set_in() { in.setCaretPosition(in.getText().length()); in.setBounds(width / 4, getHeight() - 70, width / 3, 30); in.setFont(new Font("宋體", Font.PLAIN, 15)); in.addKeyListener(new KeyAdapter() { public void keyTyped(KeyEvent e) { System.out.println("KeyTyped:"+in.getText()); } public void keyPressed(KeyEvent e) { super.keyPressed(e); System.out.println("KeyPressed:"+in.getText()); if (e.getKeyChar() == KeyEvent.VK_SPACE) {//判斷輸入是否為空格 if (terminateflag) { terminateflag = false; } else { terminateflag = true; } } } public void keyReleased(KeyEvent e) { System.out.println("KeyReleased:"+in.getText()); String s = in.getText().replaceAll(" ", ""); in.setText(s); if(terminateflag==true&&e.getKeyChar()!=KeyEvent.VK_SPACE){ terminateflag = false; } if (in.getText().length() >= 3) { allcount++; input = in.getText(); in.setText(""); lianjiflag = false; for (int i = 0; i < N; i++) { if (input.equals(num[i])) { y[i] = 50; score += 10 * difficult_level; correctcount++; lianjiflag = true; if (mindifficult_level < 5 && score > 200) { mindifficult_level = score / 100; difficultJS.setMinimum(mindifficult_level);//設置滑塊的最小難度 if (difficult_level < mindifficult_level) { difficult_level = mindifficult_level;//如果當前難度比最小難度低,調整最小難度 } difficultJS.setValue(difficult_level); } difficultJL.setText("下落等級:" + difficult_level); num[i] = Integer.toString((int) (Math.random() * 900 + 100)); while (true) { for (int j = 0; j < N; j++) { if (num[i].charAt(0) == num[j].charAt(0) && i != j) { num[i] = Integer.toString((int) (Math.random() * 900 + 100)); j = -1; } } break; } } } if (lianjiflag) { lianjicount++; } else { lianjicount = 0; } } showtext.setText("<html>輸入總次數:" + allcount + "<br/>正確次數:" + correctcount + "<br/>當前連擊數:" + lianjicount + " <br/></html>"); } }); add(in); } /*輸入空格暫停字樣*/ void set_termiJL() { termiJL.setText("輸入空格暫停"); termiJL.setFont(new Font("宋體", Font.PLAIN, 15)); termiJL.setForeground(Color.RED); termiJL.setBounds(width / 4, getHeight() - 95, width / 3, 30); add(termiJL); } /*難度等級滑塊*/ void set_difficultJS() { difficultJS.setBounds(10, getHeight() - 110, 80, 40); difficultJS.setMajorTickSpacing(1); difficultJS.setSnapToTicks(true); difficultJS.setPaintTicks(true); difficultJS.setPaintLabels(true); difficultJS.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { difficult_level = difficultJS.getValue(); difficultJL.setText("下落等級:" + difficult_level); } }); difficultJL.setBounds(10, getHeight() - 85, 100, 50); difficultJL.setFont(new Font("方正姚體", Font.PLAIN, 15)); difficultJL.setText("下落等級:" + difficult_level); add(difficultJL); add(difficultJS, Integer.valueOf(Integer.MIN_VALUE)); } /*重玩按鈕的功能*/ void set_replay() { replay.setBounds(width * 3 / 4 + 10, 0, 100, 50); add(replay); replay.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { replay_func(); } }); } /*返回主界面功能*/ void set_gotomain() { gotomain.setBounds(width * 3 / 4 + 10, 55, 100, 50); add(gotomain); gotomain.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { PlayJF.setVisible(false); uiFrame.setVisible(true); } }); } /*閃爍按鈕及其功能*/ void set_shanshuoJB() { shanshuoJB.setBounds(width * 3 / 4 + 10, 110, 100, 50); shanshuo_levelJS.setBounds(10, 5, 80, 40); shanshuo_levelJS.setSnapToTicks(true); shanshuo_levelJS.setPaintTicks(true); shanshuo_levelJS.setPaintLabels(true); shanshuo_levelJS.setMajorTickSpacing(1); shanshuo_levelJL.setFont(new Font("方正姚體", Font.PLAIN, 15)); shanshuo_levelJL.setText("閃爍等級:" + shanshuo_level); shanshuo_levelJL.setBounds(10, 30, 80, 70); shanshuo_levelJS.setVisible(false); shanshuo_levelJL.setVisible(false); add(shanshuoJB); add(shanshuo_levelJS); add(shanshuo_levelJL); shanshuoJB.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (shanshuoflag) {//當前模式是閃爍模式 shanshuoflag = false; shanshuo_levelJS.setVisible(false);//隱藏閃爍難度調節滑塊 shanshuo_levelJL.setVisible(false); shanshuoJB.setText("開啟閃爍"); shanshuo_level = 1; shanshuo_levelJS.setValue(1); } else { shanshuoflag = true; shanshuo_levelJS.setVisible(true); shanshuo_levelJL.setVisible(true); shanshuoJB.setText("關閉閃爍"); } } }); shanshuo_levelJS.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { shanshuo_level = shanshuo_levelJS.getValue(); shanshuo_levelJL.setText("閃爍等級:" + shanshuo_level); } }); } /*顯示一些統計信息*/ void set_showtext() { showtext.setFont(new Font("方正姚體", Font.PLAIN, 15)); showtext.setBounds(width / 4, 10, getWidth() / 3, getHeight() / 2); showtext.setText("<html>輸入總次數:" + allcount + "<br/>正確次數:" + correctcount + "<br/>當前連擊數:" + lianjicount + " <br/></html>"); showtext.setBorder(BorderFactory.createLineBorder(Color.GRAY)); add(showtext); } /*實現重玩功能的函數*/ void replay_func() {//就是重置一些變量 in.setEditable(true); difficult_level = 1; difficultJS.setMinimum(1); difficultJS.setMaximum(5); difficultJS.setValue(1); templife=life; shanshuo_level = 1; shanshuo_levelJS.setValue(1); shanshuo_levelJS.setVisible(false); shanshuo_levelJL.setVisible(false); terminateflag=false; getrandnum(); score = 0; count = 3; lianjicount = 0; allcount = 0; correctcount = 0; in.setText(""); showtext.setText("<html>輸入總次數:" + allcount + "<br/>正確次數:" + correctcount + "<br/>當前連擊數:" + lianjicount + " <br/></html>"); lianjiflag = false; shanshuoflag = false; shanshuoJB.setText("開啟閃爍"); beginflag = false; Gameoverflag = false; in.requestFocus(); } } } } /*在一個面板上實現標題自動下落*/ class Title extends JPanel implements Runnable { int width = 500; int height = 250; int N = 4; int[] x = new int[N];//存儲標題中的每個字的橫坐標 int[] y = new int[N];//存儲標題中的每個字的縱坐標 String[] strs = new String[]{"打", "字", "游", "戲"}; Title() { setBounds(0, 0, width, height);//設置面板大小 setOpaque(false);//透明 setplace();//設置標題每個字初始的橫縱坐標 } void setplace() { for (int i = 0; i < N; i++) { x[i] = (int) (width * 0.15 + i * 0.2 * width); y[i] = 10; } } @Override public void paint(Graphics g) { super.paint(g); g.setColor(Color.RED);//設置畫筆顏色為紅 g.setFont(new Font("方正姚體", Font.PLAIN, 50));//設置畫筆字體 for (int i = 0; i < N; i++) { g.drawString(strs[i], x[i], y[i]);//在指定位置畫出標題的字 y[i]++;//標題的字縱坐標下移一像素 if (y[i] > height - 50) {//如果到達height-50,則保持在那個位置 y[i] = height - 50; } } } @Override public void run() { while (true) { try { Thread.sleep(10);//實現每10毫秒重繪一次 } catch (InterruptedException e) { e.printStackTrace(); } repaint();//調用重繪函數 } } }
二、圖片
bg.jpg
life.jpg
看完上述內容,是不是對Java實現打字游戲的方法有進一步的了解,如果還想學習更多內容,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。