GuessNumber

/*

 * To change thistemplate, choose Tools | Templates

 * and open thetemplate in the editor.

 */

package guessnumber;

 

import java.awt.event.ActionEvent;

import java.awt.event.KeyEvent;

import java.awt.event.KeyListener;

import javax.swing.JOptionPane;

import javax.swing.Timer;

/**

 *

 * @author Leo

 */

public class Guess extends javax.swing.JFrame implementsKeyListener{

 

    String str ="Hello! Welcome to join our game!"+'\n'+"Please press 'Begin' toplay games!";

    double sum = 0.0;

    boolean bgn=true;

    int n = 0;

    Timer one;

 

    /**

     * Creates newform Guess

     */

    public Guess() {

        one = newTimer(100, new java.awt.event.ActionListener() {

            @Override

            publicvoid actionPerformed(java.awt.event.ActionEvent evt) {

               time(evt);

            }

        });

        one.start();

       initComponents();

    }

 

    private voidtime(ActionEvent e) {

       

       jTextArea1.setText(str);

    }

 

    /**

     * This method iscalled from within the constructor to initialize the form.

     * WARNING: Do NOTmodify this code. The content of this method is always

     * regenerated bythe Form Editor.

     */

   @SuppressWarnings("unchecked")

    // <editor-folddefaultstate="collapsed" desc="Generated Code">                         

