猜数字游戏的两个JAVA程序代码

合集下载

猜数字游戏源代码

猜数字游戏源代码

猜数字游戏本案例知识要点●Visual C++ 6.0下创建Win32 Console Application并运行的方法●C++程序中类的定义和实现●C++程序中类文件的引用及类的实例化一、案例需求1.案例描述由计算机产生0到99的随机数,游戏参加者将猜到的数字从键盘输入,计算机对猜数结果进行判断直到猜出正确结果。

2.案例效果图猜数字游戏运行效果如图2-1所示。

3.功能要求(1)所猜0到99的目标数字由计算随机产生。

(2)0到99的随机数的产生、所猜数字和目标数字的比较等过程以类的形式实现。

(3)若游戏参加者所猜数字正确,则提示所猜总次数;若猜数错误,则提示所猜数字比目标数字大还是小。

二、案例分析本案例中设计了一个Guess类,实现产生随机数、进行参加游戏者输入数字与目标数字的比较、计算猜数次数。

主程序中通过类的实例化实现猜数过程。

三、案例设计为了实现猜数过程,设计Guess类,结构如图2-2所示。

●数据成员int Value产生的0到99间的目标数字。

int CompareTimes为游戏者已猜次数。

●函数成员Guess()构造函数,用来产生随机目标数字。

int Compare(int InputValue)用来判断游戏者所猜数字是否正确,其参数InputValue为游戏者所猜数字。

int GetCompareTimes()用来获得游戏者已猜次数。

五、案例实现猜数字游戏源程序代码如下所示。

************************************* // * Guess.h 类声明头文件************************************* #1. #include <time.h>#2. class Guess#3. {#4. private:#5.int Value; //计算机产生的目标数字#6. int CompareTimes; //所猜次数#7. public:#8. Guess(); //构造函数的声明#9. int Compare(int InputValue); #10. int GetCompareTimes();#11. };#12. Guess:: Guess ()//构造函数的实现#13. {#14. CompareTimes=0; //猜数次数置零#15. srand((unsigned)time(NULL)); //产生随机数种子#16. Value=rand()%100;//产生0~99的随机数#17. }#18.int Guess::Compare(int InputValue)//比较猜数是否正确#19. {#20. CompareTimes++; //所猜次数加1 #21. return InputValue-Value;//比较所猜数字和目标数字是否相同,相同//返回0#22. }#23. int Guess::GetCompareTimes()//获得已猜次数#24. {#25. return CompareTimes;#26. }//************************************* //* GuessNumber.cpp 源文件************************************* #1. #include <iostream>#2. #include "Guess.h"//将已定义的类文件包含到主程序文件中#3. using namespace std;#4. int main()#5. {#6. int InputValue;#7.cout<<"\n** 欢迎使用本程序**\n"; #8. for(;;)#9. {#10. char Select;#11. Guess guessobj;//实例化Guess类#12. cout<<"我已经想好数字啦(0~99),请猜吧!\n";#13. for(;;)#14. {#15. int CompareResult; #16. cout<<"\n我想的是:";#17. cin>>InputValue;//获得游戏者输入的所猜数字#18. CompareResult=pare (InputValue);//判断游戏者所猜数字是否正确#19. if(CompareResult==0) //正确#20. {#21. int GuessTimes=guessobj.GetCompareTimes(); #22. cout<<"\n恭喜您,猜对啦!"<<endl <<"您一共猜了"<<GuessTimes<<"次"<<endl;#23. break;#24. }#25. else if(CompareResult>0)#26. {#27. cout<<"\n对不起,您猜的数大啦!\n";#28. }#29. else#30. {#31. cout<<"\n对不起,您猜的数小啦!\n";#32. }#33. }#34. cout<<"\n您还想再玩吗?('n'=No,Others=Yes)\n";#35. cin>>Select;#36. cout<<'\n';#37. if(Select=='n'||Select=='N')#38. {#39. break;#40. }#41. }#42. cout<<"********** 感谢您的使用! **********\n";#43. return 0;#44. }六、案例总结与提高1.案例总结(1)本案例的重点是介绍Visual C++ 6.0下创建并运行一个C++Win32控制台应用程序的基本过程。

