android猜数字游戏程序代码以及效果图
一段简单的猜数字代码

⼀段简单的猜数字代码⼀段简单的猜数字代码,要求是1,要猜的数字是随机数字1到9;2,猜数字次数为三次;3,如果猜中就打印提⽰语,并且结束程序;4,如果猜错就打印正确值还有剩下的次数;5,如果次数为0,就打印结束,欢迎下次再来。
⽂件名为:easy_guess.py,代码如下:1# !usr/bin/env python32# *-* coding:utf-8 *-*34'''5⼀个简单的猜数字游戏6要猜的数字为随机数字1到97猜的次数为38如果猜中就打印猜中的提⽰语9如果没猜中就打印正确值,还有剩下的次数10如果次数为0,就打印结束,欢迎下次再来11'''1213from random import randint #导⼊模块141516#num_input = int(input("Please input a number(range 1 to 9 ) to continue: ")) #输⼊数字17 guess_time = 0 #定义猜数字次数1819'''开始主循环'''20while guess_time < 4:21 num_input = int(input("PLease input a number(range 1 to 9) to continue: ")) #开始输⼊字符,因为从终端输⼊python认为是字符串,所以要在最前⾯⽤int()函数强制转化为整型,不然后续⽐较的时候会出现错误;22 number = randint(1,9) #定义随机数字,从1到923 remain_time = 3 - guess_time #定义剩下的猜字次数2425if num_input == number: #⽐较输⼊的数字是否和随机数相等,代码的第21⾏前如果没有转化成整型,这⾥会提⽰str不能与int进⾏⽐较;26print("Great guess, you are right!") #相等就执⾏27break#跳出主循环,后续的代码都不会再执⾏28elif num_input > number: #⽐较输⼊的数字是否⼤于随机数29print("Large\n The right number is: {}\n You have {} chances!".format(number,remain_time)) #满⾜条件就提⽰正确答案和剩余次数30elif num_input < number:31print("Small\n The right number is: {}\n You have {} chances!".format(number,remain_time)) #满⾜条件就提⽰正确答案和剩余次数3233 guess_time += 1 #每次循环完成都让猜字次数(guess_time)⾃加1,直到不满⾜主循环条件guess_time < 4上⾯的代码并不能执⾏如果次数为0 就打印结束,欢迎下次再来,⽽且也没有判断⽤户输⼊,下⾯把代码改⼀下,来完善⼀下,⽂件名为another_easy_guess.py:1# usr/bin/env python32# *-* coding:utf-8 *-*34from random import randint #导⼊模块56 guess_time = 0 #定义猜数字次数78'''开始主循环'''9while guess_time < 4:10 remain_time = 3 - guess_time #定义猜的次数11 num_input = input("Please input a number(integer range 1 to 9) to continue(You have {} times to guess): ".format(remain_time)) #开始输⼊12 number = randint(1,9) #定义随机数131415if guess_time >=0 and guess_time < remain_time: #猜的次数⼤于0还有⼩于剩余次数才会执⾏下⾯的代码块16if not num_input.isdigit(): #判定输⼊的是否是数字17print("Please input a integer to continue.") #如果不是数字,提⽰⽤户输⼊数字18elif int(num_input) < 0 or int(num_input) > 10: #判定是不是在我们设定的数字范围内19print("Please use the number 1 to 9 to compare.") #如果不是就提⽰20elif int(num_input) == number: #判定输⼊的数字是否与随机数相等21print("Great guess, you are right!")22break23elif int(num_input) > number: #判定输⼊数是否⼤于随机数24print("Large\n The right number is: {}\n There are {} chances for you!".format(number,(remain_time - 1)))25elif int(num_input) < number: #判定输⼊数是否⼩于随机数26print("Small\n The right number is: {}\n There are {} chances for you!".format(number,(remain_time - 1)))27else:28print("You have arrived the limited, see you next time!") #次数⼩于剩余次数后执⾏29break#跳出循环3031 guess_time += 1 #猜的次数⾃增1直到guess_time < 4;323334'''历史遗留问题:1,上⾯的代码只针对⽤户输⼊的数字,⽤户输⼊字符串也是会计算次数的;35 2,如果都没猜中且次数⽤完,是直接打印最后的You have arrived the limited, see you next time!⽽预期的提⽰正确答案。
Pythontkinter版猜数游戏