    private voidinitComponents() {

 

        jPanel1 = newjavax.swing.JPanel();

        jTextField1 =new javax.swing.JTextField();

        jScrollPane1 =new javax.swing.JScrollPane();

        jTextArea1 =new javax.swing.JTextArea();

        jButton1 = newjavax.swing.JButton();

        jButton2 = newjavax.swing.JButton();

        jButton3 = newjavax.swing.JButton();

        jButton4 = newjavax.swing.JButton();

        jButton5 = newjavax.swing.JButton();

        jButton6 = newjavax.swing.JButton();

        jButton7 = newjavax.swing.JButton();

        jButton8 = newjavax.swing.JButton();

        jButton9 = newjavax.swing.JButton();

        jButton10 =new javax.swing.JButton();

        jButton11 =new javax.swing.JButton();

        jButton12 =new javax.swing.JButton();

        jButton13 =new javax.swing.JButton();

        jButton14 =new javax.swing.JButton();

        jButton15 = new javax.swing.JButton();

        jLabel1 = newjavax.swing.JLabel();

 

       setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

 

       jPanel1.addKeyListener(new java.awt.event.KeyAdapter() {

            public voidkeyPressed(java.awt.event.KeyEvent evt) {

               jPanel1KeyPressed(evt);

            }

        });

 

       jTextField1.setText("Please enter the number you guess.");

       jTextField1.setEnabled(false);

       jTextField1.addActionListener(new java.awt.event.ActionListener() {

            publicvoid actionPerformed(java.awt.event.ActionEvent evt) {

               jTextField1ActionPerformed(evt);

            }

        });

 

       jScrollPane1.addMouseListener(new java.awt.event.MouseAdapter() {

            publicvoid mouseEntered(java.awt.event.MouseEvent evt) {

               jScrollPane1MouseEntered(evt);

            }

        });

       jScrollPane1.addFocusListener(new java.awt.event.FocusAdapter() {

            publicvoid focusGained(java.awt.event.FocusEvent evt) {

               jScrollPane1FocusGained(evt);

            }

        });

 

       jTextArea1.setColumns(20);

       jTextArea1.setRows(5);

        jTextArea1.addFocusListener(newjava.awt.event.FocusAdapter() {

            publicvoid focusGained(java.awt.event.FocusEvent evt) {

               jTextArea1FocusGained(evt);

            }

        });

       jScrollPane1.setViewportView(jTextArea1);

 

        jButton1.setText("1");

       jButton1.addMouseListener(new java.awt.event.MouseAdapter() {

            publicvoid mouseEntered(java.awt.event.MouseEvent evt) {

               btnmouseEntered(evt);

            }

        });

       jButton1.addActionListener(new java.awt.event.ActionListener() {

            publicvoid actionPerformed(java.awt.event.ActionEvent evt) {

               jButton1ActionPerformed(evt);

            }

        });

       jButton1.addKeyListener(new java.awt.event.KeyAdapter() {

            publicvoid keyPressed(java.awt.event.KeyEvent evt) {

               jButton1KeyPressed(evt);

            }

        });

 

       jButton2.setText("2");

       jButton2.addActionListener(new java.awt.event.ActionListener() {

            publicvoid actionPerformed(java.awt.event.ActionEvent evt) {

               jButton2ActionPerformed(evt);

            }

        });

 

       jButton3.setText("3");

       jButton3.addActionListener(new java.awt.event.ActionListener() {

            public voidactionPerformed(java.awt.event.ActionEvent evt) {

               jButton3ActionPerformed(evt);

            }

        });

 

       jButton4.setText("4");

       jButton4.addActionListener(new java.awt.event.ActionListener() {

            publicvoid actionPerformed(java.awt.event.ActionEvent evt) {

               jButton4ActionPerformed(evt);

            }

        });

 

       jButton5.setText("5");

       jButton5.addActionListener(new java.awt.event.ActionListener() {

            publicvoid actionPerformed(java.awt.event.ActionEvent evt) {

               jButton5ActionPerformed(evt);

            }

        });

 

       jButton6.setText("6");

       jButton6.addActionListener(new java.awt.event.ActionListener() {

            public voidactionPerformed(java.awt.event.ActionEvent evt) {

               jButton6ActionPerformed(evt);

            }

        });

 

       jButton7.setText("7");

       jButton7.addActionListener(new java.awt.event.ActionListener() {

            public voidactionPerformed(java.awt.event.ActionEvent evt) {

               jButton7ActionPerformed(evt);

            }

        });

 

       jButton8.setText("8");

       jButton8.addActionListener(new java.awt.event.ActionListener() {

            publicvoid actionPerformed(java.awt.event.ActionEvent evt) {

               jButton8ActionPerformed(evt);

            }

        });

 

       jButton9.setText("9");

       jButton9.addActionListener(new java.awt.event.ActionListener() {

            publicvoid actionPerformed(java.awt.event.ActionEvent evt) {

               jButton9ActionPerformed(evt);

            }

        });

 

       jButton10.setText("OK");

       jButton10.addActionListener(new java.awt.event.ActionListener() {

            public voidactionPerformed(java.awt.event.ActionEvent evt) {

               jButton10ActionPerformed(evt);

            }

        });

 

       jButton11.setText("Cancel");

       jButton11.addActionListener(new java.awt.event.ActionListener() {

            publicvoid actionPerformed(java.awt.event.ActionEvent evt) {

               jButton11ActionPerformed(evt);

            }

        });

 

       jButton12.setText("0");

       jButton12.addActionListener(new java.awt.event.ActionListener() {

            public voidactionPerformed(java.awt.event.ActionEvent evt) {

               jButton12ActionPerformed(evt);

            }

        });

 

       jButton13.setText("Delet");

       jButton13.addActionListener(new java.awt.event.ActionListener() {

            publicvoid actionPerformed(java.awt.event.ActionEvent evt) {

               jButton13ActionPerformed(evt);

            }

        });

 

       jButton14.setText("Help");

       jButton14.addActionListener(new java.awt.event.ActionListener() {

            publicvoid actionPerformed(java.awt.event.ActionEvent evt) {

               jButton14ActionPerformed(evt);

            }

        });

 

       jButton15.setText("Begin");

       jButton15.addActionListener(new java.awt.event.ActionListener() {

            publicvoid actionPerformed(java.awt.event.ActionEvent evt) {

               jButton15ActionPerformed(evt);

            }

        });

       jButton15.addKeyListener(new java.awt.event.KeyAdapter() {

            publicvoid keyPressed(java.awt.event.KeyEvent evt) {

               jButton15KeyPressed(evt);

            }

        });

 

       jLabel1.setText("Guess");

 

       javax.swing.GroupLayout jPanel1Layout = newjavax.swing.GroupLayout(jPanel1);

       jPanel1.setLayout(jPanel1Layout);

       jPanel1Layout.setHorizontalGroup(

           jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

           .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,jPanel1Layout.createSequentialGroup()

               .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)

               .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 226,javax.swing.GroupLayout.PREFERRED_SIZE)

