Java 控制台游戏(砸金花)
- 格式:rtf
- 大小:63.06 KB
- 文档页数:10
JAVA实现⽃地主《⽹络编程》结课报告课题⽃地主学院计算机学院专业计算机科学与技术班级17052318姓名任庆(17220624)指导教师吴永胜完成⽇期2020 年5⽉⽬录第1章绪论 (3)第2章系统设计 (3)2.1⽹络通信 (3)1.传输层协议选择:TCP (3)2.通信草图 (3)2.2同步 (4)1.游戏五⼤阶段 (4)2.流程图 (4)2.3语法语义分析 (4)1.范围 (4)2.语法 (4)3.语义 (4)第3章编码调试 (5)3.1TCP通信 (5)1.客户端 (5)2.服务器 (5)3.实现 (6)3.2同步 (7)1.阶段定义 (7)2.信号量 (7)3.主服务器 (7)4.服务器接收端 (8)5.主客户端 (8)6.客户端接收器 (8)7.同步序列码 (9)3.3语法语义 (9)1.卡牌定义 (9)2.出牌类型 (9)3.语法检查 (10)4.⽐较⼤⼩ (10)3.4打印卡牌 (10)1.原理 (10)2.实现效果 (11)第4章测试运⾏ (11)4.1Waiting (11)4.2Preparation (12)4.3Selecting (12)4.4Running (13)4.5Finish (13)第5章体会总结 (14)参考⽂献 (14)第1章绪论因为这门课是⽹络编程嘛,当然要完成的东西得在多台机器上完成,围绕着通信这个核⼼基础功能展开,因为⽃地主⼩时候玩的⽐较多,对⾥⾯的规则⾮常的熟悉,⽽且我感觉这个游戏刚好是我能够做的,感觉做起来会⽐较有意思,所以选了这个游戏来进⾏开发。
正巧这个学期选了⼀门JA V A语⾔,也为了更加深⼊的了解⼀下这门语⾔,所以决定选这门语⾔作为这个游戏的开发语⾔。
第2章系统设计2.1 ⽹络通信1.传输层协议选择:TCP原因:因为这个游戏数据传输⽐较严谨,有⼀点差错系统可能就瘫痪了,所以选择TCP来作为通信基础。
2.通信草图服务器得有⼀个监听线程,若监听到⼀个客户端,就创建⼀个接收线程和⼀个发送线程负责和客户端进⾏通信,因为是⽃地主,三⼈游戏,三个客户端就够了。
局域网三人斗地主程序(java版)说明:本程序支持局域网游戏,运行服务器端后,再运行三个客户端分别输入服务器端的IP 即可以游戏。
附件说明:扑克牌重1~54命名,分别为3到大王(四个一组,大小王除外,比如1.jpg,2.jpg都是3),0.jpg 为扑克牌的反面可以从网上下载。
声音文件参考QQ斗地主。
服务器端:三个四个类分别是:IMServer.java客户端主类IMServer.javaimport java.awt.BorderLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.*;import .ServerSocket;import .Socket;import java.util.*;import javax.swing.*;@SuppressWarnings("serial")public class IMServer extends JFrame implements ActionListener{private int command0=0;//记录接收重新开机的指令数目private int command1=0;//记录接收是否叫地主的指令数目private static ArrayList Dizhu=new ArrayList();private static final int maxThreadLimit = 10;private static int OnlineNumber=0;private JPanel p = new JPanel();DealCard test;String Command;private ArrayList Users=new ArrayList();public int[] Arr=new int[21];private JTextField jtf = new JTextField();private JTextArea jta = new JTextArea();private ArrayList<ThreadServer> threadArray = new ArrayList<ThreadServer>(); //线程数组,用于存放连接线程public IMServer(){p.setLayout(new BorderLayout());p.add(new JLabel("发送(回车)"),BorderLayout.WEST);p.add(jtf,BorderLayout.CENTER);jtf.setHorizontalAlignment(JTextField.RIGHT);getContentPane().setLayout(new BorderLayout());getContentPane().add(new JScrollPane(jta),BorderLayout.CENTER);getContentPane().add(p,BorderLayout.SOUTH);jta.setEditable(false);jtf.setHorizontalAlignment(javax.swing.JTextField.LEFT);jtf.addActionListener(this);setTitle("IM");setSize(500,300);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setVisible(true);new Thread(new Runnable() {@Overridepublic void run() {while(true){if(command0==3){CreatPai();command0=0;}else if(command1==3){int chose1 = 0;for(int i=0;i<10000;i++){}if(Dizhu.isEmpty()){JOptionPane.showMessageDialog(null,"没人抢地主,随机发牌");chose1=(int)(Math.random()*3)+1;}else{int number=(int)(Math.random()*Dizhu.size())+1;Integer chose=(Integer) Dizhu.get(number-1);chose1=chose.intValue();}Dizhu.clear();System.out.println(chose1);guangBo(" 地主是:"+chose1+"系统广播者");guangBo(" 地主是正在出牌");String send=test.CreatDizhu(chose1);System.out.println("地主的牌的是:"+send);guangBo("12|"+chose1+send);guangBo("13|"+chose1+test.dipai);command1=0;}}}}).start();try{ServerSocket serverSocket = new ServerSocket(8189);jta.append("服务器开启时间:" + new Date() + '\n');while(true){if(threadArray.size() >= maxThreadLimit){try{Thread.sleep(1000);}catch(InterruptedException ex){}}else{Socket socket = serverSocket.accept();BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); String name=in.readLine();OnlineNumber++;jta.append("用户"+name+ "上线: ("+new Date() +")" +'\n');jta.append("当前在线人数:"+OnlineNumber+"人\n");ThreadServer thread = new ThreadServer(OnlineNumber,name,socket);threadArray.add(thread);Users.add("|"+name);thread.start();try {Thread.sleep(100);if(OnlineNumber>2){for(int i=0;i<3;i++)threadArray.get(i).send("ID"+Users.get(0)+Users.get(1)+Users.get(2));System.out.println(Users);System.out.println(Users);CreatPai();}} catch (InterruptedException ex) {}}}}catch(IOException e){System.err.println(e);}}private void CreatPai(){test=new DealCard();threadArray.get(0).send("11|"+1+er1);threadArray.get(1).send("11|"+2+er2);threadArray.get(2).send("11|"+3+er3);}public static void main(String[] args){new IMServer();}@Overridepublic void actionPerformed(ActionEvent arg0){if (arg0.getSource() instanceof JTextField){String s = jtf.getText();if(s != null){guangBo(" 系统消息:"+s);s = null;}jtf.setText("");}}public void guangBo(String s) //向所有客户端监听线程发送消息{StringTokenizer st = new StringTokenizer(s,"|");st.nextToken();jta.append(s+ '\n');//if(st.hasMoreElements()){if(threadArray.size() > 0) //遍历这个线程数组{for(int i = 0;i < threadArray.size();i++){threadArray.get(i).send(s);System.out.println(i+": "+s);}}}//线程内部类class ThreadServer extends Thread{private Socket incoming;private String name;private int num;private PrintWriter out;public ThreadServer(int num,String name,Socket i){this.num=num;=name;incoming = i;}public int getnum() {return num;}public String getname(){return name;}@Overridepublic void run(){// TODO Auto-generated method stubsynchronized(this){try{try{BufferedReader inStream = new BufferedReader(new InputStreamReader(incoming.getInputStream()));OutputStream outStream = incoming.getOutputStream();out = new PrintWriter(outStream, true);while(true){String s = inStream.readLine();System.out.println(s);StringTokenizer st = new StringTokenizer(s,"|");String command=st.nextToken();if(st.hasMoreElements()){if(command.equals("error")){String name=st.nextToken();int num=Integer.parseInt(name);switch(num){case 1:this.send("11|"+1+er1);break;case 2:this.send("11|"+2+er2);break;case 3:this.send("11|"+2+er2);break;default:System.exit(-1);}}if(command.equals("20")){command0++;}else if(command.equals("21")){String name1=st.nextToken();String dizhu=st.nextToken();if(dizhu.equals("yes")){Dizhu.add(Integer.parseInt(name1));}command1++;}else if(command.equals("22")){String name1=st.nextToken();if(s.endsWith("|")){String realmsg=s.substring(3);guangBo(" 玩家"+name1+"不出牌");guangBo("14|"+realmsg+"|-1");}else{String realmsg=s.substring(3);System.out.println(realmsg);guangBo(" 玩家"+name1+"正在出牌");guangBo("14|"+realmsg);}}else if(command.equals("23")){String name1=st.nextToken();guangBo("15|"+name1);}else if(command.equals("talk")){String msg=st.nextToken();if(msg.length()>0)guangBo(s);}}else if(s.length()>0 && !s.equalsIgnoreCase("EXIT")) {guangBo(s);s = null;}else if(s.equalsIgnoreCase("EXIT")){break;}}}catch(.SocketException e){System.out.println("有用户退出");threadArray.remove(this);}finally{incoming.close();}}catch(IOException e){e.printStackTrace();}}}public void send(String s){if(s != null){out.println(s);}}}public String analysisMsg(String msg){StringTokenizer st = new StringTokenizer(msg,"|");String realMsg=st.nextToken();if(st.hasMoreElements()){String strre = st.nextToken();//读取用户名}//获取信息时间java.text.DateFormat format1 = new java.text.SimpleDateFormat("HH:mm:ss");String strTime = format1.format(new Date());strTime="("+strTime+")";return msg+strTime;}public String ChangeVector(ArrayList v) { //将向量封装成字符串String RealMsg="";for(int i=0;i<v.size();i++){RealMsg+="|"+v.get(i);}return RealMsg;}public String PackMsg(int command,String realMsg){return command+"|Server"+realMsg;}}随机产生排的54不重复的随机数RandomCard.javapublic class RandomCard {public int [] arr=new int[55];public RandomCard(){for(int i=1;i<55;i++){arr[i]=0;}}public int CreatRadom(){int Radom1=(int)(Math.random()*54)+1;if(arr[Radom1]==0) arr[Radom1]=1;else{while(arr[Radom1]==1){Radom1=(int)(Math.random()*54)+1;}arr[Radom1]=1;}return Radom1;}/* public static void main(String[] args) {Radom c= new Radom();for(int i=1;i<55;i++){System.out.println(c.CreatRadom()+" "+i);}}**/}对随机数排序CreateCard,javapublic class CreateCard {public int[] imgPath=new int[55];static RandomCard r;public CreateCard(){r=new RandomCard();for(int i=1;i<55;i++){int j=r.CreatRadom();imgPath[i]=j;}this.maoPao(imgPath,1,17);this.maoPao(imgPath,18,34);this.maoPao(imgPath,35,51);this.maoPao(imgPath,52,54);}public static void maoPao(int[] x,int begin,int end) {for (int i = begin; i <end; i++) {for (int j = i + 1; j <=end; j++) {if (x[i] > x[j]) {int temp = x[i];x[i] = x[j];x[j] = temp;}}}}public void prinArray(){for(int i=1;i<55;i++){if(i%17==1) {System.out.println();}System.out.println(imgPath[i]);}}/*public static void main(String[] args) {CreateCard c= new CreateCard();c.prinArray();}**/}服务器布牌DealCard.javaimport java.util.StringTokenizer;public class DealCard {CreateCard cr;public String user1="";public String user2="";public String user3="";public String dipai="";public String dizhu="";//地主底牌public int dizhu1;//产生的地主public int[] card;public DealCard(){this.ChangeToString();}public void ChangeToString(){cr=new CreateCard();card=cr.imgPath;for(int i=1;i<card.length;i++){if(i<18) user1+="|"+card[i];else if(i<35) user2+="|"+card[i];else if(i<52) user3+="|"+card[i];else dipai+="|"+card[i];}}public String SortString(String str){String newString="";int[] arr=new int[20];StringTokenizer st = new StringTokenizer(str,"|");int i=0;while (st.hasMoreTokens()){arr[i]=Integer.parseInt(st.nextToken());i++;}CreateCard.maoPao(arr,0,19);for(int j=0;j<arr.length;j++){newString+="|"+arr[j];}return newString;}public String CreatDizhu(int dizhu1) //根据提交的叫地主的情况随机产生地主{switch(dizhu1){case 1:return SortString(user1+dipai);case 2:return SortString(user2+dipai);case 3:return SortString(user3+dipai);default:System.exit(-1);}return null;}public static void main(String[] args){DealCard test=new DealCard();System.out.println(er1);System.out.println();System.out.println();}}客户端程序:主类MainClinet.javaimport java.awt.Color;import java.awt.Dimension;import java.awt.Toolkit;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import .Socket;import javax.swing.*;import java.util.*;import java.io.*;/**** @author Administrator*/public class MainClient extends JFrame implements ActionListener,Runnable,MouseListener {Socket socket;JTextField textTalk;JComboBox listOnline; //在线用户列表boolean ischupai=false;//标记是否出牌JLabel right=new JLabel("当前牌数为"+17);//标记剩余牌数JLabel left=new JLabel("当前牌数为"+17);//标记剩余牌数JLabel current=new JLabel("当前牌数为"+17);//标记剩余牌数JLabel right1=new JLabel();//标记剩余牌数JLabel left1=new JLabel();//标记剩余牌数JLabel current1=new JLabel();//标记剩余牌数JLabel[] labplayer={new JLabel(""),new JLabel(""),new JLabel("")};JButton start =new JButton("开始");JButton yes =new JButton("叫地主");JButton no =new JButton("不叫");Compare compare=new Compare();DealCard music=new DealCard();JLabel[] labdipai=new JLabel[3];private JTextArea jta = new JTextArea();private JTextArea jta1 = new JTextArea();private OutputStream toServer;private PrintWriter out;private BufferedReader in;private String Id;private String Username;private String[] Users=new String[3];Thread th=new Thread(this,"listen");ArrayList PlayCard=new ArrayList();//记录要出的牌ArrayList PlayCard1=new ArrayList();//记录上个玩家出牌ArrayList PlayCard2=new ArrayList();//记录上一个玩家出牌public static ArrayList RecordCard=new ArrayList();//记录玩家出牌ArrayList LeftCard=new ArrayList();//记录剩下的牌DealLabel[] labelPic=new DealLabel[20];JLabel[] lab=new JLabel[20];JLabel[] labr1=new JLabel[20];JLabel[] labr2=new JLabel[20];JLabel[] labl1=new JLabel[20];JLabel[] labl2=new JLabel[20];private JButton ibLeftSec;private JButton isbuchuR;private JButton isbuchuL;private Thread time, clocker;public static long startTime, endTime;long nowTime, leftTime, leftSec, leftMin;boolean flag = false;String msg;String Command;private String last;private String dizhu;public int[] Arr;public int loc=760; //当前玩家出牌的相对位置public int locr=580; //当前玩家出牌的相对位置public int locl1=580; //当前玩家出牌的相对位置public int locl2=500; //当前玩家出牌的相对位置private JButton buttonTalk;String IP;//服务器IP地址public MainClient(String name,String IP){this.setTitle("玩家"+name);ername=name;this.IP=IP;this.setLayout(null);setExtendedState(JFrame.MAXIMIZED_BOTH);setResizable(false);Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();init();getContentPane().setBackground(Color.GREEN);new Thread(new Runnable() {public void run() {int i=1;while(true){new Sound().play("b"+String.valueOf(i));i++;if(i>5) i=1;try{Thread.sleep(32000);}catch(Exception e) {}}}}).start();this.Bupai();clocker = new Thread(this, "clock");clocker.start();time = new Thread(this, "ti");time.start();this.setVisible(true);int width = (int)screensize.getWidth();int height = (int)screensize.getHeight();int mainloc=width/2-643;if(mainloc<10) this.setLocation(50, 0);else this.setLocation(mainloc, 0);this.setSize(1286,718); //根据我的电脑设计的大小this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);}void init(){for(int i=0;i<3;i++){labplayer[i].setSize(80, 40);this.add(labplayer[i]);}buttonTalk = new JButton("发送");buttonTalk.setSize(60, 30);buttonTalk.setLocation(1080, 570); buttonTalk.setFocusable(false); buttonTalk.addActionListener(this);this.add(buttonTalk);isbuchuR= new JButton("不出") ; isbuchuR.setFocusable(false); isbuchuR.setEnabled(false);isbuchuR.setBackground(Color.red); isbuchuR.setBounds(120,300, 62, 40); isbuchuL= new JButton("不出") ; isbuchuL.setFocusable(false);isbuchuL.setEnabled(false);isbuchuL.setBackground(Color.red); ibLeftSec = new JButton("");isbuchuL.setBounds(900,300, 62, 40); ibLeftSec.setFocusable(false); ibLeftSec.setEnabled(false);ibLeftSec.setBackground(Color.red);this.add(ibLeftSec);isbuchuR.setVisible(false);isbuchuL.setVisible(false);this.add(isbuchuR);this.add(isbuchuL);listOnline=new JComboBox(); listOnline.addItem("All");listOnline.setLocation(1160, 600); listOnline.setSize(58, 30);this.add(listOnline);JLabel labtalk=new JLabel("玩家聊天记录"); labtalk.setBounds(1150, 540,80, 40);this.add(labtalk);JLabel labre=new JLabel("消息接受者"); labre.setBounds(1080, 600,80, 40);this.add(labre);textTalk = new JTextField(20);textTalk.setSize(120, 30);textTalk.setLocation(1150,570); textTalk.addActionListener(this);this.add(textTalk);this.add(listOnline);JLabel lab1=new JLabel("玩家发送消息");JLabel lab2=new JLabel("<html>系<br>统<br>消<br>息<br>区<br>"); lab1.setBounds(1150, 20,80, 40);lab2.setBounds(5, 0,40,100);right.setBounds(890, 270, 120, 40);left.setBounds(130, 270, 120, 40);current.setBounds(560, 500, 120, 40);right1.setBounds(860, 270, 120, 40);left1.setBounds(100, 270, 120, 40);current1.setBounds(530, 500, 120, 40);this.add(lab1);this.add(lab2);this.add(right);this.add(left);this.add(current);this.add(right1);this.add(left1);this.add(current1);jta.setLocation(25, 5);jta.setSize(240, 100);jta.setVisible(true);jta1.setLocation(900, 5);jta1.setSize(140, 600);jta1.setVisible(true);start.setSize(60, 40);start.setLocation(540, 470);start.setFocusable(false);start.setVisible(true);start.setActionCommand("start");start.addActionListener(this);yes.setSize(73, 40);yes.setLocation(450, 470);yes.setFocusable(false);yes.setVisible(false);yes.setActionCommand("yes");yes.addActionListener(this);no.setSize(73, 40);no.setLocation(650, 470);no.setFocusable(false);no.setVisible(false);no.setActionCommand("no");no.addActionListener(this);jta.setEditable(true); //设置可编辑JScrollPane jsp = new JScrollPane(jta); //添加滚动条jsp.setBounds(25,0,240,100); //设置JScrollPane 宽100,高200jta1.setEditable(true); //设置可编辑JScrollPane jsp1 = new JScrollPane(jta1); //添加滚动条jsp1.setBounds(1110,50,150,500); //设置JScrollPane 宽100,高200this.add(jsp); //将组件加入容器this.add(jsp1); //将组件加入容器this.add(start);this.add(yes);this.add(no);}@Overridepublic void actionPerformed(ActionEvent e){String cmd=e.getActionCommand();if (e.getSource() instanceof JTextField){String s =textTalk.getText();if(s.length()>0){java.text.DateFormat format1 = new java.text.SimpleDateFormat("HH:mm:ss");String strTime = format1.format(new Date());strTime="("+strTime+")";jta1.append("玩家"+Id+": "+s+strTime);out.println("talk|"+s+"|"+Id+"|"+listOnline.getSelectedItem().toString());s = "";}textTalk.setText("");}if(e.getSource()==buttonTalk){String s =textTalk.getText();if(s.length()>0){java.text.DateFormat format1 = new java.text.SimpleDateFormat("HH:mm:ss");String strTime = format1.format(new Date());strTime="("+strTime+")";jta1.append(ername+": "+s+strTime+"\n");out.println("talk|"+s+"|"+Id+"|"+listOnline.getSelectedItem().toString());s="";}textTalk.setText("");}if(cmd.equals("start")){th.start();start.setVisible(false);start.setText("重新开局");start.setSize(100, 40);start.setActionCommand("restart");}else if(cmd.equals("yes")){out.println("21|"+Id+"|yes");yes.setText("出牌");no.setText("不出");no.setActionCommand("buchu");yes.setActionCommand("chu");yes.setVisible(false);no.setVisible(false);}else if(cmd.equals("no")){out.println("21|"+Id+"|no");yes.setText("出牌");no.setText("不出");no.setActionCommand("buchu");yes.setActionCommand("chu");yes.setVisible(false);no.setVisible(false);}else if(cmd.equals("chu")) //按键出牌{this.Chupai();}else if(cmd.equals("buchu")){if(PlayCard2.isEmpty()&&PlayCard1.isEmpty()){JOptionPane.showMessageDialog(null,"必须出牌","警告",JOptionPane.WARNING_MESSAGE);}else{PlayCard.clear();for(int i=0;i<LeftCard.size();i++){Integer p=(Integer)(LeftCard.get(i));int k2=p.intValue();labelPic[k2].setBounds(loc-(i+1)*25, 540, 80, 100);labelPic[k2].sign=false;}String send="22|"+Id+"|"+LeftCard.size();out.println(send);yes.setVisible(false);no.setVisible(false);isbuchuL.setVisible(false);isbuchuL.setVisible(false);ischupai=false;new Sound().play("buyao"+(int)(Math.random()*4+1));}}else if(cmd.equals("restart")){out.println("20|"+Id+"|start");start.setVisible(false);for(int i=0;i<20;i++){if(i<3)labdipai[i].setIcon(null);lab[i].setIcon(null);labl1[i].setIcon(null);labl2[i].setIcon(null);labr1[i].setIcon(null);labr2[i].setIcon(null);labelPic[i].setIcon(null);labr1[i].setBounds(1000,locr-i*25, 80, 100);labl1[i].setBounds(20,locl1-i*25, 80, 100);labelPic[i].setBounds(loc-(i+1)*25, 540, 80, 100);if(i<17){labr1[i].setIcon(newImageIcon(getClass().getResource("./tupian/"+0+".jpg")));labl1[i].setIcon(newImageIcon(getClass().getResource("./tupian/"+0+".jpg")));}}LeftCard.clear();PlayCard.clear();PlayCard1.clear();yes.setActionCommand("yes");yes.setText("叫地主");no.setActionCommand("no");no.setText("不叫");current.setText("当前牌数为17");left.setText("当前牌数为17");right.setText("当前牌数为17");isbuchuL.setVisible(false);isbuchuR.setVisible(false);current1.setText("");left1.setText("");right1.setText("");ischupai=false;}}public void connection(String name){try{//socket = new Socket("222.27.243.169",8189);socket = new Socket(IP,8189);toServer = socket.getOutputStream();in = new BufferedReader(new InputStreamReader(socket.getInputStream()));out = new PrintWriter(toServer, true);out.println(name);while(true){String s = in.readLine();if(s!=null){if(s.substring(0,1).endsWith(" "))jta.append(s+"\n");elseDealMsg(s);}s = null;}}catch(IOException e){jta.append("Server doesn't start"+"\n");System.exit(-1);}}@Overridepublic void run(){if(Thread.currentThread()==th){this.connection(Username);}Calendar now;while(((Thread.currentThread()).getName()).equals("clock")){now = Calendar.getInstance();nowTime = now.getTime().getTime();}while(((Thread.currentThread()).getName()).equals("ti"))while(flag){leftTime = endTime - nowTime;leftSec = leftTime/1000;leftMin = leftTime/(60*1000);ibLeftSec.setText(leftSec+"秒");if(leftSec == 0){flag = false;JOptionPane.showMessageDialog(this, "超时!\n时间到", "超时" , JOptionPane.OK_OPTION);break;}}}public void Bupai(){for(int i=0;i<20;i++){labelPic[i]=new DealLabel();lab[i]=new JLabel();labl1[i]=new JLabel();labl2[i]=new JLabel();labr1[i]=new JLabel();labr2[i]=new JLabel();labelPic[i].setBounds(loc-(i+1)*25, 540, 80, 100);lab[i].setBounds(loc-i*25,420, 80, 100);labr1[i].setBounds(1000,locr-i*25, 80, 100);labr2[i].setBounds(930-i*25,300, 80, 100);//左边外面labl1[i].setBounds(20,locl1-i*25, 80, 100);labl2[i].setBounds(locl2-i*25,300, 80, 100);//右边外面if(i<3){labdipai[i]=new JLabel();labdipai[i].setBounds(600-i*40, 5, 80, 100);this.add(labdipai[i]);}if(i<17){labr1[i].setIcon(newImageIcon(getClass().getResource("./tupian/"+0+".jpg")));labl1[i].setIcon(newImageIcon(getClass().getResource("./tupian/"+0+".jpg")));}labelPic[i].setFocusable(false);labelPic[i].sign=false;labelPic[i].addMouseListener(this);this.add(lab[i]);this.add(labr1[i]);this.add(labr2[i]);this.add(labl1[i]);this.add(labl2[i]);this.add(labelPic[i]);}}@Overridepublic void mouseClicked(MouseEvent e){if(!e.isMetaDown()){//鼠标没有右击,已经左击if(!PlayCard.isEmpty())PlayCard.clear();for(int i=0;i<LeftCard.size();i++){Integer p=(Integer)(LeftCard.get(i));int k=p.intValue();if(e.getSource()==labelPic[k]){if(!labelPic[k].sign){labelPic[k].setBounds(loc-(i+1)*25, 520, 80, 100);labelPic[k].sign=true;}else{labelPic[k].setBounds(loc-(i+1)*25, 540, 80, 100);labelPic[k].sign=false;}}}}else //右键出牌{this.Chupai();}}@Overridepublic void mousePressed(MouseEvent e) {}@Overridepublic void mouseReleased(MouseEvent e) {}@Overridepublic void mouseEntered(MouseEvent e) {}@Overridepublic void mouseExited(MouseEvent e) {}public void AnMsg(String msg) //解析消息{StringTokenizer st = new StringTokenizer(msg,"|");int i=0;Arr=new int[20];while (st.hasMoreTokens()){if(i==0)Command=st.nextToken();else if(i==1)last=st.nextToken();elseArr[i-2]=Integer.parseInt(st.nextToken());i++;}}public String ChangeVector(ArrayList v){ //将向量封装成字符串String RealMsg="";for(int i=0;i<v.size();i++){RealMsg+="|"+v.get(i);}return RealMsg;}public void loadImg(){LeftCard.clear();System.out.println("接收到的牌:");for(int i=0;i<20;i++){labelPic[i].setIcon(null);labelPic[i].sign=false;if(Arr[i]!=0){labelPic[i].setIcon(newImageIcon(getClass().getResource("./tupian/"+Arr[i]+".jpg")));System.out.print(" "+Arr[i]);labelPic[i].setVisible(true);labelPic[i].number=Arr[i];LeftCard.add(i);}else{labelPic[i].setIcon(null);}labelPic[i].setBounds(loc-(i+1)*25, 540, 80, 100);}System.out.println();System.out.println();System.out.println();System.out.println("向量Leftcard"+LeftCard);System.out.println();System.out.println();if(LeftCard.size()!=17&&LeftCard.size()!=20){// JOptionPane.showMessageDialog(null, "发牌有误,重新发牌,请等待");//未处理out.println("error|"+this.Id);}}public void DealMsg(String s){StringTokenizer st = new StringTokenizer(s,"|");String command=st.nextToken();if(command.equals("ID")){Users[0]=st.nextToken();Users[1]=st.nextToken();Users[2]=st.nextToken();for(int i=0;i<3;i++){if(ername.equals(Users[i])){this.Id=i+1+"";labplayer[0].setText(ername);labplayer[0].setLocation(560, 470);}else listOnline.addItem(Users[i]);}int Idnum=Integer.parseInt(Id);labplayer[1].setText(Users[Idnum%3]);labplayer[1].setLocation(890, 250);labplayer[2].setText(Users[((Idnum%3)+1)%3]);labplayer[2].setLocation(130, 250);}if(command.equals("11")){this.AnMsg(s);this.loadImg();yes.setVisible(true);no.setVisible(true);}else if(command.equals("12")){last=st.nextToken();int next=Integer.parseInt(last)%3+1;dizhu=last;if(last.equals(Id)){this.AnMsg(s);this.loadImg();yes.setVisible(true);no.setVisible(true);jta.append("您,"+Users[Integer.parseInt(Id)-1]+"是地主\n");jta.append("地主:"+Users[Integer.parseInt(Id)-1]+"正在出牌\n");this.addtime(540, 430);ischupai=true;PlayCard1.clear();PlayCard2.clear();current1.setText("地主");current.setText("当前牌数为"+LeftCard.size());}else if(next==Integer.parseInt(Id)){jta.append(last+"是地主\n");left1.setText("地主");left.setText("当前牌数为"+20);this.addtime(200, 200);。
java挖金块游戏课程设计一、课程目标知识目标:1. 让学生掌握Java基础语法,包括变量声明、数据类型、运算符和流程控制语句;2. 让学生了解面向对象编程的基本概念,如类、对象、方法和继承;3. 帮助学生理解数组的使用,包括一维数组和二维数组;4. 引导学生掌握Java图形用户界面编程,如Swing组件的使用。
技能目标:1. 培养学生运用Java语言编写简单游戏的能力;2. 培养学生运用面向对象编程思想进行问题分析、设计和实现的能力;3. 提高学生团队协作和沟通能力,能在项目开发中分工合作,共同完成任务;4. 培养学生独立调试和解决问题的能力。
情感态度价值观目标:1. 激发学生对编程的兴趣,培养其主动学习和探究的精神;2. 培养学生面对困难和挑战时保持积极的态度,勇于尝试和克服;3. 培养学生具备良好的团队协作精神,尊重他人意见,共同完成任务;4. 引导学生关注社会热点问题,将所学知识应用于实际生活,提高社会责任感。
本课程针对高年级学生,结合Java挖金块游戏项目,注重理论与实践相结合,旨在提高学生的编程能力和综合素质。
课程要求学生在掌握基本知识的基础上,充分发挥自身潜能,通过团队协作完成具有一定难度的游戏项目。
通过本课程的学习,使学生能够将所学知识应用于实际编程实践,为未来进一步学习和职业发展打下坚实基础。
二、教学内容1. Java基础语法:变量声明、数据类型、运算符、流程控制语句(包括条件语句和循环语句);2. 面向对象编程:类与对象、构造方法、封装、继承和多态;3. 数组:一维数组、二维数组、数组操作方法;4. Java图形用户界面编程:Swing组件、事件处理、布局管理器;5. 游戏设计:游戏框架搭建、角色控制、碰撞检测、分数统计;6. 项目实践:分组进行挖金块游戏项目开发,涵盖需求分析、设计、编码、测试等环节。
教学内容与课本关联性如下:1. Java基础语法:对应教材第1-3章;2. 面向对象编程:对应教材第4-6章;3. 数组:对应教材第7章;4. Java图形用户界面编程:对应教材第8章;5. 游戏设计:结合教材实例,进行拓展教学;6. 项目实践:结合教材内容和实际案例,进行综合应用。
很简单的小游戏import javax.swing.JOptionPane;public class GameWithNumbers_GroupProject{public static void main(String[] args){//Create buttons for you to choose the game.Object[] options ={ "Game fight", "Find mere", "Guess numbers","Quit" };int button = JOptionPane.showOptionDialog(null, "Which action you want to do next?", "Combat Control Panel",JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);if (button == JOptionPane.YES_OPTION){{Object[] options1 ={ "Attack", "Heal", "Quit" };int myap = 0 ;int enap = 0 ;int myhp = 500;int enemyhp = 500;JOptionPane.showMessageDialog(null, "This is a Fighting Game \nYou and your enemy both have 500 blood \nYou can choose attack your enemy or heal yourself next");while (myhp > 0 && enemyhp > 0){int myattack = (int)(Math.random()*100);int enemyattack = (int)(Math.random()*100);int myheal = (int)(Math.random()*50);int enemyheal = (int)(Math.random()*50);int i = JOptionPane.showOptionDialog(null, "Which action you want to do next?", "Combat Control Panel",JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options1, options[0]);if (i == JOptionPane.YES_OPTION){if (myap != 100){enemyhp-=myattack;enap += 25;if(enemyhp <= 0){JOptionPane.showMessageDialog(null,"You have attacked your enemy this turn \nYour HP: " + myhp + ", \nYour enemy's HP:" + "0" + " \nGet into your enemy's turn?");break;}else{JOptionPane.showMessageDialog(null,"You have attacked your enemy this turn \nYour HP: " + myhp + ", \nYour enemy's HP:" + enemyhp + " \nGet into your enemy's turn?");}}else{enemyhp-=myattack*2;enap += 25;myap = 0 ;if(enemyhp <= 0){JOptionPane.showMessageDialog(null,"You have attacked your enemy"+ " critically this turn \nYour HP: " + myhp + ", \nYour enemy's HP:" + "0" +" \nGet into your enemy's turn?");break;}else{JOptionPane.showMessageDialog(null,"You have attacked your enemy critially this "+ "turn \nYour HP: " + myhp + ", \nYour enemy's HP:" + enemyhp +" \nGet into your enemy's turn?");}}if (i == JOptionPane.NO_OPTION){myhp+=myheal;if (myhp >= 1000){myhp = 1000;}}JOptionPane.showMessageDialog(null,"You have healed yourself this turn \nYour HP: " + myhp + ", \nYour enemy's HP:" + enemyhp + " \nGet into your enemy's turn?");}if (i == JOptionPane.CANCEL_OPTION){break;}int enemyif = (int)(Math.random()*2);if (enemyif == 0){if(enap !=100){myhp-=enemyattack;myap+=25;很简单的小游戏if(myhp>=0){JOptionPane.showMessageDialog(null,"Your enemy has attacked you this turn \nYour HP: " + myhp + ", \nYour enemy's HP: " + enemyhp + " \nDo you want to get into your turn?");}else{JOptionPane.showMessageDialog(null,"Your enemy has attacked you this turn \nYour HP: " + "0" + ", \nYour enemy's HP: " + enemyhp + " \nDo you want to get into your turn?"); break;}}else{myhp-=enemyattack*2;myap+=25;enap = 0;if(myhp>=0){JOptionPane.showMessageDialog(null,"Your enemy has attacked you "+ "critically this turn \nYour HP: " + myhp +", \nYour enemy's HP: " + enemyhp + " \nDo you want to get "+ "into your turn?");}else{JOptionPane.showMessageDialog(null,"Your enemy has attacked you "+ "critically this turn \nYour HP: " + "0" +", \nYour enemy's HP: " + enemyhp + " \nDo you want to get "+ "into your turn?");break;}}}if (enemyif == 1){enemyhp+=enemyheal;if(enemyhp >= 1000){enemyhp = 1000;}JOptionPane.showMessageDialog(null,"Your enemy has healed himself this turn \nyour HP: " + myhp + ", \nYour enemy's HP:" + enemyhp + " \nDo you want to get into your turn?");}}if (myhp <= 0){JOptionPane.showMessageDialog(null,"You die, Game Over");}if (enemyhp <= 0){JOptionPane.showMessageDialog(null,"Your enemy die, You are the winner!");}else{JOptionPane.showMessageDialog(null,"The Player Quit The Game");}}}if (button == JOptionPane.NO_OPTION){//Prompt user enter his or her birthday.int birthmonth=Integer.parseInt(JOptionPane.showInputDialog(null,"Enter the month "+ "you were born in(1 to 12):"));int birthdate=Integer.parseInt(JOptionPane.showInputDialog(null,"Enter the day "+ "you were born in:"));Constellation1(birthmonth,birthdate);}if (button == JOptionPane.CANCEL_OPTION){//Create the number and tell reader whether it is prime number:int guess=(int)(Math.random()*99+2);int guess1=(int)(Math.pow(guess,0.5));String judge="";for (int check=2; check<=guess1;check++){if(guess % check == 0)judge="The number you will guess is not a prime number";elsejudge="The number you will guess is a prime number";}JOptionPane.showMessageDialog(null,judge);//Prompt user to input the numberint user=Integer.parseInt(JOptionPane.showInputDialog(null,"Guess the number(2 to 100): "));do{if(user<guess)JOptionPane.showMessageDialog(null,"The number you guessed is too low, please try again!");if(user>guess)JOptionPane.showMessageDialog(null,"The number you guessed is too large, please try again!");u很简单的小游戏if(myhp>=0){JOptionPane.showMessageDialog(null,"Your enemy has attacked you this turn \nYour HP: " + myhp + ", \nYour enemy's HP: " + enemyhp + " \nDo you want to get into your turn?");}else{JOptionPane.showMessageDialog(null,"Your enemy has attacked you this turn \nYourHP: " + "0" + ", \nYour enemy's HP: " + enemyhp + " \nDo you want to get into your turn?"); break;}}else{myhp-=enemyattack*2;myap+=25;enap = 0;if(myhp>=0){JOptionPane.showMessageDialog(null,"Your enemy has attacked you "+ "critically this turn \nYour HP: " + myhp +", \nYour enemy's HP: " + enemyhp + " \nDo you want to get "+ "into your turn?");}else{JOptionPane.showMessageDialog(null,"Your enemy has attacked you "+ "critically this turn \nYour HP: " + "0" +", \nYour enemy's HP: " + enemyhp + " \nDo you want to get "+ "into your turn?");break;}}}if (enemyif == 1){enemyhp+=enemyheal;if(enemyhp >= 1000){enemyhp = 1000;}JOptionPane.showMessageDialog(null,"Your enemy has healed himself this turn \nyour HP: " + myhp + ", \nYour enemy's HP:" + enemyhp + " \nDo you want to get into your turn?");}}if (myhp <= 0){JOptionPane.showMessageDialog(null,"You die, Game Over");}if (enemyhp <= 0){JOptionPane.showMessageDialog(null,"Your enemy die, You are the winner!");}else{JOptionPane.showMessageDialog(null,"The Player Quit The Game");}}}if (button == JOptionPane.NO_OPTION){//Prompt user enter his or her birthday.int birthmonth=Integer.parseInt(JOptionPane.showInputDialog(null,"Enter the month "+ "you were born in(1 to 12):"));int birthdate=Integer.parseInt(JOptionPane.showInputDialog(null,"Enter the day "+ "you were born in:"));Constellation1(birthmonth,birthdate);}if (button == JOptionPane.CANCEL_OPTION){//Create the number and tell reader whether it is prime number:int guess=(int)(Math.random()*99+2);int guess1=(int)(Math.pow(guess,0.5));String judge="";for (int check=2; check<=guess1;check++){if(guess % check == 0)judge="The number you will guess is not a prime number";elsejudge="The number you will guess is a prime number";}JOptionPane.showMessageDialog(null,judge);//Prompt user to input the numberint user=Integer.parseInt(JOptionPane.showInputDialog(null,"Guess the number(2 to 100): "));do{if(user<guess)JOptionPane.showMessageDialog(null,"The number you guessed is too low, please try again!");if(user>guess)JOptionPane.showMessageDialog(null,"The number you guessed is too large, please try again!");U很简单的小游戏ser=Integer.parseInt(JOptionPane.showInputDialog(null,"Guess the number(2 to 100): "));}while(user != guess);JOptionPane.showMessageDialog(null,"You got the right answer!","Congratulations!",2);}}public static int Constellation1(int month, int date){if((month==3 && date>=21 && date<=31)||(month==4 && date>=1 && date<=19)) {JOptionPane.showMessageDialog(null,"You are Aries!");}else if((month==4 && date>=20 && date<=31)||(month==5 && date>=1 && date<=20)) {JOptionPane.showMessageDialog(null,"You are Taurus!");}else if((month==5 && date>=21 && date<=31)||(month==6 && date>=1 && date<=21)) {JOptionPane.showMessageDialog(null,"You are Gemini!");}else if((month==6 && date>=22 && date<=30)||(month==7 && date>=1 && date<=22)) {JOptionPane.showMessageDialog(null,"You are Cancer!");}else if((month==7 && date>=23 && date<=31)||(month==8 && date>=1 && date<=22)) {JOptionPane.showMessageDialog(null,"You are Leo!");}else if((month==9 && date>=1 && date<=22)||(month==8 && date>=23 && date<=31)) {JOptionPane.showMessageDialog(null,"You are Virgo!");}else if((month==9 && date>=23 && date<=30)||(month==10 && date>=1 && date<=22)) {JOptionPane.showMessageDialog(null,"You are Libra!");}else if((month==11 && date>=1 && date<=21)||(month==10 && date>=23 && date<=31)) {JOptionPane.showMessageDialog(null,"You are Scorpio!");}else if((month==11 && date>=22 && date<=30)||(month==12 && date>=1 && date<=21)) {JOptionPane.showMessageDialog(null,"You are Sagittarius!");}else if((month==1 && date>=1 && date<=19)||(month==12 && date>=22 && date<=31)) {JOptionPane.showMessageDialog(null,"You are Capricorn!");}else if((month==1 && date>=20 && date<=31)||(month==2 && date>=1 && date<=18)) {JOptionPane.showMessageDialog(null,"You are Aquarius!");}else{JOptionPane.showMessageDialog(null,"You are Pisces!");}return Constellation2(month,date);}public static int Constellation2(int month, int date){month=(int)(Math.random()*12+1);if(month==4 || month==6 || month==9 || month==11)date=(int)(Math.random()*31+1);else if(month==2)date=(int)(Math.random()*29+1);elsedate=(int)(Math.random()*30+1);String monthname="";switch(month){case 1:monthname="January";break;case 2:monthname="Feburary";break;case 3:monthname="March";break;case 4:monthname="April";break;case 5:monthname="May";break;case 6:monthname="June";break;case 7:monthname="July";break;case 8:monthname="August";break;case 9:monthname="September";break;case 10:monthname="October";break;case 11:monthname="November";break;default:monthname="December";break;}JOptionP很简单的小游戏ser=Integer.parseInt(JOptionPane.showInputDialog(null,"Guess the number(2 to 100): ")); }while(user != guess);JOptionPane.showMessageDialog(null,"You got the right answer!","Congratulations!",2);}}public static int Constellation1(int month, int date){if((month==3 && date>=21 && date<=31)||(month==4 && date>=1 && date<=19)) {JOptionPane.showMessageDialog(null,"You are Aries!");}else if((month==4 && date>=20 && date<=31)||(month==5 && date>=1 && date<=20)) {JOptionPane.showMessageDialog(null,"You are Taurus!");}else if((month==5 && date>=21 && date<=31)||(month==6 && date>=1 && date<=21)) {JOptionPane.showMessageDialog(null,"You are Gemini!");}else if((month==6 && date>=22 && date<=30)||(month==7 && date>=1 && date<=22)) {JOptionPane.showMessageDialog(null,"You are Cancer!");}else if((month==7 && date>=23 && date<=31)||(month==8 && date>=1 && date<=22)) {JOptionPane.showMessageDialog(null,"You are Leo!");}else if((month==9 && date>=1 && date<=22)||(month==8 && date>=23 && date<=31)) {JOptionPane.showMessageDialog(null,"You are Virgo!");}else if((month==9 && date>=23 && date<=30)||(month==10 && date>=1 && date<=22)) {JOptionPane.showMessageDialog(null,"You are Libra!");}else if((month==11 && date>=1 && date<=21)||(month==10 && date>=23 && date<=31)) {JOptionPane.showMessageDialog(null,"You are Scorpio!");}else if((month==11 && date>=22 && date<=30)||(month==12 && date>=1 && date<=21)) {JOptionPane.showMessageDialog(null,"You are Sagittarius!");}else if((month==1 && date>=1 && date<=19)||(month==12 && date>=22 && date<=31)) {JOptionPane.showMessageDialog(null,"You are Capricorn!");}else if((month==1 && date>=20 && date<=31)||(month==2 && date>=1 && date<=18)) {JOptionPane.showMessageDialog(null,"You are Aquarius!");}else{JOptionPane.showMessageDialog(null,"You are Pisces!");}return Constellation2(month,date);}public static int Constellation2(int month, int date){month=(int)(Math.random()*12+1);if(month==4 || month==6 || month==9 || month==11)date=(int)(Math.random()*31+1);else if(month==2)date=(int)(Math.random()*29+1);elsedate=(int)(Math.random()*30+1);String monthname="";switch(month){case 1:monthname="January"; break;case 2:monthname="Feburary"; break;case 3:monthname="March"; break;case 4:monthname="April"; break;case 5:monthname="May"; break;case 6:monthname="June"; break;case 7:monthname="July"; break;case 8:monthname="August"; break;case 9:monthname="September"; break;case 10:monthname="October";break;case 11:monthname="November"; break;default:monthname="December"; break;}JOptionPane.showMessageDialog(null, "You should find a fere whose birthday is "+date+ "th of "+monthname);System.exit(0);return Constellation1(month,date);}}。
j a v a小游戏源代码 Document number:NOCG-YUNOO-BUYTT-UU986-1986UTJava小游戏第一个Java文件:import class GameA_B {public static void main(String[] args) {Scanner reader=new Scanner;int area;"Game Start…………Please enter the area:(1-9)" +'\n'+"1,2,3 means easy"+'\n'+"4,5,6 means middle"+'\n'+"7,8,9 means hard"+'\n'+"Please choose:");area=();switch((area-1)/3){case 0:"You choose easy! ");break;case 1:"You choose middle! ");break;case 2:"You choose hard! ");break;}"Good Luck!");GameProcess game1=new GameProcess(area);();}}第二个Java文件:import class GameProcess {int area,i,arrcount,right,midright,t;int base[]=new int[arrcount],userNum[]=newint[area],sysNum[]=new int[area];Random random=new Random();Scanner reader=new Scanner;GameProcess(int a){area=a;arrcount=10;right=0;midright=0;t=0;base=new int[arrcount];userNum=new int[area];sysNum=new int[area];for(int i=0;i<arrcount;i++){base[i]=i;// }}void process(){rand();while(right!=area){scanf();compare();print();check();}}void rand(){for(i=0;i<area;i++){t=(arrcount);//sysNum[i]=base[t];delarr(t);}}void delarr(int t){for(int j=t;j<arrcount-1;j++)base[j]=base[j+1];arrcount--;}void scanf(){"The system number has created!"+"\n"+"Please enter "+area+" Numbers");for(int i=0;i<area;i++){userNum[i]=();}}void check(){if(right==area)"You win…………!");}boolean check(int i){return true;}void compare(){int i=0,j=0;right=midright=0;for(i=0;i<area;i++){for(j=0;j<area;j++){if(userNum[i]==sysNum[j]){if(i==j)right++;elsemidright++;}}}}void print(){" A "+right+" B "+midright);}}。
Java实现多人在线游戏开发案例Java是一种广泛使用的编程语言,具有高效、可靠和安全等特点。
它在游戏开发领域也有广泛应用,能够实现多人在线游戏的开发。
本文将以一个多人在线游戏开发案例为例,介绍如何利用Java实现该项目。
一、项目概述本项目旨在实现一个基于Java的多人在线游戏。
游戏采用客户端-服务器模式,玩家通过客户端与服务器进行通信,实现多个玩家间的即时互动。
服务器负责处理游戏逻辑和数据交互,客户端负责展示游戏画面和玩家操作。
二、技术选型1. 客户端开发技术在客户端开发中,我们选择使用JavaFX进行界面开发,它是Java平台的图形用户界面工具包。
JavaFX提供了丰富的UI组件和动画效果,适用于游戏开发。
2. 服务器开发技术在服务器端开发中,我们选择使用Java Socket和多线程技术。
Java Socket用于实现网络通信,多线程用于处理多个客户端的请求,并保证游戏的并发性。
三、项目结构1. 客户端结构客户端主要包括以下几个模块:- 用户界面模块:负责游戏画面的展示和用户操作的响应。
- 网络通信模块:负责与服务器进行通信,接收和发送游戏数据。
- 游戏逻辑模块:负责处理游戏的逻辑,如碰撞检测、玩家操作等。
- 辅助模块:负责提供一些辅助功能,如音效、动画等。
2. 服务器结构服务器主要包括以下几个模块:- 网络通信模块:负责接受和处理客户端的连接请求,并进行数据的传输。
- 游戏逻辑模块:负责处理游戏的逻辑,如碰撞检测、计分等。
- 数据库模块:负责存储游戏数据,如用户信息、排行榜等。
四、开发步骤1. 客户端开发步骤(略)2. 服务器开发步骤(略)五、实现效果通过以上的开发步骤,我们成功实现了一个基于Java的多人在线游戏。
玩家可以通过客户端与服务器进行连接,实现多人实时互动的游戏体验。
在游戏中,玩家可以进行各种操作,与其他玩家进行竞技、合作等。
六、总结通过本案例的实现,我们掌握了利用Java实现多人在线游戏的方法。
java实现2048⼩游戏(含注释)本⽂实例为⼤家分享了java实现2048⼩游戏的具体代码,供⼤家参考,具体内容如下实现⽂件APP.javaimport javax.swing.*;public class APP {public static void main(String[] args) {new MyFrame();}}类⽂件import javax.swing.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.util.Random;//定义⾃⼰的类(主类)去继承JFrame类并实现KeyListener接⼝和ActionListener接⼝public class MyFrame extends JFrame implements KeyListener, ActionListener {//⽤于存放游戏各位置上的数据int[][] data = new int[4][4];//⽤于判断是否失败int loseFlag = 1;//⽤于累计分数int score = 0;//⽤于切换主题String theme = "A";//设置三个菜单项⽬JMenuItem item1 = new JMenuItem("经典");JMenuItem item2 = new JMenuItem("霓虹");JMenuItem item3 = new JMenuItem("糖果");//核⼼⽅法public MyFrame(){//初始化窗⼝initFrame();//初始化菜单initMenu();//初始化数据initData();//绘制界⾯paintView();//为窗体提供键盘监听,该类本⾝就是实现对象this.addKeyListener(this);//设置窗体可见setVisible(true);}//窗体初始化public void initFrame(){//设置尺⼨setSize(514,538);//设置居中setLocationRelativeTo(null);//设置总在最上⾯setAlwaysOnTop(true);setLayout(null);}//初始化菜单public void initMenu() {//菜单栏⽬JMenuBar menuBar = new JMenuBar();JMenu menu1 = new JMenu("换肤");JMenu menu2 = new JMenu("关于我们");//添加上menuBarmenuBar.add(menu1);menuBar.add(menu2);//添加上menumenu1.add(item1);menu1.add(item2);menu1.add(item3);//注册监听item1.addActionListener(this);item2.addActionListener(this);item3.addActionListener(this);//添加进窗体super.setJMenuBar(menuBar);}//初始化数据,在随机位置⽣成两个2public void initData(){generatorNum();generatorNum();}//重新绘制界⾯的⽅法public void paintView(){//调⽤⽗类中的⽅法清空界⾯getContentPane().removeAll();//判断是否失败if(loseFlag==2){//绘制失败界⾯JLabel loseLable = new JLabel(new ImageIcon("D:\\Download\\BaiDu\\image\\"+theme+"-lose.png"));//设置位置和⾼宽loseLable.setBounds(90,100,334,228);//将该元素添加到窗体中getContentPane().add(loseLable);}//根据现有数据绘制界⾯for(int i=0;i<4;i++) {//根据位置循环绘制for (int j = 0; j < 4; j++) {JLabel image = new JLabel(new ImageIcon("D:\\Download\\BaiDu\\image\\"+theme+"-"+data[i][j]+".png"));//提前计算好位置image.setBounds(50 + 100 * j, 50+100*i, 100, 100);//将该元素添加进窗体getContentPane().add(image);}}//绘制背景图⽚JLabel background = new JLabel(new ImageIcon("D:\\Download\\BaiDu\\image\\"+theme+"-Background.jpg")); //设置位置和⾼宽background.setBounds(40,40,420,420);//将该元素添加进窗体getContentPane().add(background);//得分模板设置JLabel scoreLable = new JLabel("得分:"+score);//设置位置和⾼宽scoreLable.setBounds(50,20,100,20);getContentPane().repaint();}//⽤不到的但是必须重写的⽅法,⽆需关注@Overridepublic void keyTyped(KeyEvent e) {}//键盘被按下所触发的⽅法,在此⽅法中加⼊区分上下左右的按键@Overridepublic void keyPressed(KeyEvent e) {//keyCode接收按键信息int keyCode = e.getKeyCode();//左移动if(keyCode == 37){moveToLeft(1);generatorNum();}//上移动else if(keyCode==38){moveToTop(1);generatorNum();}//右移动else if(keyCode==39){moveToRight(1);generatorNum();}//下移动else if(keyCode==40){moveToBottom(1);generatorNum();}//忽视其他按键else {return;}//检查是否能够继续移动check();//重新根据数据绘制界⾯paintView();}//左移动的⽅法,通过flag判断,传⼊1是正常移动,传⼊2是测试移动 public void moveToLeft(int flag) {for(int i=0;i<data.length;i++){//定义⼀维数组接收⼀⾏的数据int[] newArr = new int[4];//定义下标⽅便操作int index=0;for(int x=0;x<data[i].length;x++){//将有数据的位置前移if(data[i][x]!=0){newArr[index]=data[i][x];index++;}}//赋值到原数组data[i]=newArr;//判断相邻数据是否相邻,相同则相加,不相同则略过for(int x=0;x<3;x++){if(data[i][x]==data[i][x+1]){data[i][x]*=2;//如果是正常移动则加分if(flag==1){score+=data[i][x];}//将合并后的数据都前移,实现数据覆盖for(int j=x+1;j<3;j++){data[i][j]=data[i][j+1];}//末尾补0data[i][3]=0;}//右移动的⽅法,通过flag判断,传⼊1是正常移动,传⼊2是测试移动 public void moveToRight(int flag) {//翻转⼆维数组reverse2Array();//对旋转后的数据左移动moveToLeft(flag);//再次翻转reverse2Array();}//上移动的⽅法,通过flag判断,传⼊1是正常移动,传⼊2是测试移动 public void moveToTop(int flag) {//逆时针旋转数据anticlockwise();//对旋转后的数据左移动moveToLeft(flag);//顺时针还原数据clockwise();}//下移动的⽅法,通过flag判断,传⼊1是正常移动,传⼊2是测试移动 public void moveToBottom(int flag) {//顺时针旋转数据clockwise();//对旋转后的数据左移动moveToLeft(flag);//逆时针旋转还原数据anticlockwise();}//检查能否左移动public boolean checkLeft(){//开辟新⼆维数组⽤于暂存数据和⽐较数据int[][] newArr = new int[4][4];//复制数组copyArr(data,newArr);//测试移动moveToLeft(2);boolean flag = false;//设置break跳出的for循环标记lo:for (int i = 0; i < data.length; i++) {for (int j = 0; j < data[i].length; j++) {//如果有数据不相同,则证明能够左移动,则返回trueif(data[i][j]!=newArr[i][j]){flag=true;break lo;}}}//将原本的数据还原copyArr(newArr,data);return flag;}//检查能否右移动,与checkLeft()⽅法原理相似public boolean checkRight(){int[][] newArr = new int[4][4];copyArr(data,newArr);moveToRight(2);boolean flag = false;lo:for (int i = 0; i < data.length; i++) {for (int j = 0; j < data[i].length; j++) {if(data[i][j]!=newArr[i][j]){flag=true;break lo;}}}copyArr(newArr,data);//检查能否上移动,与checkLeft()⽅法原理相似public boolean checkTop(){int[][] newArr = new int[4][4];copyArr(data,newArr);moveToTop(2);boolean flag = false;lo:for (int i = 0; i < data.length; i++) {for (int j = 0; j < data[i].length; j++) {if(data[i][j]!=newArr[i][j]){flag=true;break lo;}}}copyArr(newArr,data);return flag;}//检查能否下移动,与checkLeft()⽅法原理相似public boolean checkBottom(){int[][] newArr = new int[4][4];copyArr(data,newArr);moveToBottom(2);boolean flag = false;lo:for (int i = 0; i < data.length; i++) {for (int j = 0; j < data[i].length; j++) {if(data[i][j]!=newArr[i][j]){flag=true;break lo;}}}copyArr(newArr,data);return flag;}//检查是否失败public void check(){//上下左右均不能移动,则游戏失败if(checkLeft()==false&&checkRight()==false&&checkTop()==false&&checkBottom()==false){ loseFlag = 2;}}//复制⼆维数组的⽅法,传⼊原数组和新数组public void copyArr(int[][] src,int[][] dest){for (int i = 0; i < src.length; i++) {for (int j = 0; j < src[i].length; j++) {//遍历复制dest[i][j]=src[i][j];}}}//键盘被松开@Overridepublic void keyReleased(KeyEvent e) {}//翻转⼀维数组public void reverseArray(int[] arr){for(int start=0,end=arr.length-1;start<end;start++,end--){int temp = arr[start];arr[start] = arr[end];arr[end] = temp;}}//翻转⼆维数组public void reverse2Array(){for (int i = 0; i < data.length; i++) {reverseArray(data[i]);//顺时针旋转public void clockwise(){int[][] newArr = new int[4][4];for(int i=0;i<4;i++){for(int j=0;j<4;j++){//找规律啦~newArr[j][3-i] = data[i][j];}}data = newArr;}//逆时针旋转public void anticlockwise(){int[][] newArr = new int[4][4];for(int i=0;i<4;i++){for(int j=0;j<4;j++){//规律newArr[3-j][i] = data[i][j];}}data = newArr;}//空位置随机⽣成2public void generatorNum(){int[] arrarI = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}; int[] arrarJ = {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}; int w=0;for (int i = 0; i < data.length; i++) {for (int j = 0; j < data[i].length; j++) {if(data[i][j]==0){//找到并存放空位置arrarI[w]=i;arrarJ[w]=j;w++;}}}if(w!=0){//随机数找到随机位置Random r= new Random();int index = r.nextInt(w);int x = arrarI[index];int y = arrarJ[index];//空位置随机⽣成2data[x][y]=2;}}//换肤操作@Overridepublic void actionPerformed(ActionEvent e) {//接收动作监听,if(e.getSource()==item1){theme = "A";}else if(e.getSource()==item2){theme = "B";}else if(e.getSource()==item3){theme = "C";}//换肤后重新绘制paintView();}}//测试失败效果的数据/*int[][] data = {{2,4,8,4},{16,32,64,8},{128,2,256,2},{512,8,1024,2048}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
近年来,Java作为一种新的编程语言,以其简单性、可移植性和平台无关性等优点,得到了广泛地应用,特别是Java与万维网的完美结合,使其成为网络编程和嵌入式编程领域的首选编程语言。
Eclipse是一个开放源代码的、基于Java的可扩展开发平台,同时它也是是著名的跨平台的自由集成开发环境,它以其友好的开发界面、强大的组件支持等优点,得到广大程序员的接受和认可。
贪吃蛇是人们手机中是一个很常见的一个经典小游戏,人们对它并不陌生,在紧张的现实生活中给人们带来了不少的乐趣,编写这个贪吃蛇小游戏能让人们在业余时间里适当的放松,保持好的心态。
在这个程序中我采用了Java中的图形用户界面技术,同时引入了线程来编写。
本次设计主要是对我之前所学Java知识的一个巩固,不仅提高了我综合运用以前所学知识的能力,同时也锻炼了我的实际动手能力。
整个游戏代码简单易懂,用户在娱乐的同时也可以简单的看一下代码,有助于初涉Java者语言水平的提高。
贪吃蛇的核心算法是如何实现移动和吃掉食物,在当前运动方向上头指针所指的位置之前添加一个节点,然后删除尾节点,最后把链表中的所有节点依次画出来,这样就可以达到移动的效果。
对是否吃到食物,需要对蛇和食物进行碰撞检测,检测未碰撞在一起则只需要执行移动操作,碰撞在一起时表示吃到食物,则只需把食物入队即可,即在蛇的节点链表上再添加一个节点,从而达到身体增长的效果。
本次设计的重点之处在于编程思想的形成,设计图像界面,产生随机食物及其位置。
难点在于程序编写中,整个程序框架的架构。
这就要求我们不仅要对这个游戏的玩法特别熟悉,而且还要熟练掌握Java 语言。
实现贪吃蛇的四个类模块,分别为游戏界面、蛇、食物和方向。
其具体设计如下:1产生游戏界面Yard.java包括界面的位置、大小的设定,绘制游戏界面,启动键盘监听器。
1)在launch()中添加代码:this.setBounds(200,200,COLS*BLOCK_SIZE,ROWS*BLOCK _SIZE);设定界面的位置、大小。
翻金花的规矩
翻金花的规矩包括以下步骤:
1. 洗牌:将一副牌(除去大小王)均匀洗好,放在桌面中央。
2. 发牌:由庄家开始发牌,每次发一张,按逆时针方向依次发牌,每人各得三张。
3. 下注:在发牌过程中,玩家可以决定是否下注(也就是是否愿意和其他玩家一起竞争)。
下注的金额会影响最终的赢家分配。
4. 比较牌面:在所有玩家都下注后,各人亮出自己的三张牌,比较牌面大小。
5. 结算:根据牌面大小,决定谁是赢家,并根据各人下注的金额进行赢家分配。
在翻金花中,牌面大小由牌面数字决定,花色大小依次为黑桃、红桃、梅花、方块。
其中,豹子是指三张牌中有两张是同样的数字,如3个6;顺子是指三张牌数字连续,如345;同花是指三张牌花色相同,如三张红桃7;葫芦是指三张牌中有两张是同样的数字且另一张是不同的数字,如3个8和一张A;同花顺是指三张牌花色相同且数字连续,如红桃345。
在翻金花中,玩家可以根据自己的牌面大小来决定是否下注和下注的金额。
如果牌面大,可以赢得更多的筹码;如果牌面小,则可能输掉筹码。
玩家需要根据自己的牌面和对手的牌面来决定下注的策略。
翻金花是一种考验玩家判断力和策略的游戏,需要玩家熟悉游戏规则和掌握一定的技巧才能成为赢家。
java实现⽃地主游戏感想:第⼀次写博客,感觉编辑器挺复杂厉害的,感觉⾃⼰的内容挺简单的。
有什么问题请多多指教!思路:1、创建⼀个扑克牌的实体类Poker,设置了四个参数:花⾊、数字、牌值(判断⼤⼩)、是否地主牌,实现getset⽅法和构造⽅法;2、创建⼀个玩家的实体类Player,设置了四个参数:初始牌集合,排序后牌集合,牌值集合,是否地主,实现getset⽅法和构造⽅法;3、洗牌:循环嵌套花⾊数组跟数字数组⽣成52个Poker,⼿动加⼊⼤⼩王Poker,放进map(int,Poker)⾥⾯,利⽤Collections.shuffle随机排序map的key,再根据key⽣成排序后的Poker集合4、发牌:⽣成3个玩家对象,拿到洗牌后的集合,前51张牌为玩家牌,后3张为地主牌,在51张牌中随机⼀张为地主牌,遍历玩家牌分配个每⼀个Player,同时根据玩家牌的牌值⽣成集合grades存进Player对象中,将grades转为int数组并进⾏升序排序,根据grade取得新Poker集合分配给玩家。
Poker类:package pany;public class Poker {private String color;private String number;private int grade;boolean isLandowners;public boolean isLandowners() {return isLandowners;}public void setLandowners(boolean landowners) {isLandowners = landowners;}public int getGrade() {return grade;}public void setGrade(int grade) {this.grade = grade;}public String getColor() {return color;}public void setColor(String color) {this.color = color;}public String getNumber() {return number;}public void setNumber(String number) {this.number = number;}public Poker() {}public Poker(String color, String number ,int grade,boolean isLandowners) {this.color = color;this.number = number;this.grade=grade;this.isLandowners=isLandowners;}public String toString() {return this.getColor()+this.getNumber();}}Player类:package pany;import java.util.ArrayList;import java.util.LinkedList;public class Player {private ArrayList<Poker> pokers;private boolean isLandower;private ArrayList<Poker> newPokers;private LinkedList<Integer> grades;public LinkedList<Integer> getGrades() {return grades;}public void setGrades(LinkedList<Integer> grades) {this.grades = grades;}public ArrayList<Poker> getNewPokers() {return newPokers;}public void setNewPokers(ArrayList<Poker> newPokers) {this.newPokers = newPokers;}public boolean isLandower() {return isLandower;}public void setLandower(boolean landower) {isLandower = landower;}public Player() {}public ArrayList<Poker> getPokers() {return pokers;}public void setPokers(ArrayList<Poker> pokers) {this.pokers = pokers;}}洗牌:/*洗牌*/public static LinkedList<Poker> getPokerList() {LinkedList<Poker> pokers = new LinkedList<Poker>();LinkedList<Poker> newPokers = new LinkedList<Poker>();ArrayList<Integer> arrayList = new ArrayList<>();int[] arr;/*⽣成54张扑克牌(Poker对象)*//*⽤嵌套循环⽣成从⽅块3到⿊桃2的Poker对象,放进Poker的LinkedList保证顺序*/ String[] colors = {"♦", "♣", "♥", "♠"};String[] numbers = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"}; for (int i = 0; i < numbers.length; i++) {for (int j = 0; j < colors.length; j++) {Poker p = new Poker(colors[j], numbers[i], (4 * i) + j + 1, false);pokers.add(p);}}/*添加⼤⼩王*/pokers.add(new Poker("black", "☆", 53, false));pokers.add(new Poker("red", "☆", 54, false));/*将⽣成的54张扑克牌从1到54放进map*/for (int z = 1; z <= pokers.size(); z++) {map.put(z, pokers.get(z - 1));}/*遍历Map,将每个Poker对应的key放进 ArrayList<Integer> arrayList */Set<Map.Entry<Integer, Poker>> set = map.entrySet();Iterator it = set.iterator();while (it.hasNext()) {Map.Entry<Integer, Poker> e = (Map.Entry<Integer, Poker>) it.next();arrayList.add(e.getKey());}/*利⽤Collections.shuffle随机排序key*/Collections.shuffle(arrayList);/*将乱序后的key对于的Poker放进newPokers⾥⾯ */for (Integer i : arrayList) {newPokers.add(map.get(i));}return newPokers;}发牌:/*发牌*//*根据玩家⼈数⽣成Player,默认num=3*/private static void sentPoker(int num) {/*获取洗牌后的LinkedList,保证顺序*/LinkedList<Poker> Allpokers = getPokerList();ArrayList<Poker> pokers = new ArrayList<>();ArrayList<Poker> BottomPokers = new ArrayList<>();/*⽣成玩家对象*/for (int i = 0; i < num; i++) {Player p = new Player();players.add(p);}/*前50张牌为玩家牌,后三张为底牌*/for (int p = 0; p < Allpokers.size(); p++) {if (p <= 50) {pokers.add(Allpokers.get(p));} else {BottomPokers.add(Allpokers.get(p));}}/*玩家牌中随机⼀张为地主牌*/Random rand = new Random();int s = rand.nextInt(51);pokers.get(s).setLandowners(true);System.out.println("地主牌: " + pokers.get(s));/*根据num⽣成Player对象*/for (int j = 0; j < num; j++) {/*玩家的牌值集合*/LinkedList<Integer> grades = new LinkedList<>();/*玩家的⼿牌集合*/ArrayList<Poker> playerPokers = new ArrayList<Poker>();/*根据玩家个数分配玩家牌*/for (int z = j; z < pokers.size(); z = z + num) {playerPokers.add(pokers.get(z));grades.add(pokers.get(z).getGrade());players.get(j).setPokers(playerPokers);players.get(j).setGrades(grades);}/*根据玩家牌中的地主牌设置玩家是否地主*/for (Poker p : players.get(j).getPokers()) {if (p.isLandowners() == true) {players.get(j).setLandower(true);}}/*根据玩家的牌值集合⽣成数组*/Integer[] gs = new Integer[players.get(j).getGrades().size()];grades.toArray(gs);/*排序数组,由低到⾼*/Arrays.sort(gs);/*排序后的玩家牌*/ArrayList<Poker> newPokers = new ArrayList<>();for (int g = 0; g < gs.length; g++) {Poker p = map.get(gs[g]);newPokers.add(p);}players.get(j).setNewPokers(newPokers);System.out.println("玩家" + (j + 1) + ": " + players.get(j).getNewPokers() + " 是否地主:" + players.get(j).isLandower()); }System.out.print("底牌为: ");for (Poker p : BottomPokers) {System.out.print(p + " ");}}效果如下:以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
扫雷使用Java语言和JavaFX开发的小游戏扫雷游戏是一款经典的单人益智游戏,目标是在一个方块网格中,找出所有不含雷的方块,同时避开所有含雷的方块。
本文将介绍如何使用Java语言和JavaFX开发一个简单的扫雷游戏。
一、游戏设计和规则扫雷游戏的设计和规则非常简单。
一个方块网格被分成若干个小方块,有些方块上隐藏着雷,而其他方块上则显示着数字,数字表示该方块周围的雷数。
玩家可以点击方块来揭示它的内容,如果揭示到含雷的方块,则游戏结束;如果揭示到数字方块,则继续进行游戏;若揭示到不含雷的方块,则继续揭示周围的方块,直到揭示到含雷的方块或者揭示到边界为止。
游戏目标是揭示出所有不含雷的方块。
二、项目结构与主要类在Java语言和JavaFX开发扫雷游戏时,一个推荐的项目结构如下:1. Main类:游戏的入口类,负责启动游戏。
2. Game类:游戏的主要逻辑类,包含方块网格的生成、雷的布置以及游戏状态的管理。
3. Block类:方块类,包含方块的状态(是否揭示、是否含雷等)和周围雷数的计算方法。
4. UI类:游戏的用户界面类,负责显示方块网格和处理点击事件等。
三、使用JavaFX创建用户界面JavaFX是现代化的Java图形界面开发框架,提供了丰富的界面组件和动画效果。
在扫雷游戏中,可以使用JavaFX来实现方块的显示以及用户交互。
1. 创建方块网格:使用JavaFX的GridPane布局来创建方块网格。
可以根据游戏难度在GridPane中添加若干个方块组件,并设置它们的样式和事件处理器。
2. 显示方块内容:根据方块的状态,在界面上显示相应的图标或者文字。
可以使用JavaFX的Label组件来显示方块的内容,并根据不同的状态设置不同的样式。
3. 处理点击事件:为每个方块组件添加事件处理器,当用户点击方块时,根据方块的内容和状态来更新界面显示。
四、实现游戏逻辑在Game类中实现游戏的主要逻辑。
首先,根据游戏难度生成方块网格,并在其中随机布置一定数量的雷。
目录一、实现方案 (2)二、具体代码及程序框图分析 (3)三、参考资料 (13)一、实现方案本游戏采用Java语言编写,使用Eclipse编译器,jdk1.7.0_51编译环境。
游戏的UI主要运用Java图形界面编程(AWT),实现窗口化可视化的界面。
游戏的后台通过监听键盘方向键来移动数字方块,运用随机数的思想随机产生一个2或4的随机数,显示在随机方块中,运用二维数组存储、遍历查找等思想,在每次移动前循环查找二维数组相邻的移动方向的行或列可以合并与否,如果没有可以合并的数字方块同时又没有空余的空间产生新的数字则游戏宣告结束,同时,当检测到合并的结果中出现2048,也宣告游戏结束。
游戏设计了非常简单的交互逻辑,流程如下:为了增加游戏的用户体验,后期加入了操作音效(音效文件提取自百度移动应用商店——2048),在移动和合并方块时播放不同声音。
二、具体代码及程序框图分析整个游戏有三个类,分别为游戏的主类Game.class、事件处理类MyListener.class、声音处理类PlaySound.class,下面对Game.class和MyListener.class进行说明。
Game.class的简单程序框图如下:游戏的主类Game.class是窗体程序JFrame的扩展类,主要负责界面的搭建,完成界面绘图的工作。
该类作为主类,主方法public static void main(String[] args)中先新建一个该类的对象,接着调用用与创建界面控件的方法IntUI(),代码如下:public static void main(String[] args) {Game UI = new Game();UI.IntUI();}IntUI()方法用于JFrame控件及界面框架的搭建,代码解析如下:首先创建一个窗体,标题为“2048小游戏”,把坐标固定在屏幕的x=450,y=100的位置,把窗体大小设置为宽400像素高500像素,然后把JPlane的布局管理器设置为空,具体代码如下:this.setTitle("2048小游戏");this.setLocation(450,100);this.setSize(400, 500);this.setLayout(null);接下来分别是【新游戏】、【帮助】、和【退一步】的按钮,以【新游戏】按钮为例,创建一个新游戏的图片按钮,图片相对路径为res/start.png,为了达到更美观的显示效果,把聚焦,边线等特征设置为false,把相对窗体的坐标设置为(5, 10),大小设置为宽120像素高30像素,具体代码如下:ImageIcon imgicon = new ImageIcon("res/start.png");JButton bt = new JButton(imgicon);bt.setFocusable(false);bt.setBorderPainted(false);bt.setFocusPainted(false);bt.setContentAreaFilled(false);bt.setBounds(-15, 10, 120, 30);this.add(bt);而分数显示控件与按钮控件类似,不再赘述。
用Java编程语言编写石头剪刀布游戏示例文章标题:用Java编程语言编写石头剪刀布游戏示例介绍内容:石头剪刀布游戏是一种简单而受欢迎的游戏,编程语言可以帮助我们实现一个可以和计算机进行对战的石头剪刀布游戏程序。
本文将介绍如何使用Java编程语言编写一个简单而有趣的石头剪刀布游戏示例。
首先,我们需要创建一个Java类,作为我们的游戏程序的主类。
接下来,我们可以使用Java的输入输出和随机数生成的类来实现游戏的逻辑。
下面是一个示例代码,用于实现一个石头剪刀布游戏:```javaimport java.util.Scanner;import java.util.Random;public class RockPaperScissorsGame {public static void main(String[] args) {Scanner scanner = new Scanner(System.in);Random random = new Random();String[] gestures = {"石头", "剪刀", "布"};System.out.println("欢迎来到石头剪刀布游戏!");while (true) {System.out.print("请输入你的选择(石头、剪刀、布):");String playerGesture = scanner.nextLine();if (!isValidGesture(playerGesture)) {System.out.println("无效的手势,请重新输入。
");continue;}int computerChoice = random.nextInt(3);String computerGesture = gestures[computerChoice];System.out.println("你的选择:" + playerGesture);System.out.println("电脑的选择:" + computerGesture);String result = calculateResult(playerGesture, computerGesture);System.out.println(result);System.out.print("是否要继续游戏?(是/否):");String continueChoice = scanner.nextLine();if (continueChoice.equalsIgnoreCase("否")) {break;}}System.out.println("谢谢你玩石头剪刀布游戏!");}private static boolean isValidGesture(String gesture) {return gesture.equals("石头") || gesture.equals("剪刀") || gesture.equals("布");}private static String calculateResult(String playerGesture, String computerGesture) {if (playerGesture.equals(computerGesture)) {return "平局!";} else if ((playerGesture.equals("石头") && computerGesture.equals("剪刀")) ||(playerGesture.equals("剪刀") && computerGesture.equals("布")) ||(playerGesture.equals("布") && computerGesture.equals("石头"))) {return "你赢了!";} else {return "你输了!";}}}```在上述Java代码中,我们首先使用Scanner类来接收玩家输入,使用Random类来生成电脑的随机选择。
java实现24点游戏代码import java.util.Arrays;import java.util.Scanner;public class Test07 {public static void main(String[] args) {Scanner scn = new Scanner(System.in);int shu[] = new int[4];for (int i = 0; i < 4; i++) {shu[i] = scn.nextInt();}// int shu[] = { 5, 9, 9, 4 };char op[] = { '+', '-', '*', '/' };A : for (int i = 0; i < 4; i++) {for (int n1 = 0; n1 < op.length; n1++) {for (int j = 0; j < 4; j++) {for (int n2 = 0; n2 < op.length; n2++) {for (int k = 0; k < 4; k++) {for (int n3 = 0; n3 < op.length; n3++) {for (int m = 0; m < 4; m++) {// 选的这4个数不能重复if (isAllTheOrgiNum(shu[i], shu[j], shu[k], shu[m], shu)) {double temp = 0;switch (op[n1]) {case '+':temp = shu[i] + shu[j];break;case '-':temp = shu[i] - shu[j];break;case '*':temp = shu[i] * shu[j];break;case '/':temp = (double) shu[i] / shu[j];break;}switch (op[n2]) {case '+':temp = temp + shu[k];break;case '-':temp = temp - shu[k];break;case '*':temp = temp * shu[k];break;case '/':temp = (double) temp / shu[k];break;}switch (op[n3]) {case '+':temp = temp + shu[m];break;case '-':temp = temp - shu[m];break;case '*':temp = temp * shu[m];break;case '/':temp = (double) temp / shu[m];break;}if (temp == 24) {System.out.println("(" + "(" + shu[i] + " " + op[n1] + " " + shu[j] + ")" + " " + op[n2] + " " + shu[k] + ")" + " " + op[n3] + " " + shu[m]); break A;}}}}}}}}}}private static boolean isAllTheOrgiNum(int i, int j, int k, int l, int[] shu) {// TODO Auto-generated method stubint[] a = { i, j, k, l };Arrays.sort(a);Arrays.sort(shu);if(a[0]==shu[0] && a[1]==shu[1] &&a[2]==shu[2] && a[3]==shu[3]) {return true;}return false;}}。
//Java编程:五子棋游戏源代码import java.awt.*;import java.awt.event.*;import java.applet.*;import javax.swing.*;import java.io.PrintStream;import javax.swing.JComponent;import javax.swing.JPanel;/**main方法创建了ChessFrame类的一个实例对象(cf),*并启动屏幕显示显示该实例对象。
**/public class FiveChessAppletDemo {public static void main(String args[]){ChessFrame cf = new ChessFrame();cf.show();}}/**类ChessFrame主要功能是创建五子棋游戏主窗体和菜单**/class ChessFrame extends JFrame implements ActionListener { private String[] strsize={"20x15","30x20","40x30"};private String[] strmode={"人机对弈","人人对弈"};public static boolean iscomputer=true,checkcomputer=true; private int width,height;private ChessModel cm;private MainPanel mp;//构造五子棋游戏的主窗体public ChessFrame() {this.setTitle("五子棋游戏");cm=new ChessModel(1);mp=new MainPanel(cm);Container con=this.getContentPane();con.add(mp,"Center");this.setResizable(false);this.addWindowListener(new ChessWindowEvent());MapSize(20,15);JMenuBar mbar = new JMenuBar();this.setJMenuBar(mbar);JMenu gameMenu = new JMenu("游戏");mbar.add(makeMenu(gameMenu, new Object[] {"开局", "棋盘","模式", null, "退出"}, this));JMenu lookMenu =new JMenu("视图");mbar.add(makeMenu(lookMenu,new Object[] {"Metal","Motif","Windows"},this));JMenu helpMenu = new JMenu("帮助");mbar.add(makeMenu(helpMenu, new Object[] {"关于"}, this));}//构造五子棋游戏的主菜单public JMenu makeMenu(Object parent, Object items[], Object target){ JMenu m = null;if(parent instanceof JMenu)m = (JMenu)parent;else if(parent instanceof String)m = new JMenu((String)parent);elsereturn null;for(int i = 0; i < items.length; i++)if(items[i] == null)m.addSeparator();else if(items[i] == "棋盘"){JMenu jm = new JMenu("棋盘");ButtonGroup group=new ButtonGroup();JRadioButtonMenuItem rmenu;for (int j=0;j<strsize.length;j++){rmenu=makeRadioButtonMenuItem(strsize[j],target);if (j==0)rmenu.setSelected(true);jm.add(rmenu);group.add(rmenu);}m.add(jm);}else if(items[i] == "模式"){JMenu jm = new JMenu("模式");ButtonGroup group=new ButtonGroup();JRadioButtonMenuItem rmenu;for (int h=0;h<strmode.length;h++){rmenu=makeRadioButtonMenuItem(strmode[h],target);if(h==0)rmenu.setSelected(true);jm.add(rmenu);group.add(rmenu);}m.add(jm);}elsem.add(makeMenuItem(items[i], target));return m;}//构造五子棋游戏的菜单项public JMenuItem makeMenuItem(Object item, Object target){ JMenuItem r = null;if(item instanceof String)r = new JMenuItem((String)item);else if(item instanceof JMenuItem)r = (JMenuItem)item;elsereturn null;if(target instanceof ActionListener)r.addActionListener((ActionListener)target);return r;}//构造五子棋游戏的单选按钮式菜单项public JRadioButtonMenuItem makeRadioButtonMenuItem( Object item, Object target){JRadioButtonMenuItem r = null;if(item instanceof String)r = new JRadioButtonMenuItem((String)item);else if(item instanceof JRadioButtonMenuItem)r = (JRadioButtonMenuItem)item;elsereturn null;if(target instanceof ActionListener)r.addActionListener((ActionListener)target);return r;}public void MapSize(int w,int h){setSize(w * 20+50 , h * 20+100 );if(this.checkcomputer)this.iscomputer=true;elsethis.iscomputer=false;mp.setModel(cm);mp.repaint();}public boolean getiscomputer(){return this.iscomputer;}public void restart(){int modeChess = cm.getModeChess();if(modeChess <= 3 && modeChess >= 1){cm = new ChessModel(modeChess);MapSize(cm.getWidth(),cm.getHeight());}else{System.out.println("\u81EA\u5B9A\u4E49");}}public void actionPerformed(ActionEvent e){String arg=e.getActionCommand();try{if (arg.equals("Windows"))UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");else if(arg.equals("Motif"))UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");elseUIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel" ); SwingUtilities.updateComponentTreeUI(this);}catch(Exception ee){}if(arg.equals("20x15")){this.width=20;this.height=15;cm=new ChessModel(1);MapSize(this.width,this.height);SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("30x20")){this.width=30;this.height=20;cm=new ChessModel(2);MapSize(this.width,this.height);SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("40x30")){this.width=40;this.height=30;cm=new ChessModel(3);MapSize(this.width,this.height);SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("人机对弈")){this.checkcomputer=true;this.iscomputer=true;cm=new ChessModel(cm.getModeChess());MapSize(cm.getWidth(),cm.getHeight());SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("人人对弈")){this.checkcomputer=false;this.iscomputer=false;cm=new ChessModel(cm.getModeChess());MapSize(cm.getWidth(),cm.getHeight());SwingUtilities.updateComponentTreeUI(this);}if(arg.equals("开局")){restart();}if(arg.equals("关于"))JOptionPane.showMessageDialog(this, "五子棋游戏测试版本", "关于", 0);if(arg.equals("退出"))System.exit(0);}}/**类ChessModel实现了整个五子棋程序算法的核心*/class ChessModel {//棋盘的宽度、高度、棋盘的模式(如20×15)private int width,height,modeChess;//棋盘方格的横向、纵向坐标private int x=0,y=0;//棋盘方格的横向、纵向坐标所对应的棋子颜色,//数组arrMapShow只有3个值:1,2,3,-5,//其中1代表该棋盘方格上下的棋子为黑子,//2代表该棋盘方格上下的棋子为白子,//3代表为该棋盘方格上没有棋子,//-5代表该棋盘方格不能够下棋子private int[][] arrMapShow;//交换棋手的标识,棋盘方格上是否有棋子的标识符private boolean isOdd,isExist;public ChessModel() {}//该构造方法根据不同的棋盘模式(modeChess)来构建对应大小的棋盘public ChessModel(int modeChess){this.isOdd=true;if(modeChess == 1){PanelInit(20, 15, modeChess);}if(modeChess == 2){PanelInit(30, 20, modeChess);}if(modeChess == 3){PanelInit(40, 30, modeChess);}}//按照棋盘模式构建棋盘大小private void PanelInit(int width, int height, int modeChess){this.width = width;this.height = height;this.modeChess = modeChess;arrMapShow = new int[width+1][height+1];for(int i = 0; i <= width; i++){for(int j = 0; j <= height; j++){arrMapShow[i][j] = -5;}}}//获取是否交换棋手的标识符public boolean getisOdd(){return this.isOdd;}//设置交换棋手的标识符public void setisOdd(boolean isodd){if(isodd)this.isOdd=true;elsethis.isOdd=false;}//获取某棋盘方格是否有棋子的标识值public boolean getisExist(){return this.isExist;}//获取棋盘宽度public int getWidth(){return this.width;}//获取棋盘高度public int getHeight(){return this.height;}//获取棋盘模式public int getModeChess(){return this.modeChess;}//获取棋盘方格上棋子的信息public int[][] getarrMapShow(){return arrMapShow;}//判断下子的横向、纵向坐标是否越界private boolean badxy(int x, int y){if(x >= width+20 || x < 0)return true;return y >= height+20 || y < 0;}//计算棋盘上某一方格上八个方向棋子的最大值,//这八个方向分别是:左、右、上、下、左上、左下、右上、右下public boolean chessExist(int i,int j){if(this.arrMapShow[i][j]==1 || this.arrMapShow[i][j]==2)return true;return false;}//判断该坐标位置是否可下棋子public void readyplay(int x,int y){if(badxy(x,y))return;if (chessExist(x,y))return;this.arrMapShow[x][y]=3;}//在该坐标位置下棋子public void play(int x,int y){if(badxy(x,y))return;if(chessExist(x,y)){this.isExist=true;return;}elsethis.isExist=false;if(getisOdd()){setisOdd(false);this.arrMapShow[x][y]=1;}else{setisOdd(true);this.arrMapShow[x][y]=2;}}//计算机走棋/**说明:用穷举法判断每一个坐标点的四个方向的的最大棋子数,*最后得出棋子数最大值的坐标,下子**/public void computerDo(int width,int height){int max_black,max_white,max_temp,max=0;setisOdd(true);System.out.println("计算机走棋...");for(int i = 0; i <= width; i++){for(int j = 0; j <= height; j++){if(!chessExist(i,j)){//算法判断是否下子max_white=checkMax(i,j,2);//判断白子的最大值max_black=checkMax(i,j,1);//判断黑子的最大值max_temp=Math.max(max_white,max_black);if(max_temp>max){max=max_temp;this.x=i;this.y=j;}}}}setX(this.x);setY(this.y);this.arrMapShow[this.x][this.y]=2;}//记录电脑下子后的横向坐标public void setX(int x){this.x=x;}//记录电脑下子后的纵向坐标public void setY(int y){this.y=y;}//获取电脑下子的横向坐标public int getX(){return this.x;}//获取电脑下子的纵向坐标public int getY(){return this.y;}//计算棋盘上某一方格上八个方向棋子的最大值,//这八个方向分别是:左、右、上、下、左上、左下、右上、右下public int checkMax(int x, int y,int black_or_white){int num=0,max_num,max_temp=0;int x_temp=x,y_temp=y;int x_temp1=x_temp,y_temp1=y_temp;//judge rightfor(int i=1;i<5;i++){x_temp1+=1;if(x_temp1>this.width)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}//judge leftx_temp1=x_temp;for(int i=1;i<5;i++){x_temp1-=1;if(x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}if(num<5)max_temp=num;//judge upx_temp1=x_temp;y_temp1=y_temp;num=0;for(int i=1;i<5;i++){y_temp1-=1;if(y_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}//judge downy_temp1=y_temp;for(int i=1;i<5;i++){y_temp1+=1;if(y_temp1>this.height)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}if(num>max_temp&&num<5)max_temp=num;//judge left_upx_temp1=x_temp;y_temp1=y_temp;num=0;for(int i=1;i<5;i++){x_temp1-=1;y_temp1-=1;if(y_temp1<0 || x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}//judge right_downx_temp1=x_temp;y_temp1=y_temp;for(int i=1;i<5;i++){x_temp1+=1;y_temp1+=1;if(y_temp1>this.height || x_temp1>this.width)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}if(num>max_temp&&num<5)max_temp=num;//judge right_upx_temp1=x_temp;y_temp1=y_temp;num=0;for(int i=1;i<5;i++){x_temp1+=1;y_temp1-=1;if(y_temp1<0 || x_temp1>this.width)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}//judge left_downx_temp1=x_temp;y_temp1=y_temp;for(int i=1;i<5;i++){x_temp1-=1;y_temp1+=1;if(y_temp1>this.height || x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==black_or_white) num++;elsebreak;}if(num>max_temp&&num<5)max_temp=num;max_num=max_temp;return max_num;}//判断胜负public boolean judgeSuccess(int x,int y,boolean isodd){ int num=1;int arrvalue;int x_temp=x,y_temp=y;if(isodd)arrvalue=2;elsearrvalue=1;int x_temp1=x_temp,y_temp1=y_temp;//判断右边for(int i=1;i<6;i++){x_temp1+=1;if(x_temp1>this.width)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue)num++;elsebreak;}//判断左边x_temp1=x_temp;for(int i=1;i<6;i++){if(x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}if(num==5)return true;//判断上方x_temp1=x_temp;y_temp1=y_temp;num=1;for(int i=1;i<6;i++){y_temp1-=1;if(y_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}//判断下方y_temp1=y_temp;for(int i=1;i<6;i++){y_temp1+=1;if(y_temp1>this.height)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}if(num==5)return true;//判断左上x_temp1=x_temp;y_temp1=y_temp;num=1;for(int i=1;i<6;i++){x_temp1-=1;if(y_temp1<0 || x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}//判断右下x_temp1=x_temp;y_temp1=y_temp;for(int i=1;i<6;i++){x_temp1+=1;y_temp1+=1;if(y_temp1>this.height || x_temp1>this.width) break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}if(num==5)return true;//判断右上x_temp1=x_temp;y_temp1=y_temp;num=1;for(int i=1;i<6;i++){x_temp1+=1;y_temp1-=1;if(y_temp1<0 || x_temp1>this.width)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue) num++;elsebreak;}//判断左下x_temp1=x_temp;y_temp1=y_temp;for(int i=1;i<6;i++){x_temp1-=1;y_temp1+=1;if(y_temp1>this.height || x_temp1<0)break;if(this.arrMapShow[x_temp1][y_temp1]==arrvalue)num++;elsebreak;}if(num==5)return true;return false;}//赢棋后的提示public void showSuccess(JPanel jp){JOptionPane.showMessageDialog(jp,"你赢了,好厉害!","win",RMATION_MESSAGE);}//输棋后的提示public void showDefeat(JPanel jp){JOptionPane.showMessageDialog(jp,"你输了,请重新开始!","lost",RMATION_MESSAGE);}}/**类MainPanel主要完成如下功能:*1、构建一个面板,在该面板上画上棋盘;*2、处理在该棋盘上的鼠标事件(如鼠标左键点击、鼠标右键点击、鼠标拖动等)**/class MainPanel extends JPanelimplements MouseListener,MouseMotionListener{private int width,height;//棋盘的宽度和高度private ChessModel cm;//根据棋盘模式设定面板的大小MainPanel(ChessModel mm){cm=mm;width=cm.getWidth();height=cm.getHeight();addMouseListener(this);}//根据棋盘模式设定棋盘的宽度和高度public void setModel(ChessModel mm){cm = mm;width = cm.getWidth();height = cm.getHeight();}//根据坐标计算出棋盘方格棋子的信息(如白子还是黑子),//然后调用draw方法在棋盘上画出相应的棋子public void paintComponent(Graphics g){super.paintComponent(g);for(int j = 0; j <= height; j++){for(int i = 0; i <= width; i++){int v = cm.getarrMapShow()[i][j];draw(g, i, j, v);}}}//根据提供的棋子信息(颜色、坐标)画棋子public void draw(Graphics g, int i, int j, int v){int x = 20 * i+20;int y = 20 * j+20;//画棋盘if(i!=width && j!=height){g.setColor(Color.white);g.drawRect(x,y,20,20);}//画黑色棋子if(v == 1 ){g.setColor(Color.gray);g.drawOval(x-8,y-8,16,16);g.setColor(Color.black);g.fillOval(x-8,y-8,16,16);}//画白色棋子if(v == 2 ){g.setColor(Color.gray);g.drawOval(x-8,y-8,16,16);g.setColor(Color.white);g.fillOval(x-8,y-8,16,16);}if(v ==3){g.setColor(Color.cyan);g.drawOval(x-8,y-8,16,16);}}//响应鼠标的点击事件,根据鼠标的点击来下棋,//根据下棋判断胜负等public void mousePressed(MouseEvent evt){int x = (evt.getX()-10) / 20;int y = (evt.getY()-10) / 20;System.out.println(x+" "+y);if (evt.getModifiers()==MouseEvent.BUTTON1_MASK){cm.play(x,y);System.out.println(cm.getisOdd()+" "+cm.getarrMapShow()[x][y]);repaint();if(cm.judgeSuccess(x,y,cm.getisOdd())){cm.showSuccess(this);evt.consume();ChessFrame.iscomputer=false;}//判断是否为人机对弈if(ChessFrame.iscomputer&&!cm.getisExist()){puterDo(cm.getWidth(),cm.getHeight());repaint();if(cm.judgeSuccess(cm.getX(),cm.getY(),cm.getisOdd())){cm.showDefeat(this);evt.consume();}}}}public void mouseClicked(MouseEvent evt){}public void mouseReleased(MouseEvent evt){}public void mouseEntered(MouseEvent mouseevt){}public void mouseExited(MouseEvent mouseevent){}public void mouseDragged(MouseEvent evt){}//响应鼠标的拖动事件public void mouseMoved(MouseEvent moveevt){int x = (moveevt.getX()-10) / 20;int y = (moveevt.getY()-10) / 20;cm.readyplay(x,y);repaint();}}class ChessWindowEvent extends WindowAdapter{ public void windowClosing(WindowEvent e){ System.exit(0);}ChessWindowEvent(){}}。
教你使⽤Java实现扫雷⼩游戏(最新完整版)⽬录效果展⽰主类:GameWin类底层地图MapBottom类顶层地图MapTop类底层数字BottomNum类初始化地雷BottomRay类⼯具GameUtil类总结⼤家好,我是orangemilk_,哈哈,学习Java已经到⼀个阶段啦,今天我们使⽤GUI来写⼀个扫雷⼩游戏吧!效果展⽰主类:GameWin类package com.sxt;import javax.swing.*;import java.awt.*;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;public class GameWin extends JFrame {int width = 2 * GameUtil.OFFSET + GameUtil.MAP_W * GameUtil.SQUARE_LENGTH;int height = 4 * GameUtil.OFFSET + GameUtil.MAP_H * GameUtil.SQUARE_LENGTH;Image offScreenImage = null;MapBottom mapBottom = new MapBottom();MapTop mapTop = new MapTop();void launch(){GameUtil.START_TIME=System.currentTimeMillis();this.setVisible(true);this.setSize(width,height);this.setLocationRelativeTo(null);this.setTitle("Java扫雷⼩游戏");this.setDefaultCloseOperation(EXIT_ON_CLOSE);//⿏标事件this.addMouseListener(new MouseAdapter() {@Overridepublic void mouseClicked(MouseEvent e) {super.mouseClicked(e);switch (GameUtil.state){case 0 :if(e.getButton()==1){GameUtil.MOUSE_X = e.getX();GameUtil.MOUSE_Y = e.getY();GameUtil.LEFT = true;}if(e.getButton()==3) {GameUtil.MOUSE_X = e.getX();GameUtil.MOUSE_Y = e.getY();GameUtil.RIGHT = true;}//去掉break,任何时候都监听⿏标事件case 1 :case 2 :if(e.getButton()==1){if(e.getX()>GameUtil.OFFSET + GameUtil.SQUARE_LENGTH*(GameUtil.MAP_W/2)&& e.getX()<GameUtil.OFFSET + GameUtil.SQUARE_LENGTH*(GameUtil.MAP_W/2) + GameUtil.SQUARE_LENGTH&& e.getY()>GameUtil.OFFSET&& e.getY()<GameUtil.OFFSET+GameUtil.SQUARE_LENGTH){mapBottom.reGame();mapTop.reGame();GameUtil.FLAG_NUM=0;GameUtil.START_TIME=System.currentTimeMillis();GameUtil.state=0;break;default:}}});while (true){repaint();try {Thread.sleep(40);} catch (InterruptedException e) {e.printStackTrace();}}}@Overridepublic void paint(Graphics g) {offScreenImage = this.createImage(width,height);Graphics gImage = offScreenImage.getGraphics();//设置背景颜⾊gImage.setColor(Color.lightGray);gImage.fillRect(0,0,width,height);mapBottom.paintSelf(gImage);mapTop.paintSelf(gImage);g.drawImage(offScreenImage,0,0,null);}public static void main(String[] args) {GameWin gameWin = new GameWin();unch();}}底层地图MapBottom类//底层地图:绘制游戏相关组件package com.sxt;import java.awt.*;public class MapBottom {BottomRay bottomRay = new BottomRay();BottomNum bottomNum = new BottomNum();{bottomRay.newRay();bottomNum.newNum();}//重置游戏void reGame(){for (int i = 1; i <=GameUtil.MAP_W ; i++) {for (int j = 1; j <=GameUtil.MAP_H ; j++) {GameUtil.DATA_BOTTOM[i][j]=0;}}bottomRay.newRay();bottomNum.newNum();}//绘制⽅法void paintSelf(Graphics g){g.setColor(Color.BLACK);//画竖线for (int i = 0; i <= GameUtil.MAP_W; i++) {g.drawLine(GameUtil.OFFSET + i * GameUtil.SQUARE_LENGTH,3*GameUtil.OFFSET,GameUtil.OFFSET+i*GameUtil.SQUARE_LENGTH,3*GameUtil.OFFSET+GameUtil.MAP_H*GameUtil.SQUARE_LENGTH);}//画横线for (int i = 0; i <=GameUtil.MAP_H; i++){g.drawLine(GameUtil.OFFSET,3*GameUtil.OFFSET+i*GameUtil.SQUARE_LENGTH,GameUtil.OFFSET+GameUtil.MAP_W*GameUtil.SQUARE_LENGTH,3*GameUtil.OFFSET+i*GameUtil.SQUARE_LENGTH);}for (int i = 1; i <= GameUtil.MAP_W ; i++) {for (int j = 1; j <= GameUtil.MAP_H; j++) {//雷if (GameUtil.DATA_BOTTOM[i][j] == -1) {g.drawImage(GameUtil.lei,GameUtil.OFFSET + (i - 1) * GameUtil.SQUARE_LENGTH + 1,GameUtil.OFFSET * 3 + (j - 1) * GameUtil.SQUARE_LENGTH + 1,GameUtil.SQUARE_LENGTH - 2,GameUtil.SQUARE_LENGTH - 2,null);}//数字if (GameUtil.DATA_BOTTOM[i][j] >=0) {g.drawImage(GameUtil.images[GameUtil.DATA_BOTTOM[i][j]],GameUtil.OFFSET + (i - 1) * GameUtil.SQUARE_LENGTH + 15,GameUtil.OFFSET * 3 + (j - 1) * GameUtil.SQUARE_LENGTH + 5,null);}}}//绘制数字,剩余雷数,倒计时GameUtil.drawWord(g,""+(GameUtil.RAY_MAX-GameUtil.FLAG_NUM),GameUtil.OFFSET,2*GameUtil.OFFSET,30,Color.red);GameUtil.drawWord(g,""+(GameUtil.END_TIME-GameUtil.START_TIME)/1000,GameUtil.OFFSET + GameUtil.SQUARE_LENGTH*(GameUtil.MAP_W-1),2*GameUtil.OFFSET,30,Color.red);switch (GameUtil.state){case 0:GameUtil.END_TIME=System.currentTimeMillis();g.drawImage(GameUtil.face,GameUtil.OFFSET + GameUtil.SQUARE_LENGTH * (GameUtil.MAP_W/2), GameUtil.OFFSET,null);break;case 1:g.drawImage(GameUtil.win,GameUtil.OFFSET + GameUtil.SQUARE_LENGTH * (GameUtil.MAP_W/2), GameUtil.OFFSET,null);g.drawImage(GameUtil.over,GameUtil.OFFSET + GameUtil.SQUARE_LENGTH * (GameUtil.MAP_W/2),GameUtil.OFFSET,null);break;default:}}}顶层地图MapTop类顶层地图类:绘制顶层组件package com.sxt;import java.awt.*;public class MapTop {//格⼦位置int temp_x;int temp_y;//重置游戏void reGame(){for (int i = 1; i <=GameUtil.MAP_W ; i++) {for (int j = 1; j <=GameUtil.MAP_H ; j++) {GameUtil.DATA_TOP[i][j]=0;}}}//判断逻辑void logic(){temp_x=0;temp_y=0;if(GameUtil.MOUSE_X>GameUtil.OFFSET && GameUtil.MOUSE_Y>3*GameUtil.OFFSET){ temp_x = (GameUtil.MOUSE_X - GameUtil.OFFSET)/GameUtil.SQUARE_LENGTH+1;temp_y = (GameUtil.MOUSE_Y - GameUtil.OFFSET * 3)/GameUtil.SQUARE_LENGTH+1; }if(temp_x>=1 && temp_x<=GameUtil.MAP_W&& temp_y>=1 && temp_y<=GameUtil.MAP_H){if(GameUtil.LEFT){//覆盖,则翻开if(GameUtil.DATA_TOP[temp_x][temp_y]==0){GameUtil.DATA_TOP[temp_x][temp_y]=-1;}spaceOpen(temp_x,temp_y);GameUtil.LEFT=false;}if(GameUtil.RIGHT){//覆盖则插旗if(GameUtil.DATA_TOP[temp_x][temp_y]==0){GameUtil.DATA_TOP[temp_x][temp_y]=1;GameUtil.FLAG_NUM++;}//插旗则取消else if(GameUtil.DATA_TOP[temp_x][temp_y]==1){GameUtil.DATA_TOP[temp_x][temp_y]=0;GameUtil.FLAG_NUM--;}else if(GameUtil.DATA_TOP[temp_x][temp_y]==-1){numOpen(temp_x,temp_y);}GameUtil.RIGHT=false;}}boom();victory();}//数字翻开void numOpen(int x,int y){//记录旗数int count=0;if(GameUtil.DATA_BOTTOM[x][y]>0){for (int i = x-1; i <=x+1 ; i++) {for (int j = y-1; j <=y+1 ; j++) {if(GameUtil.DATA_TOP[i][j]==1){count++;}}}if(count==GameUtil.DATA_BOTTOM[x][y]){for (int i = x-1; i <=x+1 ; i++) {for (int j = y-1; j <=y+1 ; j++) {if(GameUtil.DATA_TOP[i][j]!=1){GameUtil.DATA_TOP[i][j]=-1;}//必须在雷区当中if(i>=1&&j>=1&&i<=GameUtil.MAP_W&&j<=GameUtil.MAP_H){spaceOpen(i,j);}}}}}}//失败判定 t 表⽰失败 f 未失败boolean boom(){if(GameUtil.FLAG_NUM==GameUtil.RAY_MAX){for (int i = 1; i <=GameUtil.MAP_W ; i++) {for (int j = 1; j <=GameUtil.MAP_H ; j++) {if(GameUtil.DATA_TOP[i][j]==0){GameUtil.DATA_TOP[i][j]=-1;}}}}for (int i = 1; i <=GameUtil.MAP_W ; i++) {for (int j = 1; j <=GameUtil.MAP_H ; j++) {if(GameUtil.DATA_BOTTOM[i][j]==-1&&GameUtil.DATA_TOP[i][j]==-1){GameUtil.state = 2;seeBoom();return true;}}//失败显⽰void seeBoom(){for (int i = 1; i <=GameUtil.MAP_W ; i++) {for (int j = 1; j <=GameUtil.MAP_H ; j++) {//底层是雷,顶层不是旗,显⽰if(GameUtil.DATA_BOTTOM[i][j]==-1&&GameUtil.DATA_TOP[i][j]!=1){GameUtil.DATA_TOP[i][j]=-1;}//底层不是雷,顶层是旗,显⽰差错旗if(GameUtil.DATA_BOTTOM[i][j]!=-1&&GameUtil.DATA_TOP[i][j]==1){GameUtil.DATA_TOP[i][j]=2;}}}}//胜利判断 t 表⽰胜利 f 未胜利boolean victory(){//统计未打开格⼦数int count=0;for (int i = 1; i <=GameUtil.MAP_W ; i++) {for (int j = 1; j <=GameUtil.MAP_H ; j++) {if(GameUtil.DATA_TOP[i][j]!=-1){count++;}}}if(count==GameUtil.RAY_MAX){GameUtil.state=1;for (int i = 1; i <=GameUtil.MAP_W ; i++) {for (int j = 1; j <=GameUtil.MAP_H ; j++) {//未翻开,变成旗if(GameUtil.DATA_TOP[i][j]==0){GameUtil.DATA_TOP[i][j]=1;}}}return true;}return false;}//打开空格void spaceOpen(int x,int y){if(GameUtil.DATA_BOTTOM[x][y]==0){for (int i = x-1; i <=x+1 ; i++) {for (int j = y-1; j <=y+1 ; j++) {//覆盖,才递归if(GameUtil.DATA_TOP[i][j]!=-1){if(GameUtil.DATA_TOP[i][j]==1){GameUtil.FLAG_NUM--;}GameUtil.DATA_TOP[i][j]=-1;//必须在雷区当中if(i>=1&&j>=1&&i<=GameUtil.MAP_W&&j<=GameUtil.MAP_H){spaceOpen(i,j);}}}}}}//绘制⽅法void paintSelf(Graphics g){logic();for (int i = 1; i <= GameUtil.MAP_W ; i++) {for (int j = 1; j <= GameUtil.MAP_H; j++) {//覆盖if (GameUtil.DATA_TOP[i][j] == 0) {g.drawImage(GameUtil.top,GameUtil.OFFSET + (i - 1) * GameUtil.SQUARE_LENGTH + 1,GameUtil.OFFSET * 3 + (j - 1) * GameUtil.SQUARE_LENGTH + 1, GameUtil.SQUARE_LENGTH - 2,GameUtil.SQUARE_LENGTH - 2,null);}//插旗if (GameUtil.DATA_TOP[i][j] == 1) {g.drawImage(GameUtil.flag,GameUtil.OFFSET + (i - 1) * GameUtil.SQUARE_LENGTH + 1,GameUtil.OFFSET * 3 + (j - 1) * GameUtil.SQUARE_LENGTH + 1, GameUtil.SQUARE_LENGTH - 2,GameUtil.SQUARE_LENGTH - 2,null);}//差错旗if (GameUtil.DATA_TOP[i][j] == 2) {g.drawImage(GameUtil.noflag,GameUtil.OFFSET + (i - 1) * GameUtil.SQUARE_LENGTH + 1,GameUtil.OFFSET * 3 + (j - 1) * GameUtil.SQUARE_LENGTH + 1, GameUtil.SQUARE_LENGTH - 2,GameUtil.SQUARE_LENGTH - 2,null);}}}}}底层数字BottomNum类//底层数字类package com.sxt;public class BottomNum {void newNum() {for (int i = 1; i <=GameUtil.MAP_W ; i++) {for (int j = 1; j <=GameUtil.MAP_H ; j++) {if(GameUtil.DATA_BOTTOM[i][j]==-1){for (int k = i-1; k <=i+1 ; k++) {for (int l = j-1; l <=j+1 ; l++) {if(GameUtil.DATA_BOTTOM[k][l]>=0){}}}}}}初始化地雷BottomRay类//初始化地雷类package com.sxt;public class BottomRay {//存放坐标int[] rays = new int[GameUtil.RAY_MAX*2];//地雷坐标int x,y;//是否放置 T 表⽰可以放置 F 不可放置boolean isPlace = true;//⽣成雷void newRay() {for (int i = 0; i < GameUtil.RAY_MAX*2 ; i=i+2) {x= (int) (Math.random()*GameUtil.MAP_W +1);//1-12y= (int) (Math.random()*GameUtil.MAP_H +1);//1-12//判断坐标是否存在for (int j = 0; j < i ; j=j+2) {if(x==rays[j] && y==rays[j+1]){i=i-2;isPlace = false;break;}}//将坐标放⼊数组if(isPlace){rays[i]=x;rays[i+1]=y;}isPlace = true;}for (int i = 0; i < GameUtil.RAY_MAX*2; i=i+2) {GameUtil.DATA_BOTTOM[rays[i]][rays[i+1]]=-1;}}}⼯具GameUtil类//⼯具类:存放静态参数,⼯具⽅法package com.sxt;import java.awt.*;public class GameUtil {//地雷个数static int RAY_MAX = 5;//地图的宽static int MAP_W = 11;//地图的⾼static int MAP_H = 11;//雷区偏移量static int OFFSET = 45;//格⼦边长static int SQUARE_LENGTH = 50;//插旗数量static int FLAG_NUM = 0;//⿏标相关//坐标static int MOUSE_X;static int MOUSE_Y;//状态static boolean LEFT = false;static boolean RIGHT = false;//游戏状态 0 表⽰游戏中 1 胜利 2 失败static int state = 0;//倒计时static long START_TIME;static long END_TIME;//底层元素 -1 雷 0 空 1-8 表⽰对应数字static int[][] DATA_BOTTOM = new int[MAP_W+2][MAP_H+2];//顶层元素 -1 ⽆覆盖 0 覆盖 1 插旗 2 差错旗static int[][] DATA_TOP = new int[MAP_W+2][MAP_H+2];//载⼊图⽚static Image lei = Toolkit.getDefaultToolkit().getImage("imgs/lei.png");static Image top = Toolkit.getDefaultToolkit().getImage("imgs/top.gif");static Image flag = Toolkit.getDefaultToolkit().getImage("imgs/flag.gif");static Image noflag = Toolkit.getDefaultToolkit().getImage("imgs/noflag.png");static Image face = Toolkit.getDefaultToolkit().getImage("imgs/face.png");static Image over = Toolkit.getDefaultToolkit().getImage("imgs/over.png");static Image win = Toolkit.getDefaultToolkit().getImage("imgs/win.png");static Image[] images = new Image[9];static {for (int i = 1; i <=8 ; i++) {images[i] = Toolkit.getDefaultToolkit().getImage("imgs/num/"+i+".png");}}static void drawWord(Graphics g,String str,int x,int y,int size,Color color){g.setColor(color);g.setFont(new Font("仿宋",Font.BOLD,size));g.drawString(str,x,y);}}总结在使⽤Java编写扫雷⼩游戏时遇到了很多问题,在解决问题时,确实对java的⾯向对象编程有了更加深⼊的理解。
public class CardGame { static int userMoney = 0; static int computerMoney = 0; static int[] handcards = new int[6];
public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("请输入赌本:"); userMoney = sc.nextInt(); computerMoney = userMoney; while (userMoney > 0 && computerMoney > 0) { System.out.println("请输入本局赌注:"); int duzhu = sc.nextInt(); if (duzhu <= 0 || duzhu > userMoney || duzhu > computerMoney) { System.out.println("赌注不正确,请重新输入:"); continue; } printpai(); System.out.println(); if (compara() > 0) { System.out.println("玩家获胜!"); userMoney += duzhu; computerMoney -= duzhu; } else if (compara() < 0) { System.out.println("电脑获胜!"); userMoney -= duzhu; computerMoney += duzhu; } else { System.out.println("平局!"); } System.out .println("玩家赌本为:" + userMoney + " 电脑赌本为:" + computerMoney); } }
public static void printpai() { for (int j = 0; j < handcards.length; j++) { int huase = (int) (Math.random() * 4 + 1); int paimian = (int) (Math.random() * 13 + 2); handcards[j] = (huase * 100 + paimian); switch (huase) { case 1: System.out.print("黑桃"); break; case 2: System.out.print("红桃"); break; case 3: System.out.print("梅花"); break; case 4: System.out.print("方块"); break; } if (handcards[j] % 100 <= 10) { System.out.print(handcards[j] % 100 + " "); } else { switch (handcards[j] % 10) { case 1: System.out.print("J "); break; case 2: System.out.print("Q "); break; case 3: System.out.print("K "); break; case 4: System.out.print("A "); break; } } } }
// 比较两手牌时不能用数字的大小sum+(handcards[j] = (huase * 100 + paimian)) // 的加以判断,那样判断的结果会令 黑桃A黑桃Q的情况,不符合现实 public static int compara() { int[] userCard = new int[handcards.length / 2]; int[] computerCard = new int[handcards.length / 2]; // 打印数字类型的牌面值,数组 // System.out.println(Arrays.toString(handcards)); // 定义玩家的牌,取数组元素的前三个 for (int i = 0; i < userCard.length; i++) { userCard[i] = handcards[i]; } // 定义电脑的牌,取数组元素的后三个 for (int i = handcards.length / 2; i < handcards.length; i++) { computerCard[i - handcards.length / 2] = handcards[i]; } // 比较两玩家的牌的大小值 return fromCardToNumber(userCard) - fromCardToNumber(computerCard); }
public static int fromCardToNumber(int[] temp) { // 下面是一段 冒泡排序 for (int i = 0; i < temp.length; i++) { // 比牌面值的大小,即现实中红桃5(代表205)永远是比 黑桃(K113)要小的,对牌的大小顺序进行排序 for (int j = 0; j < temp.length - i - 1; j++) { if (temp[j] % 100 < temp[j + 1] % 100) { int tmp = temp[j]; temp[j] = temp[j + 1]; temp[j + 1] = tmp; } } // 输出冒泡排序的两组数字,前面一半的数组值代表玩家的,后一半的数组值代表式电脑的 // System.out.print(temp[i] + " "); } // System.out.println(); int num = 0; // 判断三条的情况 if (temp[0] % 100 == temp[1] % 100 && temp[1] % 100 == temp[2] % 100) { num = 6 * 1000000 + temp[0] % 100 * 10000 + temp[1] % 100 * 100 + temp[2] % 100; } else if (temp[0] / 100 == temp[1] / 100 && temp[1] / 100 == temp[2] / 100 && temp[0] % 100 == temp[1] % 100 + 1 && temp[1] % 100 == temp[2] % 100 + 1) { num = 5 * 1000000 + temp[0] % 100 * 10000 + temp[1] % 100 * 100 + temp[2] % 100; } else if (temp[0] / 100 == temp[1] / 100 && temp[1] / 100 == temp[2] / 100) { num = 4 * 1000000 + temp[0] % 100 * 10000 + temp[1] % 100 * 100 + temp[2] % 100; } else if (temp[0] % 100 == temp[1] % 100 + 1 && temp[1] % 100 == temp[2] % 100 + 1) { num = 3 * 1000000 + temp[0] % 100 * 10000 + temp[1] % 100 * 100 + temp[2] % 100; // 数组是从大到小排列的,因此在比较时 要注意 } else if (temp[0] % 100 == temp[1] % 100 || temp[1] % 100 == temp[2] % 100) { num = 2 * 1000000 + temp[0] % 100 * 10000 + temp[1] % 100 * 100 + temp[2] % 100; } else { num = 1 * 1000000 + temp[0] % 100 * 10000 + temp[1] % 100 * 100 + temp[2] % 100; } return num;
} } -------------------------------------------------------------------------------------------------------------- /* *
用面向对象的方式重写扑克牌游戏程序,定义以下类型: 1,花色,枚举类型,包含枚举值:黑,红,梅,方。 2,点数,枚举类型,包含枚举值:2-A 3,一张扑克牌(Card):包含属性:花色,点数 4,一手扑克牌(OneHandCards): 包含属性:Card[] cards;//三张扑克牌 方法: public int compareTo(OneHandCards c); 该方法返回某两手扑克牌大小比较的结果: 如果当前这手牌比c大,则返回>0的值 如果当前这手牌比c小,则返回<0的值 如果当前这手牌和c相等,则返回0 5,玩家类(Player) :包含属性:姓名,赌本,当前一手牌
6,游戏类(Game):包含属性:两个玩家 包含方法:void 发牌();为该游戏中的所有玩家发牌。 void startGame();开始游戏。 */
package Leiduixiang; import java.util.Scanner;; public class StudentManage { static int[][] a = {{70,67,67,78},{90,89,78,78},{98,87,89,84},{90,98,87,56}}; static String[] b = {"语文","数学","英语","化学"}; static String[] c = {"张三","张四","张五","张六"}; public static void main(String[] args) {