Pythontkinter版猜数游戏import randomimport tkinterimport tkinter.messageboximport tkinter.simpledialogroot = ()#窗⼝标题root.title('猜数游戏--by董付国')#窗⼝初始⼤⼩和位置root.geometry('280x80+400+300')#不允许改变窗⼝⼤⼩root.resizable(False, False)#⽤户猜的数varNumber = tkinter.StringVar(root, value='0')#允许猜的总次数totalTimes = tkinter.IntVar(root, value=0)#已猜次数already = tkinter.IntVar(root, value=0)#当前⽣成的随机数currentNumber = tkinter.IntVar(root, value=0)#玩家玩游戏的总次数times = tkinter.IntVar(root, value=0)#玩家猜对的总次数right = tkinter.IntVar(root, value=0)lb = bel(root, text='请输⼊⼀个整数:')lb.place(x=10, y=10, width=100, height=20)#⽤户猜数并输⼊的⽂本框entryNumber = tkinter.Entry(root, width=140, textvariable=varNumber)entryNumber.place(x=110, y=10, width=140, height=20)#只有开始游戏以后才允许输⼊entryNumber['state'] = 'disabled'#关闭程序时提⽰战绩def closeWindow():message = '本次共玩游戏 {0} 次,猜对 {1} 次!\n欢迎下次再玩!'.format(times.get(), right.get())tkinter.messagebox.showinfo('战绩', message)root.destroy()root.protocol('WM_DELETE_WINDOW', closeWindow)#按钮单击事件处理函数def buttonClick():if button['text']=='Start Game':#每次游戏时允许⽤户⾃定义数值范围#玩家必须输⼊正确的数while True:try:start = tkinter.simpledialog.askinteger('允许的最⼩整数', '最⼩数', initialvalue=1)breakexcept:passwhile True:try:end = tkinter.simpledialog.askinteger('允许的最⼤整数', '最⼤数', initialvalue=10)breakexcept:pass#在⽤户⾃定义的数值范围内⽣成随机数currentNumber.set(random.randint(start, end))#⽤户⾃定义⼀共允许猜⼏次#玩家必须输⼊正确的整数while True:try:t = tkinter.simpledialog.askinteger('最多允许猜⼏次?', '总次数', initialvalue=3)totalTimes.set(t)breakexcept:pass#已猜次数初始化为0already.set(0)button['text'] = '剩余次数:' + str(t)#把⽂本框初始化为0varNumber.set('0')#允许⽤户开始输⼊整数entryNumber['state'] = 'normal'#玩游戏的次数加1times.set(times.get() + 1)else:#⼀共允许猜⼏次total = totalTimes.get()#本次游戏的正确答案current = currentNumber.get()#玩家本次猜的数try:x = int(varNumber.get())except:tkinter.messagebox.showerror('抱歉', '必须输⼊整数')returnif x == current:tkinter.messagebox.showinfo('恭喜', '猜对啦')button['text'] = 'Start Game'#禁⽤⽂本框entryNumber['state'] = 'disabled'right.set(right.get() + 1)else:#已猜次数加1already.set(already.get()+1)if x > current:tkinter.messagebox.showerror('抱歉', '猜的数太⼤了')else:tkinter.messagebox.showerror('抱歉', '猜的数太⼩了')#可猜次数⽤完了if already.get()==total:tkinter.messagebox.showerror('抱歉', '游戏结束了,正确的数是:'+str(currentNumber.get())) button['text'] = 'Start Game'#禁⽤⽂本框entryNumber['state'] = 'disabled'else:button['text'] = '剩余次数:' + str(total-already.get())#在窗⼝上创建按钮,并设置事件处理函数button = tkinter.Button(root, text='Start Game', command=buttonClick)button.place(x=10, y=40, width=250, height=20)#启动消息主循环root.mainloop()有时间更改⼀下,感觉还不错哈import tkinterimport mathimport tkinter.messageboximport randomroot =()root.minsize(350,260)root.title('猜数字游戏')number=random.randint(1,20)def say_hello():print('hello,world!')def send_low():tkinter.messagebox.showinfo("messagebox","Your guess is too low.")def check_num():guess=text_guess.get()guess=int(guess)if guess>number:tkinter.messagebox.showinfo("height","Your guess is too height.")if guess < number:tkinter.messagebox.showinfo("low","Your guess is too low.")if guess == number:tkinter.messagebox.showinfo("good","Good job!")def btn_confirm():myName=text_name.get()tkinter.messagebox.showinfo("name",'Well,'+myName+',I am thinking of a number between 1 and 20.') #namelabel=bel(root,text="Wellcome to our game!")label.pack()label_name=bel(root,text="What's your name?")label_name.place(x=10,y=60)text_name=tkinter.Entry(root,width=20)text_name.place(x=10,y=90)btnOK=tkinter.Button(root,text="OK",command=btn_confirm)btnOK.place(x=200,y=90,height=28)#inputlabel_guess=bel(root,text='Take a guess:')label_guess.place(x=10,y=150)text_guess=tkinter.Entry(root,width=10)text_guess.place(x=90,y=150)btnCheck=tkinter.Button(root,text='Guess',command=check_num)btnCheck.place(x=200,y=150,width=45,height=28)root.mainloop()计算2。
猜数字游戏源代码