               .addContainerGap())

            .addGroup(jPanel1Layout.createSequentialGroup()

               .addContainerGap()

               .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

                   .addGroup(jPanel1Layout.createSequentialGroup()

                       .addComponent(jLabel1)

                       .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))

                   .addGroup(jPanel1Layout.createSequentialGroup()

                       .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)

                           .addComponent(jTextField1)

                           .addGroup(jPanel1Layout.createSequentialGroup()

                                .addGap(0, 0,Short.MAX_VALUE)

                               .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)

                                   .addGroup(jPanel1Layout.createSequentialGroup()

                                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)

                                           .addComponent(jButton12)

                                           .addComponent(jButton1)

                                           .addComponent(jButton4)

                                           .addComponent(jButton7))

                                       .addGap(55, 55, 55)

                                       .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING,false)

                                           .addGroup(jPanel1Layout.createSequentialGroup()

                                               .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

                                                   .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)

                                                       .addComponent(jButton2)

                                                       .addComponent(jButton5)

                                                       .addComponent(jButton8))

                                                   .addComponent(jButton14))

                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)

                                               .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

                                                   .addComponent(jButton3, javax.swing.GroupLayout.Alignment.TRAILING)

                                                   .addComponent(jButton6, javax.swing.GroupLayout.Alignment.TRAILING)

                                                   .addComponent(jButton9, javax.swing.GroupLayout.Alignment.TRAILING)

                                                   .addComponent(jButton10, javax.swing.GroupLayout.Alignment.TRAILING)))

                                           .addGroup(jPanel1Layout.createSequentialGroup()

                                               .addGap(63, 63, 63)

                                               .addComponent(jButton15)

                                                .addGap(0, 1,Short.MAX_VALUE))))

                                   .addGroup(javax.swing.GroupLayout.Alignment.LEADING,jPanel1Layout.createSequentialGroup()

                                       .addComponent(jButton13)

                                       .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

                                       .addComponent(jButton11)))))

                       .addGap(15, 15, 15))))

        );

        jPanel1Layout.setVerticalGroup(

           jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

           .addGroup(jPanel1Layout.createSequentialGroup()

               .addContainerGap()

               .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 12,javax.swing.GroupLayout.PREFERRED_SIZE)

               .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)

               .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE,javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

               .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

               .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 66,javax.swing.GroupLayout.PREFERRED_SIZE)

               .addGap(18, 18, 18)

               .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

                   .addComponent(jButton3)

                   .addComponent(jButton1)

                   .addComponent(jButton2))

               .addGap(18, 18, 18)

               .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

                   .addComponent(jButton4)

                   .addComponent(jButton5)

                   .addComponent(jButton6))

               .addGap(18, 18, 18)

               .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

                   .addComponent(jButton8)

                    .addComponent(jButton7)

                   .addComponent(jButton9))

               .addGap(18, 18, 18)

               .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

                   .addComponent(jButton12)

                   .addComponent(jButton10)

                   .addComponent(jButton14))

               .addGap(18, 18, 18)

               .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

                    .addComponent(jButton13)

                   .addComponent(jButton15)

                   .addComponent(jButton11))

               .addContainerGap(22, Short.MAX_VALUE))

        );

 

       javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());

       getContentPane().setLayout(layout);

       layout.setHorizontalGroup(

           layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

           .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE,javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

        );

       layout.setVerticalGroup(

           layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

           .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE,javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

        );

 

        pack();

    }//</editor-fold>                       

 

    private voidjButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        

        str = str +'1';        // TODO add your handlingcode here:

    }                                       

 

    private voidjButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                        

        str = str +'3';        // TODO add your handlingcode here:

    }                                       

 

    private voidjButton12ActionPerformed(java.awt.event.ActionEvent evt) {                                         

        str = str +'0';        // TODO add your handlingcode here:

    }                                        

 

    private voidjButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                        

        str = str +'2';        // TODO add your handlingcode here:

    }                                       

 

    private voidjButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                        

        str = str +'4';        // TODO add your handlingcode here:

    }                                       

 

    private voidjButton5ActionPerformed(java.awt.event.ActionEvent evt) {                                        

        str = str +'5';        // TODO add your handlingcode here:

    }                                       

 

    private voidjButton6ActionPerformed(java.awt.event.ActionEvent evt) {                                        

        str = str +'6';        // TODO add your handlingcode here:

    }                                       

 

    private voidjButton7ActionPerformed(java.awt.event.ActionEvent evt) {                                        

        str = str +'7';        // TODO add your handlingcode here:

    }                                       

 

    private voidjButton8ActionPerformed(java.awt.event.ActionEvent evt) {                                         

        str = str +'8';        // TODO add your handlingcode here:

    }                                       

 

    private voidjButton9ActionPerformed(java.awt.event.ActionEvent evt) {                                        

        str = str + '9';        // TODO add your handling code here:

    }                                       

 

    private voidjButton11ActionPerformed(java.awt.event.ActionEvent evt) {                                         

        str ="0";        // TODO add yourhandling code here:

    }                                        

 

    private voidjButton13ActionPerformed(java.awt.event.ActionEvent evt) {                                         

        if(str.length() - 1 > 0)

            str =str.substring(0, str.length() - 1);

       if(str.length()==1)

           str="0";

    }                                        

 

    private voidjButton10ActionPerformed(java.awt.event.ActionEvent evt) {                                          

 

        int a = (int)(Math.random() * 100);

        int b =Integer.parseInt(str);

       if(b<0||b>99)

        {

           JOptionPane.showMessageDialog(null,"Please enter a number between0~99!");

        }

        else

        {

        double c;

        String strs;

        strs = a +"";

        if(str.equals(strs)) {

            c = 10.0;

           JOptionPane.showMessageDialog(null, "Congratulation! You win!Youget" + c);

        }// TODO addyour handling code here:

        else {

            c =(double) ((100 - (double) Math.abs(a - b)) / 10);

           JOptionPane.showMessageDialog(null, "You get" + c);

        }

        sum = sum + c;

        str ="";

        n++;

       System.out.println("Time:"+n+",The number computerguess:"+a+",The number you guess:"+b+",Grade:"+c);

        if (n == 10) {

           JOptionPane.showMessageDialog(null, "Your ultimate grade is" +sum);

           System.out.println("sum:"+sum);

            n = 0;

            sum=0.0;

           str="";

        }

        }

    }                                        

 

    private voidjScrollPane1FocusGained(java.awt.event.FocusEvent evt) {                                        

        // TODO addyour handling code here:

       jTextArea1.setText(str);

    }                                       

 

    private voidjScrollPane1MouseEntered(java.awt.event.MouseEvent evt) {                                         

        // TODO addyour handling code here:

        //jTextArea1.setText(str);

    }                                        

 

    private voidjTextArea1FocusGained(java.awt.event.FocusEvent evt) {                                      

        // TODO addyour handling code here:

       jTextArea1.setText(str);

    }                                     

 

    private voidjButton15ActionPerformed(java.awt.event.ActionEvent evt) {                                         

        str =""; 

        sum=0.0;

        n=0;

        bgn=true;

        // TODO addyour handling code here:

    }                                        

 

    private voidjButton14ActionPerformed(java.awt.event.ActionEvent evt) {                                         

      

        JOptionPane.showMessageDialog(null,"Pleaseenter a number between 0~99 you guess."+"\n"

                +"The computer will guess a number too."+"\n"

                +"100 detract the gap between your guess and the computer's is yourgrade."+"\n"

                + "Youhave ten times to gain grades."+"\n"

                +"Your grades is ten times to your ultimate grade. " );        // TODO add your handling code here:

    }                                        

 

    private voidjTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                           

        // TODO addyour handling code here:

    }                                          

 

    private voidbtnmouseEntered(java.awt.event.MouseEvent evt) {                                 

        // TODO addyour handling code here:

        //jTextArea1.setText(str);

    }                               

 

    private voidjButton1KeyPressed(java.awt.event.KeyEvent evt) {                                   

    // TODO add your handlingcode here:

    }                                  

 

    private voidjPanel1KeyPressed(java.awt.event.KeyEvent evt) {                                  

 

    // TODO add yourhandling code here:

       

    }                                 