Python小游戏代码

Python小游戏代码

Python5个小游戏代码1. 猜数字游戏import randomdef guess_number():random_number = random.randint(1, 100)attempts = 0while True:user_guess = int(input("请输入一个1到100之间的数字:"))attempts += 1if user_guess > random_number:print("太大了,请再试一次!")elif user_guess < random_number:print("太小了,请再试一次!")else:print(f"恭喜你,猜对了!你用了{attempts}次尝试。

")breakguess_number()这个猜数字游戏的规则很简单,程序随机生成一个1到100之间的数字,然后玩家通过输入猜测的数字来与随机数进行比较。

如果猜测的数字大于或小于随机数,程序会给出相应的提示。

直到玩家猜对为止,程序会显示恭喜消息,并告诉玩家猜对所用的尝试次数。

2. 石头、剪刀、布游戏import randomdef rock_paper_scissors():choices = ['石头', '剪刀', '布']while True:user_choice = input("请选择(石头、剪刀、布):")if user_choice not in choices:print("无效的选择,请重新输入!")continuecomputer_choice = random.choice(choices)print(f"你选择了:{user_choice}")print(f"电脑选择了:{computer_choice}")if user_choice == computer_choice:print("平局!")elif (user_choice == '石头' and computer_choice == '剪刀') or \(user_choice == '剪刀' and computer_choice == '布') or \(user_choice == '布' and computer_choice == '石头'):print("恭喜你,你赢了!")else:print("很遗憾,你输了!")play_again = input("再玩一局?(是/否)")if play_again.lower() != "是" and play_again.lower() != "yes":print("游戏结束。

猜数字实验报告

猜数字实验报告

《程序设计课程设计》题目:《猜数字》游戏物联网工程学院计算机科学与技术专业学号:学生姓名:孙文佳班级:计科1305成绩:设计思路:猜数字是一个比较益智的游戏,游戏规则也很简单,真正自己实现游戏的运行也并不是什么难事,下面就主要讲讲自己的设计思路。

大的框架是把函数封装在类中,这样就可以应用所学的类。

首先是随机产生一个4位整数,根据要求,最高位不能为0,且每一位的数不能相同。

让系统随机产生4个个位数,这里就用到srand(time(NULL))获取系统的时间作为种子,防止每次运行的结果都是相同的。

time()函数包含在头文件time.h中。

用一个for语句,依次产生这四个数,因为要求最高位不能为0,这里就用一个while语句重新生成a[0],然后就是每位上的数不得相同,依然用while语句解决这个问题。

接着是提示用户输入一个四位数,把这个四位数各位上的数保存在数组b[4]中,然后就是比较b[4]和a[4],计算数字正确且位置正确的数的个数,还有数字正确但位置错误的数的个数(这应该是游戏的额核心),其实这一步也不难,就是利用一个for语句逐个比较b[j]与a[i],如果b[j]等于a[i],wrong++,然后判断i是否等于j,是的话right++,wrong--,如果猜了8次还不正确的话,提示用户是否继续,这里用一个switch语句就行了。

如果猜了15次还不正确的话,提示用户游戏失败,是否重新玩一局。

在此之前把这次的记录写入txt文件中,这里就用到c++的输入输出流,对于数据的保存只要学会格式,依葫芦画瓢即可。

还有就是数据的读取,在游戏结束时输出上一局的结果。

程序代码:#include<iostream>#include<time.h>#include<windows.h>#include<fstream>using namespace std;class game{public:void showfunction();void showfunction2();void target();void start();void tips();void selection();private:int a[4];};void gotoxy(int x, int y){HANDLE hCon;hCon = GetStdHandle(STD_OUTPUT_HANDLE);COORD setps;setps.X = x;setps.Y = y;SetConsoleCursorPosition(hCon,setps);}void data_load(){ifstream e;int count=0;int b[4],right,wrong;e.open("Data.txt",ios::binary|ios::in);if(e){e.seekg( (count++) * sizeof(int),ios::beg);e.read( (char *)&right,sizeof(int));e.seekg( (count++) * sizeof(int),ios::beg);e.read( (char *)&("A"),sizeof(int));e.seekg( (count++) * sizeof(int),ios::beg);e.read( (char *)&wrong,sizeof(sizeof(int)));e.seekg( (count++) * sizeof(int),ios::beg);e.read( (char *)&("B"),sizeof(int));cout<<"上一局结果是:"<<right<<"A"<<wrong<<"B"<<endl;}}void quit(){gotoxy(0,10);cout<<" "<<"* * * * * * * * * * * * * * * * * * * * * * *"<<endl;cout<<" "<<"* 正在退出游戏,请稍后(loading......) *"<<endl;cout<<" "<<"* * * * * * * * * * * * * * * * * * * * * * *"<<endl;Sleep(1500);system("cls");}void game::selection(){int n;cout<<" "<<"** * * * * * * * * * * * * **"<<endl;cout<<" "<<"*1:返回主菜单。

简单的java代码例子

简单的java代码例子

简单的java代码例子1. 使用Java实现一个简单的计算器,可以进行加减乘除运算。

```javaimport java.util.Scanner;public class Calculator {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);System.out.print("请输入第一个数:");double num1 = scanner.nextDouble();System.out.print("请输入运算符(+、-、*、/):");String operator = scanner.next();System.out.print("请输入第二个数:");double num2 = scanner.nextDouble();double result = 0;switch (operator) {case "+":result = num1 + num2;break;case "-":result = num1 - num2;break;case "*":result = num1 * num2;break;case "/":result = num1 / num2;break;default:System.out.println("输入的运算符不正确!");break;}System.out.println("计算结果为:" + result);}}```2. 使用Java实现一个简单的猜数字游戏,随机生成一个1-100之间的整数,让用户猜,直到猜中为止。

```javaimport java.util.Random;import java.util.Scanner;public class GuessNumber {public static void main(String[] args) {Random random = new Random();int number = random.nextInt(100) + 1;Scanner scanner = new Scanner(System.in);int guess;do {System.out.print("请输入你猜的数字(1-100):");guess = scanner.nextInt();if (guess > number) {System.out.println("猜大了!");} else if (guess < number) {System.out.println("猜小了!");}} while (guess != number);System.out.println("恭喜你,猜对了!");}}```3. 使用Java实现一个简单的学生信息管理系统,可以添加、删除、修改、查询学生信息。

猜数字游戏java源代码

猜数字游戏java源代码

import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyAdapter;import java.awt.event.KeyEvent;import java.util.Random;import javax.swing.JButton;import javax.swing.JLabel;import javax.swing.JFrame;import javax.swing.JOptionPane;import javax.swing.JTextField;import javax.swing.WindowConstants;import java.awt.FlowLayout;public class cszyx extends javax.swing.JFrame {private JLabel jLabel1;private JTextField jTextField1;private JButton jButton1;private int number = 0;private int counter = 0;long startTime = System.currentTimeMillis();long endTime;/***新建一个随机数产生器,然后生成一个1到100之间的整数*/public cszyx() {super ("欢迎来到猜数字游戏");initChuankou();Random random = new Random();number = random.nextInt(100); // 产生一个1-100间的随机数}/***初始化窗口组件*/private void initChuankou() {setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);// 窗口关闭时销毁窗口getContentPane().setLayout(null);// 设置窗口布局为绝对布局JFrame frame = new JFrame("Test Buttons");frame.setLayout(new FlowLayout());jLabel1 = new JLabel();getContentPane().add(jLabel1);jLabel1.setText("<html>欢迎进入有趣的猜数字游戏!请输入1~100中的任意一个数:</html>");jLabel1.setBounds(2, 0, 200, 50);// 设置标签位置jTextField1 = new JTextField();getContentPane().add(jTextField1);jTextField1.setBounds(50, 60, 112, 28);jTextField1.addKeyListener(new KeyAdapter() {// 文本框添加键盘按键监听-监听回车键public void keyPressed(KeyEvent evt) {jTextField1KeyPressed(evt);}});jButton1 = new JButton();getContentPane().add(jButton1);jButton1.setText("确定");jButton1.setBounds(70, 110, 60, 28);jButton1.addActionListener(new ActionListener() {// 按钮添加监听public void actionPerformed(ActionEvent evt) {jButton1ActionPerformed(evt);// 按钮被点击时执行该方法}});pack();this.setSize(250, 200); // 设置窗口大小setLocationRelativeTo(null); // 设置窗口在显示器居中显示} catch (Exception e) {e.printStackTrace();}setVisible(true);}private void jButton1ActionPerformed(ActionEvent evt) {int guess = 0; // 记录玩家所猜测的数字counter++; // 计数器增加一。

用C++编程语言编写猜数字游戏示例

用C++编程语言编写猜数字游戏示例

用C++编程语言编写猜数字游戏示例文章标题:用C++编程语言编写猜数字游戏示例介绍内容:猜数字游戏是一种常见且富有乐趣的游戏,编程语言可以帮助我们实现一个交互式的猜数字游戏程序。

本文将介绍如何使用C++编程语言编写一个简单而有趣的猜数字游戏示例。

首先,我们需要包含C++标准库中的iostream和cstdlib头文件,以便使用输入输出和随机数生成的函数。

接下来,我们可以定义一个范围内的随机数作为答案,然后让玩家进行数字的猜测。

下面是一个示例代码,用于实现一个猜数字游戏:```cpp#include <iostream>#include <cstdlib>#include <ctime>int main() {srand(time(0)); // 根据当前时间设置随机种子int answer = rand() % 100 + 1; // 生成1到100之间的随机数int guess;int attempts = 0;std::cout << "欢迎来到猜数字游戏!\n";std::cout << "我已经想好了一个1到100之间的数字,你来猜猜看吧!\n";do {std::cout << "请输入你的猜测:";std::cin >> guess;if (guess < answer) {std::cout << "猜小了,请再试一次。

\n";} else if (guess > answer) {std::cout << "猜大了,请再试一次。

\n";}attempts++;} while (guess != answer);std::cout << "恭喜你猜对了!答案是" << answer << "。

java猜数字游戏代码

java猜数字游戏代码

java猜数字游戏代码qq:7编写程序,项目名与类名均为GuessNumberGame。

每次游戏程序随机产生一个0-9之间的整数,要求玩家输入自己猜的数字,并对用户输入数字进行检查,进行如下提示:n 如果用户猜对了,则提示:恭喜你,猜对了。

结束本次游戏。

n 如果用户猜错了,则提示:你猜的数字太(大或小)了。

要求用户继续猜。

如果连续3次没有猜对,则提示:游戏失败。

一次游戏结束时,提示用户是否继续新的游戏,果用户选择继续,则开始新一次游戏,否则输出:你共进行了XXX次游戏,成功XXX次,失败XXX次。

然后结束程序运行。

import java.util.Scanner;public class GuessNumberGame {public static void main(String[] args) {System.out.println(欢迎你试玩猜数字游戏:);System.out.println(请按1开始2退出);Scanner s = new Scanner(System.in);int ch;int win = 0;int lose = 0;int dh = 0;int fg;ch = s.nextInt();switch (ch) {case 1:fg = Guess(dh);if (fg == 1) {win++;}if (fg == 2) {lose++;}System.out.println(请按1继续2退出); ch = s.nextInt();while (ch != 2) {fg = Guess(dh);if (fg == 1) {win++;}if (fg == 2) {lose++;}System.out.println(请按1继续2退出); ch = s.nextInt();}break;case 2:break;default:break;}System.out.printf(你共进行%d次游戏猜对%d次猜错%d次\n,win+lose,win,lose);if (win lose win != win + lose) {System.out.println(拜拜欢迎下次再玩O(∩_∩)O哈哈~此次游戏成绩总评为良好);}if (win lose lose != win + lose) {System.out.println(拜拜欢迎下次再玩O(∩_∩)O哈哈~此次游戏成绩总评为中等);}if (win == win + lose) {System.out.println(拜拜欢迎下次再玩o(≧v≦)o~~好棒此次游戏成绩总评为优秀);}if (lose == win + lose) {System.out.println(拜拜欢迎下次再玩(+﹏+)~狂晕此次游戏成绩总评为特差);}}public static int Guess(int dh) {System.out.println(﹡﹡﹡﹡﹡﹡﹡﹡﹡﹡﹡﹡﹡﹡);Scanner ca = new Scanner(System.in);int max;int j;int i = 0;int fg;max =(int) (Math.random() * 10);do {System.out.println(请您输入数字:);j = ca.nextInt();if (j max) {System.out.println(太小哦);}if (j max) { System.out.println(太大哦);}if (j == max) { break;}i++;} while (i 3);switch (i) {case 1:System.out.println(您猜对了);fg = 1;break;case 2:System.out.println(您猜对了);fg = 1;break;case 3:if (j == max) {System.out.println(您猜对了);fg = 1;} else {System.out.println(对不起你没猜对); fg = 2;}break;default:System.out.println(对不起你没猜对); fg = 2;break;}return fg;}}。

猜数字游戏的两个Java程序代码

猜数字游戏的两个Java程序代码
for(inti=0;i<4;i++){
str+=putIn[i];
}
str+= " " + right;
returnstr;
}
public static voidPrintHistory(String[] history){
for(inti=0;i<history.length;i++){
if("".compareTo(history[0])==0) {System.out.println("还没有输入内容"); continue;}
if("H".compareTo(str)==0 || "h".compareTo(str)==0) {PrintHistory(history);}
}
public static StringRemarkHistory(int[]putIn, String right){
Stringstr= "";
String right = ""; //以字符串形式保存的比较结果
//计算出多少个"A"
for(inti=0;i<4;i++){
if(guess[i]==putIn[i])rightA++;
}
//计算出多少个"B"
for(inti=0;i<4;i++){
for(intj=0; j<4; j++){
}System.out.println();
int[]putIn;//定义用户输入
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

for(f(number[i]==number[j]){ System.out.println("请输入 4 位不相同的数字"); continue out1; }
} } //输入没错时,退出此死循环,继续其它操作 break; } return number; } //比较输入的与系统产生的,返回结果: xA yB public static String CompareNumber(int[] guess, int[] putIn){ int rightA = 0; //比较结果有多少个"A" int rightB = 0; //比较结果有多少个"B" String right = ""; //以字符串形式保存的比较结果 //计算出多少个"A" for(int i=0; i<4; i++){ if(guess[i]==putIn[i]) rightA++; } //计算出多少个"B" for(int i=0; i<4; i++){ for(int j=0; j<4; j++){
putIn = PutIn(history); //获取用户输入 right = CompareNumber(guess, putIn); //比较输入结果 history[i] = RemarkHistory(putIn, right); //作历史记录,以便随时查看 if(pareTo("4A")==0){
//使用者输入猜的四个数字(这四个数字之间也不能相同, 如果有相同的则提示使用者,并让 它重新输入)
public static int[] PutIn(String[] history){ int[] number = new int[4]; int putIn = 0; Scanner sc = new Scanner(System.in); System.out.println("请输入您猜想的 4 位数字"); PrintMenu(); out1: while(true){
System.out.println("欢迎你试玩猜数字游戏:"); System.out.println("请按 1 开始 2 退出"); Scanner s = new Scanner(System.in); int ch=0; ch = s.nextInt(); if(ch==1){
System.out.println("---------------------"); Scanner ca = new Scanner(System.in); int max =0; int j=0; int i=0; max= (int)(Math.random()*100); do{ System.out.println("请您输入数字:");
//如果输入英文、符号、小数等则提示并要求重新输入 try {
putIn = sc.nextInt(); } catch (Exception e) {
String str = sc.next(); if("Y".compareTo(str)==0 || "y".compareTo(str)==0) {main(null);} if("N".compareTo(str)==0 || "n".compareTo(str)==0) {System.exit(0);} if("H".compareTo(str)==0 || "h".compareTo(str)==0) {PrintHistory(history);} System.out.println("请输入正整数。"); continue; } //如果输入的不是 4 位数,提示并要求重新输入 if(putIn>9999 || putIn<100){ System.out.println("请输入一个 4 位数"); continue; } //把输入的一个 4 位数字变成数组 number[0] = putIn/1000; number[1] = putIn%1000/100; number[2] = putIn%100/10; number[3] = putIn%10; //如果有相同的数字,提示并要求重新输入 for(int i=0; i<4; i++){
public static void PrintHistory(String[] history){ for(int i=0; i<history.length; i++){
if("".compareTo(history[0])==0) {System.out.println("还没有输入内容"); continue;} if("".compareTo(history[i])==0) continue; System.out.println(history[i]); } } }
System.out.println("恭喜您,猜中了!!!"); PrintMenu(); menu(history); } } System.out.println("您已经猜了 10 次,本次游戏结束"); PrintMenu(); menu(history);
}
//自动产生四个 0~9 的数字作为随机数,这个四位数相互之间不能相同。 public static int[] MakeGuessNumber(){ Random r = new Random(); int[] guess = new int[4]; for(int i=0; i<4; i++){ guess[i] = r.nextInt(10); for(int j=i-1; j>=0; j--){ if(guess[i]==guess[j]){i--;break;} } } return guess; }
2、比较复杂的 import java.util.Random; import java.util.Scanner; public class Guess {
public static void main(String[] args) { //产生随机数 int[] guess = MakeGuessNumber(); System.out.print("系统产生的随机数为:"); for(int i=0; i<4; i++){
System.out.print(guess[i]); }System.out.println(); int[] putIn ;//定义用户输入 String right = ""; //临时保存比较的结果 String[] history = new String[]{"","","","","","","","","",""}; for(int i=0; i<10; i++){
case 5: System.out.println("您猜对了,您获得 60 分"); break; case 6: System.out.println("您猜对了,您获得 50 分"); break; case 7: System.out.println("您猜对了,您获得 40 分"); break; case 8: System.out.println("您猜对了,您获得 30 分"); break; case 9: System.out.println("您猜对了,您获得 20 分"); break; case 10: System.out.println("您猜对了,您获得 10 分"); break; default :System.out.println("对不起你没猜对"); break; } }else if(ch==2) { break;} } System.out.println("谢谢您的使用"); } }
j = ca.nextInt(); if(j<max){ System.out.println("太小哦"); } if(j>max){ System.out.println("太大哦"); } if(j==max){ break; } i++; }while(i<10); switch(i){ case 1: System.out.println("您猜对了,您获得 100 分"); break; case 2: System.out.println("您猜对了,您获得 90 分"); break; case 3: System.out.println("您猜对了,您获得 80 分"); break; case 4: System.out.println("您猜对了,您获得 70 分"); break;
猜数字游戏的两个 Java 程序代码
1、比较简单 import java.util.Scanner; import ng.Math; public class Cai { /**
* 生成 100 内的随即数然后 提示用户输入 * 用户输入数据猜 *提示用户 猜大了还是猜 小了 */
public static void main(String[] args) { while(true){
相关文档
最新文档