猜数字游戏本案例知识要点●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控制台应用程序的基本过程。
实验任务5-编写猜数游戏

实验任务5-编写猜数游戏【程序题⽬】编写猜数游戏【程序设计思想】⾸先⽤随机⽅法输出1-100的任意整数,输⼊猜的数字,⽤if else 判断与随机数字的⼤⼩,输出判断的结果,当没猜对的时候,⽤do while 循环输出继续游戏输⼊1,否输⼊0,当猜数成功时⽤do while 循环,输⼊0则进⾏下⼀轮循环,输⼊1 ,则退出。
【程序流程图】【源程序】//信1605-1 寇肖萌 20163446import javax.swing.JOptionPane;public class Number{public static void main(String args[]){String RandomNumber;int number1;int i;int c;do {i=(int)(Math.random()*101)+1;do {RandomNumber=JOptionPane.showInputDialog("随机数\n");number1 = Integer.parseInt(RandomNumber);if(number1==i){JOptionPane.showMessageDialog(null,"恭喜您","猜对了",JOptionPane.PLAIN_MESSAGE);}else if(number1<i){JOptionPane.showMessageDialog(null,null,"猜⼩了",JOptionPane.PLAIN_MESSAGE);}else{JOptionPane.showMessageDialog(null,null,"猜⼤了",JOptionPane.PLAIN_MESSAGE);}} while(number1!=i);String Number;Number=JOptionPane.showInputDialog(null,"是否要继续猜数,继续请输⼊1,否输⼊0\n"); c=Integer.parseInt(Number);}while(number1==i&&c==1);}}【实验结果截图】(此时若输⼊0,则退出程序输⼊1,则重新开始⼀个猜数游戏)【编译错误分析】刚开始不能执⾏新的猜数游戏,经过多次调试,我⼜多加⼀个do while 循环,当没猜对数时进⾏⼀直猜数的循环,当猜对之后并且选择继续游戏,输⼊1重新进⾏猜数游戏,输⼊0则退出游戏,当输⼊int型数字的时候,默认存储都是String类型,需要⽤Integer.parseInt()来转换。
加密码的猜数字游戏