private void JFrameKeyPressed(java.awt.event.KeyEvent evt)

{

    if(bgn)

    {

     if(evt.getID()==KeyEvent.VK_BACK_SPACE)

   jButton13.doClick();

   if(evt.getID()==KeyEvent.VK_1)

    { str=str+'1';

   JOptionPane.showMessageDialog(null, "Why?");

    }

   if(evt.getID()==KeyEvent.VK_2)

       jButton2.doClick();

   if(evt.getID()==KeyEvent.VK_3)

       jButton3.doClick();

   if(evt.getID()==KeyEvent.VK_4)

       jButton4.doClick();

   if(evt.getID()==KeyEvent.VK_5)

       jButton5.doClick();

    if(evt.getID()==KeyEvent.VK_6)

       jButton6.doClick();

   if(evt.getID()==KeyEvent.VK_7)

       jButton7.doClick();

   if(evt.getID()==KeyEvent.VK_8)

       jButton8.doClick();

   if(evt.getID()==KeyEvent.VK_9)

       jButton9.doClick();

   if(evt.getID()==KeyEvent.VK_0)

       jButton12.doClick();

   if(evt.getID()==KeyEvent.VK_DELETE)

       jButton11.doClick();

   if(evt.getID()==KeyEvent.VK_ENTER)

   jButton10.doClick();

   if(evt.getID()==KeyEvent.VK_F1)

       jButton14.doClick(); 

    }

}

    private voidjButton15KeyPressed(java.awt.event.KeyEvent evt) {                                    

 

   

       

   // TODO add yourhandling code here: // TODO add your handling code here:

    }                                   

 

    /**

     * @param args thecommand line arguments

     */

    public static voidmain(String args[]) {

        /* Set theNimbus look and feel */

       //<editor-fold defaultstate="collapsed" desc=" Lookand feel setting code (optional) ">

        /* If Nimbus(introduced in Java SE 6) is not available, stay with the default look andfeel.

         * For detailssee http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html

         */

        try {

            for(javax.swing.UIManager.LookAndFeelInfo info :javax.swing.UIManager.getInstalledLookAndFeels()) {

                if("Nimbus".equals(info.getName())) {

                   javax.swing.UIManager.setLookAndFeel(info.getClassName());

                   break;

                }

            }

        } catch(ClassNotFoundException | InstantiationException | IllegalAccessException |javax.swing.UnsupportedLookAndFeelException ex) {

           java.util.logging.Logger.getLogger(Guess.class.getName()).log(java.util.logging.Level.SEVERE,null, ex);

        }

       //</editor-fold>

 

        /* Create anddisplay the form */

       java.awt.EventQueue.invokeLater(new Runnable() {

            @Override

            publicvoid run() {

                newGuess().setVisible(true);

            }

        });

    }

    // Variablesdeclaration - do not modify                    

    privatejavax.swing.JButton jButton1;

    privatejavax.swing.JButton jButton10;

    privatejavax.swing.JButton jButton11;

    privatejavax.swing.JButton jButton12;

    privatejavax.swing.JButton jButton13;

    privatejavax.swing.JButton jButton14;

    privatejavax.swing.JButton jButton15;

    privatejavax.swing.JButton jButton2;

    privatejavax.swing.JButton jButton3;

    privatejavax.swing.JButton jButton4;

    privatejavax.swing.JButton jButton5;

    privatejavax.swing.JButton jButton6;

    privatejavax.swing.JButton jButton7;

    privatejavax.swing.JButton jButton8;

    privatejavax.swing.JButton jButton9;

    privatejavax.swing.JLabel jLabel1;

    privatejavax.swing.JPanel jPanel1;

    privatejavax.swing.JScrollPane jScrollPane1;

    privatejavax.swing.JTextArea jTextArea1;

    privatejavax.swing.JTextField jTextField1;

    // End ofvariables declaration                  

 

    @Override

    public voidkeyTyped(KeyEvent e) {

        throw newUnsupportedOperationException("Not supported yet."); //To change bodyof generated methods, choose Tools | Templates.

    }

 

    @Override

    public void keyPressed(KeyEvente) {

        throw newUnsupportedOperationException("Not supported yet."); //To change bodyof generated methods, choose Tools | Templates.

    }

 

    @Override

    public voidkeyReleased(KeyEvent e) {

        throw newUnsupportedOperationException("Not supported yet."); //To change bodyof generated methods, choose Tools | Templates.

    }

}

### 什么是算法以及如何通过编程实现猜数字游戏 #### 定义与背景 在计算机科学领域,算法是一组清晰定义的指令集合,用于解决特定问题或完成某项任务。对于初学者来说,理解简单的算法概念非常重要,比如排序算法中的冒泡排序和快速排序[^1]。 然而,在实际应用中,还有许多其他类型的程序逻辑可以被看作是算法的一部分,例如猜数字游戏。这种游戏的核心在于随机数生成器的功能以及玩家输入验证的过程。以下是具体实现方法: --- #### Python 实现猜数字游戏逻辑 ##### 游戏描述 猜数字游戏的目标是由计算机随机生成一个介于指定范围内的整数(如1到100),然后让玩家尝试猜测这个数值。每次猜测后,程序会告诉玩家他们的猜测是否过高、过低或者正确。 ##### 代码示例 以下是一个完整的Python版本的猜数字游戏实现: ```python import random def guess_number_game(): # 随机生成目标数字 target_number = random.randint(1, 100) attempts = 0 print("欢迎来到猜数字游戏!我已经选好了一个1到100之间的数字。") while True: try: # 获取用户的输入并转换为整数 user_guess = int(input("请输入你的猜测:")) # 增加尝试次数计数 attempts += 1 # 判断用户输入的有效性和准确性 if user_guess < target_number: print("太小了!再试一次。") elif user_guess > target_number: print("太大了!再试一次。") else: print(f"恭喜你!你在 {attempts} 次尝试后成功猜到了数字 {target_number}!") break except ValueError: print("无效输入,请输入一个有效的整数。") # 调用函数启动游戏 guess_number_game() ``` 上述代码实现了基本的游戏功能,并包含了异常处理来防止因非法字符而导致程序崩溃的情况发生。 --- #### 可视化 ASCII Art 表达胜利场景 为了增加趣味性,可以在玩家获胜时显示一段ASCII艺术文字作为奖励反馈: ```plaintext _______ _ _____ __ ___ |__ __(_) |_ _| /\ \ \ / / | | | _ ___ | | / \ \ \_/ /| | | | | |/ __| | | / /\ \ \ / | | | | | | (__ |_| / ____ \ | | | | |_| |_|\___| (_) /_/ \_\ |_| |_| Congratulations! You've won the Guess Number Game! ``` 此部分可以通过条件语句嵌入至最终成功的打印消息之中。 --- #### 扩展思考 如果希望进一步优化该游戏体验,则可考虑加入更多特性,例如限制最大尝试次数或将历史记录保存下来供后续分析使用等想法[^2]。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值