if(n>num){
printf("太大了,没机会了\n");
}
else{
if(n<num){printf("太小了,没机会了!\n");
}
else{
printf("你猜对了\n");
printf("你真聪明!\n");
exit(0);
}
}
printf("你真笨\n");
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<time.h>
void youxi();
int main(){
youxi();
return 0;
}
void youxi(){
const int kouling=123;
int a;
scanf("%d",&n);
if(n>num){
printf("太大了,再好好想想\n");
}
else{
if(n<num){printf("太小了,再好好想想\n");
}
else{
printf("你猜对了\n");
printf("你真聪明!\n");
exit(0);
}
}
printf("再猜一次!!!\n");
scanf("%d",&n);
c猜数游戏源代码含登录等

c猜数游戏源代码含登录等预览说明:预览图片所展示的格式为文档的源格式展示,下载源文件没有水印,内容可编辑和复制c++猜数游戏源代码(含登录等)/*c++猜数游戏游戏规则:用户有7/6/5次机会猜测0~99的随机数,猜中+10/20/40分,没猜中-10/20/40分。
用户名、密码、分数被保存在文件中。
制作者:LH*/#include <iostream>#include <fstream>#include <string>#include <ctime>using namespace std;class Users{public:Users(); //构造函数,默认分数为0,用户个数为0,首次使用时建立一个文件void zpm(); //主屏幕private:void choose(); //选择void logo();//主图void dl(); //登录void zc(); //注册void yx_e(); //游戏_简单void yx_m(); //游戏_中等void yx_d(); //游戏_困难void gxsj(); //更新数据void choose_level();//选择级别string name; //当前用户名string mima; //当前密码string rmima; //确认密码int score; //当前分数int num; //计数int n; //用户的个数int score0[50]; //用于查找、比较。
下同。
string name0[50];string mima0[50];};Users::Users(){score=0;num=0;ifstream infile("user.dat");if(!infile) //如果打开失败,即文件不存在{ofstream outfile("user.dat"); //建立此文件outfile<<0<<'\'; //默认用户个数为0 outfile.close();}infile.close();}void Users::zpm(){logo();cout<<"游戏规则:\1.您需要有您的用户名和密码才能登录,如果您是新用户,请注册。
猜数字游戏源代码

#include <stdio.h>#include <stdlib.h>#include <process.h>#include <time.h>int main(){printf("\t\t * *\n");printf("\t\t * *\n");printf("\t\t * *\n");printf("\t\t *\n");printf("\t\t *\n");printf("\t\t *\n");printf("\t\t *\n");printf("\n");printf("\t\t *\n");printf("This is a number guessing game.\nJust guess and enjoy it!\nYou should input a number like 1234\n");system("pause");//游戏提示intanswer[4],a=0,b=0,i=0,j=0,guess,g[4],times=0,times_limit=12,win=0,lose=0,best_grade=13,round =0,alter1=1,alter2=1,rank=0,score=0;char face;//变量声明do{round++;times=0;system("cls");printf("Round:%d\tRank:%d\tScore:%d\tBestgrade:%d\n",round,rank,score,best_grade);printf("You will have %d chances to give your answer in this round\n",times_limit);//round初始化for(i=0;i<4;i++){srand((unsigned)time(NULL));answer[i]=rand()%10;for(j=0;j<i;j++){if(answer[j]==answer[i]){answer[i]=rand()%10;j=-1;}}}//随机生成4位answer//测试行printf("The answer is %d%d%d%d\n",answer[0],answer[1],answer[2],answer[3]);do{times++;printf("%2d\t",times);a=0;b=0;//计次,a,b单次初始化scanf("%d",&guess);g[0]=guess/1000;g[1]=(guess-g[0]*1000)/100;g[2]=(guess-g[0]*1000-g[1]*100)/10;g[3]=guess-g[0]*1000-g[1]*100-g[2]*10;//输入求guess各位数字for(i=0;i<4;i++){for(j=0;j<4;j++){b=b+(answer[i]==g[j]&&i!=j);a=a+(answer[i]==g[j]&&i==j);}}if(a!=4) face=1;else face=2;printf("\t%dA%dB\t%c\n",a,b,face);//比较求a,b并输出比较结果if(a<4&×==times_limit&&score>0){printf("Do you want to get an extra chance with one score?\ny(1)/n(0)\n");scanf("%d",&alter1);if(alter1==1){times--;score--;}}//用分数换次数}while(a!=4&×<times_limit);//处理给出答案直至答案正确或机会用完if(a==4){printf("Congratulations!\nYou are right!\n");win++;if(times<best_grade) best_grade=times;rank++;times_limit--;score++;}else{printf("Sorry.\nYou are wrong!\nThe answer is %d%d%d%d\n",answer[0],answer[1],answer[2],answer[3]);lose++;}printf("Round:%d\tWin:%d\tLose:%d\tScore:%d\tRank:%d\tBestgrade:%d\n",round,win,lose,score,rank,best_grade);//结果处理if(rank<10){printf("Continue?\ny(1)/n(0)\n");scanf("%d",&alter2);}}while(alter2==1&&rank<10);//等级至顶前选择是否继续system("cls");printf("Game over!\n");printf("Win:%d\tLose:%d\tRank:%d\tBest grade:%d\n",win,lose,rank,best_grade);system("pause");return 0;//结束处理}。
猜数字的编程程序

猜数字的编程程序
以下是一个简单的猜数字游戏的Python编程程序。
在这个游戏中,程序会随机选择一个在1到100之间的数字,然后让用户来猜这个数字。
如果用户猜的数字太大或太小,程序会给出相应的提示,直到用户猜中为止。
python
import random
def guess_number():
number_to_guess = random.randint(1, 100)
guess = None
attempt = 0
while guess != number_to_guess:
guess = int(input('猜一个1到100之间的数字: '))
attempt += 1
if guess < number_to_guess:
print('猜的数字太小了!')
elif guess > number_to_guess:
print('猜的数字太大了!')
print(f'恭喜你,你在{attempt}次尝试后猜中了数字{number_to_guess}!')
# 开始游戏
guess_number()
这个程序使用了Python的random模块来生成随机数,并使用了一个while 循环来让用户反复猜数字,直到猜中为止。
在每次循环中,程序都会检查用户猜的数字是否等于要猜的数字,如果不是,就会根据用户猜的数字的大小给出相应的提示。
最后,当用户猜中数字时,程序会打印出一条恭喜信息,并告诉用户他们用了多少次尝试才猜中这个数字。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
android真机测试运行效果图如下:以下是MainActivity.java文件//*************MainActivity.java************************* package com.example.guessinggame;import android.os.Bundle;import android.app.Activity;import android.content.Intent;import android.view.Menu;import android.view.View;import android.widget.Button;public class MainActivity extends Activity {private Button easyBtn; //响应“简单”按钮private Button normalBtn;//响应“标准”按钮private Button hardBtn; //响应“困难”按钮@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.activity_main);initControl(); //初始化控件}//初始化控件public void initControl(){easyBtn = (Button)findViewById(R.id.easy);normalBtn = (Button)findViewById(R.id.normal);hardBtn = (Button)findViewById(R.id.hard);}//响应button点击事件public void clickButton(View v){Intent intent = new Intent(MainActivity.this , GuessingGame.class);switch (v.getId()) {case R.id.easy:intent.putExtra("numOfData", 3);intent.putExtra("guessNums", 8);startActivity(intent);break;case R.id.normal:intent.putExtra("numOfData", 4);intent.putExtra("guessNums", 10);startActivity(intent);break;case R.id.hard:intent.putExtra("numOfData", 5);intent.putExtra("guessNums", 15);startActivity(intent);break;default:break;}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}以下是GuessingGame.java文件//***************GuessingGame.java****************package com.example.guessinggame;import java.util.ArrayList;import java.util.List;import android.app.Activity;import android.app.AlertDialog;import android.content.DialogInterface;import android.content.DialogInterface.OnClickListener;import android.graphics.Paint;import android.os.Bundle;import android.text.Editable;import android.text.TextWatcher;import android.view.KeyEvent;import android.view.Menu;import android.view.MenuItem;import android.view.View;import android.view.View.OnKeyListener;import android.widget.Button;import android.widget.EditText;import android.widget.ImageButton;import android.widget.TextView;import android.widget.Toast;public class GuessingGame extends Activity{private int guessNums; //猜测总次数private int guessCounts;//猜测次数统计private int numOfData; //给定猜测的位数private int[] randomNum; //生成随机数// private int countNums; //用户输入数字的位数统计private int[] userInputNum; //用户输入数字private StringBuffer ARight; //已经猜对的数字private int ARightLength; //ARight的长度private List<Integer> list; //用于记录用户按下的数字private ToolMethods toolMth; //获取随机数方法类private EditText editAnswer; //显示输入的答案private TextView guessingInfo;//显示猜测结果private ImageButton imageBtn; //提示按钮private Button createNum; //生成随机数按钮private Button answerBtn; //查看答案private Button guessBtn; //“开始猜”按钮private Button[] numButtons; //拥有0~9数字的button按钮//拥有0~9数字的ID号private int[] numButtonsID = {R.id.zero , R.id.one , R.id.two ,R.id.three , R.id.four , R.id.five ,R.id.six ,R.id.seven , R.id.eight , R.id.nine};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.guessing);init(); //初始化}private void init() {// 数据初始化int temp = 0;temp = getIntent().getIntExtra("guessNums", 0);guessNums = temp;temp = getIntent().getIntExtra("numOfData", 0);numOfData = temp;guessCounts = 0;randomNum = new int[numOfData];// countNums = 0;userInputNum = new int[numOfData];//方法类初始化toolMth = new ToolMethods();//控件初始化editAnswer = (EditText)findViewById(R.id.editAnswer);guessingInfo = (TextView)findViewById(R.id.guessingInfo);imageBtn = (ImageButton)findViewById(R.id.imageBtn);createNum = (Button)findViewById(R.id.randomNum);answerBtn = (Button)findViewById(R.id.answer);guessBtn = (Button)findViewById(R.id.guess);numButtons = new Button[10];for(int i = 0; i < 10; i++){numButtons[i]=(Button)findViewById(numButtonsID[i]);}createNum.setText("随机生成" + numOfData + "位数");editAnswer.setOnKeyListener(new onKeyListener());//输入框响应事件editAnswer.addTextChangedListener(new textWatcher());//输入字符串超过长度响应事件//getApplicationContext()对于整个应用处于运行期间有效toolMth.showDialog(GuessingGame.this , "吴康大侠,您好!", 3000, false, true);}//输入字符串超过长度响应事件public class textWatcher implements TextWatcher{private int selectionStart = 0;private int selectionEnd = 0;private CharSequence temp = null;@Overridepublic void onTextChanged(CharSequence s, int start, int before, int count) {}@Overridepublic void beforeTextChanged(CharSequence s, int start, int count,int after) {temp = s;}@Overridepublic void afterTextChanged(Editable s) {selectionStart = editAnswer.getSelectionStart();selectionEnd = editAnswer.getSelectionEnd();if(temp.length() > numOfData){Toast.makeText(GuessingGame.this, "请不要超过" + numOfData + "位数", Toast.LENGTH_SHORT).show();s.delete(selectionStart-1, selectionEnd);int tempSelection = selectionStart;editAnswer.setText(s);editAnswer.setSelection(tempSelection);}}}//输入框响应事件public class onKeyListener implements OnKeyListener{@Overridepublic boolean onKey(View v, int keyCode, KeyEvent event) {if(keyCode == KeyEvent.KEYCODE_DEL){if(editAnswer.getText().toString().length() < numOfData){for(Button tempBtn : numButtons){tempBtn.setEnabled(true);}}editAnswer.requestFocus();}if(keyCode == KeyEvent.KEYCODE_0 || keyCode == KeyEvent.KEYCODE_1 || keyCode == KeyEvent.KEYCODE_2 ||keyCode == KeyEvent.KEYCODE_3 || keyCode == KeyEvent.KEYCODE_4 || keyCode == KeyEvent.KEYCODE_5 ||keyCode == KeyEvent.KEYCODE_6 || keyCode == KeyEvent.KEYCODE_7 || keyCode == KeyEvent.KEYCODE_8 || keyCode == KeyEvent.KEYCODE_9){judgeNumsCount();}return false;}}//响应产生随机数的函数public void createNum(View v){randomNum = toolMth.createNum(numOfData);editAnswer.setVisibility(View.VISIBLE);createNum.setText("不重复的" + numOfData + "位数");createNum.setEnabled(false);answerBtn.setEnabled(true);guessBtn.setEnabled(true);for(int i = 0; i < 10; i++){numButtons[i].setEnabled(true);}}//响应0~9数字按钮的函数public void numButton(View v){for(int i = 0; i < 10; i++){if(v == numButtons[i]){//获取光标的位置int index = editAnswer.getSelectionStart();Editable editable = editAnswer.getText();editable.insert(index, numButtons[i].getText().toString());judgeNumsCount();break;}}}public void judgeNumsCount(){list = new ArrayList<Integer>();//当“输入位数”==“给定猜测的位数”时,数字按钮将失效if(editAnswer.getText().toString().length() == numOfData){for(Button tempBtn : numButtons){tempBtn.setEnabled(false);}int temp = Integer.parseInt(editAnswer.getText().toString());int[] tempNum = new int[numOfData];for(int j = 0; j < numOfData; j++){tempNum[j] = temp % 10;temp = temp/10;}for(int j = numOfData - 1; j >= 0 ; j--){list.add(tempNum[j]);}}else{for(Button tempBtn : numButtons){tempBtn.setEnabled(true);}}}public void guessButton(View v){int Acounts = 0; //统计A的次数int Bcounts = 0; //统计B的次数ARight = new StringBuffer("你已经猜对了:");ARightLength = ARight.length();if(v == guessBtn){if(editAnswer.getText().toString().length() !=numOfData){Toast.makeText(this, "请输入" + numOfData + "位数,不然不能猜的(⊙o⊙)哦~~", Toast.LENGTH_LONG).show();}else if(!toolMth.isRepeated(list)){Toast.makeText(this, "请不要输入重复数字", Toast.LENGTH_LONG).show();}else{judgeNumsCount();for(int i = 0; i < list.size(); i++){userInputNum[i] = list.get(i).intValue();}guessCounts++; //统计已经猜的次数for(int i = 0; i < numOfData; i++)for(int j = 0; j < numOfData; j++){if(userInputNum[i] == randomNum[j]){if(i == j){Acounts++; //统计A的次数ARight.append(userInputNum[i] + " 、");}else Bcounts++; //统计B的次数}}if(guessCounts == guessNums){if(Acounts == numOfData){toolMth.showDialog(GuessingGame.this, "您在最后一次机会中猜对了答案,恭喜您!", 3000, true, false);StringBuffer showStr = new StringBuffer(guessingInfo.getText().toString());showStr.append("\n" + editAnswer.getText().toString() + "---->" + Acounts + "A" + Bcounts + "B");guessingInfo.setText(showStr);}else{AlertDialog.Builder builder = new AlertDialog.Builder(GuessingGame.this).setTitle("可惜...").setMessage("已经超过" + guessNums + "次").setIcon(R.drawable.sad).setPositiveButton("确定", new OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {}});builder.create().show();}editAnswer.setVisibility(View.INVISIBLE);createNum.setText("随机生成" + numOfData + "位数");createNum.setEnabled(true);guessBtn.setEnabled(false);answerBtn.setEnabled(false);guessingInfo.setText("");guessCounts = 0;ARight.delete(0, ARight.length());}else if(Acounts == numOfData){if(guessCounts == 1){toolMth.showDialog(GuessingGame.this, "您在第一次就猜对了答案,太厉害了!", 3000, true, false);}else{toolMth.showDialog(GuessingGame.this, "恭喜您猜对了!", 3000, true, false);}StringBuffer showStr = new StringBuffer(guessingInfo.getText().toString());showStr.append("\n" + editAnswer.getText().toString() + "---->" + Acounts + "A" + Bcounts + "B");editAnswer.setVisibility(View.INVISIBLE);guessingInfo.setText(showStr);createNum.setText("随机生成" + numOfData + "位数");createNum.setEnabled(true);guessBtn.setEnabled(false);answerBtn.setEnabled(false);guessingInfo.setText("");guessCounts = 0;ARight.delete(0, ARight.length());}else{toolMth.showDialog(GuessingGame.this, "您没有猜对!", 3000, false, false);StringBuffer showStr = new StringBuffer(guessingInfo.getText().toString());showStr.append("\n" + editAnswer.getText().toString() + "---->" + Acounts + "A" + Bcounts + "B");guessingInfo.getPaint().setFakeBoldText(true);guessingInfo.getPaint().setAntiAlias(true);guessingInfo.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);guessingInfo.setText(showStr);}// countNums = 0;for(Button tempBtn : numButtons){tempBtn.setEnabled(true);}if(editAnswer.getText().toString().length() == numOfData){editAnswer.setText("");}}}}public void imageButton(View v){if(v == imageBtn){String tempTitle,tempMessage;if(ARight == null || ARight.length() <= 0){tempTitle = "提示:";tempMessage = "请开始吧!";}else if(ARight.length() == ARightLength){tempTitle = "可惜…";tempMessage = "抱歉,你没有答对";}else{tempTitle = "提示:";tempMessage = ARight.substring(0, ARight.length()-1);}AlertDialog.Builder builder = new AlertDialog.Builder(GuessingGame.this);builder.setTitle(tempTitle).setMessage(tempMessage).setPositiveButton("确定", new OnClickListener() {public void onClick(DialogInterface dialog, int which) {}});builder.create().show();}}public void answerButton(View v){StringBuffer answerStr = new StringBuffer();for(int temp : randomNum){answerStr.append(temp);}AlertDialog.Builder builder = new AlertDialog.Builder(GuessingGame.this);builder.setTitle("答案如下:").setMessage(answerStr).setPositiveButton("确定", new OnClickListener() {public void onClick(DialogInterface dialog, int which) {}});builder.create().show();}public boolean onCreateOptionsMenu(Menu menu) {super.onCreateOptionsMenu(menu);/** add()方法的四个参数,依次是:1、组别,如果不分组的话就写Menu.NONE,* 2、Id,这个很重要,Android根据这个Id来确定不同的菜单3、顺序,那个菜单现在在前面由这个参数的大小决定* 4、文本,菜单的显示文本*/menu.add(1, 1, 1, "帮助");menu.add(1, 2, 2, "关于");return true;}@Overridepublic boolean onOptionsItemSelected(MenuItem item) {AlertDialog.Builder builder = new AlertDialog.Builder(this);switch (item.getItemId()) {case 1:builder.setTitle("帮助").setMessage(R.string.guessingGame).setPositiveButton("确定", new OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {}});builder.create().show();break;case 2:builder.setTitle("关于").setMessage("玉树临风,嘿嘿~~").setPositiveButton("确定", new OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {}});builder.create().show();break;default:break;}return super.onOptionsItemSelected(item);}}以下是ToolMethods.java文件//****************** ToolMethods.java**************** package com.example.guessinggame;import java.util.HashSet;import java.util.List;import java.util.Set;import android.content.Context;import android.view.Gravity;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.Toast;public class ToolMethods {//public int[] createNum(int numOfData) {int[] randomNum = new int[numOfData];int i = 0;String[] tempArray;do{tempArray = getNumber(numOfData);}while(!isRepeated(tempArray));for(String tempNum : tempArray){randomNum[i++] = Integer.parseInt(tempNum);}return randomNum;}//生成随机数(字符串类型)private String[] getNumber(int numOfData) {String[] tempArray = new String[numOfData];for(int i = 0; i < numOfData; i++){int tempNum = (int)(Math.random()*10);tempArray[i] = String.valueOf(tempNum);}return tempArray;}//验证随机数是否重复private boolean isRepeated(String[] tempArray) {Set<String> set = new HashSet<String>();for(String tempStr : tempArray){set.add(tempStr);}if(set.size() != tempArray.length){return false;}return true;}//验证随机数是否重复public boolean isRepeated(List<Integer> list) {Set<Integer> set = new HashSet<Integer>();for(int i = 0; i < list.size(); i++){set.add(list.get(i));}if(set.size() != list.size()){return false;}return true;}public void showDialog(Context context, String message, int milliseconds, boolean useSmileImage, boolean useCoolImage){Toast dialog = Toast.makeText(context, message, Toast.LENGTH_LONG);dialog.setGravity(Gravity.CENTER, 0, 0);LinearLayout dialogView = (LinearLayout)dialog.getView();ImageView useImage = new ImageView(context);if(useSmileImage){useImage.setImageResource(R.drawable.smile);}else if(useCoolImage){useImage.setImageResource(R.drawable.cool);}else{useImage.setImageResource(R.drawable.sad);}dialogView.addView(useImage, 0);dialog.setDuration(milliseconds);dialog.show();}}。