200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > Java游戏开发——开心农场

Java游戏开发——开心农场

时间:2023-06-15 15:31:03

相关推荐

Java游戏开发——开心农场

游戏介绍:

“开心农场”是一款以种植为主的社交游戏。用户可以扮演一个农场的农场主,在自己的农场里开垦土地,种植各种水果蔬菜。本次开发了一个“开心农场”游戏,运行程序,效果如下图所示。鼠标先选定指定土地(默认选择第一块土地),点击“播种”按钮,可以播种种子;点击“生长”按钮,可以让作物处于生长阶段;点击“开花”按钮,可以让作物处于开花阶段;点击“结果”按钮,可以让作物结果;点击“收获”按钮,可以收获果实到仓库。默认生长期为1分钟,开花期为2分钟,落果期为3分钟,支持作物离线生长。

使用素材文件夹:

素材以及完整源码链接:/s/1p1rXX1VlB21RnLfHEAStCg 提取码: gszw

游戏设计的思路:

使用一个带背景的面板作为游戏面板,图片里有九块可种植的土地,每块土地对应的Farm对象存储当前土地状态和最后一次操作时间,先判断鼠标点击的哪块土地,再对选定的土地进行后续操作。面板使用“播种”、“生长”、“开花”、“结果”、“收获”五个按钮和9个用于表示九块土地上的作物的Crop对象。5个按钮的点击事件,会改变土地的状态和最后操作时间以及Crop对象的图片,通过改变Crop对象的图片可以达到农作物各种状态的转变。使用文本存储当前游戏数据,使用线程每秒自动刷新游戏页面并更新文件中的游戏数据,在游戏初始化时先读取历史数据,再做状态的换算,用以达到作物离线生长的作用。

设计步骤:

1.1设计农作物Crop类:

农作物Crop类实现作物状态的显示,通过继承JLabel组件和设置JLabel组件的Icon实现。

package farmGame;import javax.swing.Icon;import javax.swing.ImageIcon;import javax.swing.JLabel;public class Crop extends JLabel{Icon icon = null;public Crop(){super();}public void setIcon(String picture){icon = new ImageIcon(picture);//获取图片setIcon(icon);}}

1.2设计游戏面板BackgroundPanel类:

BackgroundPanel类主要用来显示游戏背景图。

package farmGame;import java.awt.Graphics;import java.awt.Image;import javax.swing.JPanel;public class BackgroundPanel extends JPanel{private Image image;public BackgroundPanel(){super();setOpaque(false);//当设置为false时,组件并未不会显示其中的某些像素,允许控件下面的像素显现出来。setLayout(null);}public void setImage(Image image){this.image = image;}protected void paintComponent(Graphics g){//重写绘制组件外观方法if(image!=null){int width = getWidth();int height = getHeight();g.drawImage(image, 0, 0, width, height, this);}super.paintComponent(g);}}

1.3农场土地Farm类:

Farm类对象用来存储一块土地的状态和最后一次操作时间(例如播种),包含该块土地相关的播种、生长、开花、结果、收获操作;state==0时未播种,state==1时已播种,state==2时生长中,state==3时开花中,state==4已结果;每次操作如果符合条件修改state值和最后一次操作时间,否则设置提示信息为不能播种。

package farmGame;import java.io.Serializable;import java.util.Date;public class Farm implements Serializable {private static final long serialVersionUID = 1L;public int state = 0;public Date lastTime = null;public int getState() {return state;}public void setState(int state) {this.state = state;}public Date getLastTime() {return lastTime;}public void setLastTime(Date lastTime) {this.lastTime = lastTime;}public String seed(Crop crop,String picture){String returnValue = "";if(state == 0){crop.setIcon(picture);state = 1;lastTime = new Date();}else{returnValue = getMessage()+",不能播种";}return returnValue;}public String grow(Crop crop,String picture){String returnValue = "";if(state == 1){crop.setIcon(picture);state = 2;lastTime = new Date();}else{returnValue = getMessage()+",不能生长";}return returnValue;}public String bloom(Crop crop,String picture){String returnValue = "";if(state == 2){crop.setIcon(picture);state = 3;lastTime = new Date();}else{returnValue = getMessage()+",不能开花";}return returnValue;}public String fruit(Crop crop,String picture){String returnValue = "";if(state == 3){crop.setIcon(picture);state = 4;lastTime = new Date();}else{returnValue = getMessage()+",不能结果";}return returnValue;}public String harvest(Crop crop,String picture){String returnValue="";if(state==4){crop.setIcon(picture);state = 0;lastTime = null;}else{returnValue = getMessage()+",不能收获!";}return returnValue;}public String getMessage() {String message = "";switch(state){case 0:message = "作物还没有播种";break;case 1:message = "作物刚刚播种";break;case 2:message = "作物正在生长";break;case 3:message = "作物正处于开花期";break;case 4:message = "作物已经结果";break;}return message;}}

1.4设计游戏窗口MainFrame类:

编写一个继承自JFrame类的MainFrame窗体类,用于完成播种、生长、开花、结果、收获等操作。

GROWTIME常量表示1分钟的生长期毫秒数,BLOOMTIME和FRUITTIME表示2分钟的开花期毫秒数和3分钟的落果期毫秒数,fruitNumber记录仓库果实数量,farms对应9块土地,crops对应9块土地上的作物图片,isInDiamond()方法用于判断鼠标点击的是哪块土地,saveNowState()方法用于存储当前游戏数据,readNowState()方法用于读取历史游戏数据并转换成当前时间对应的游戏数据,线程每秒执行一次存储游戏和读取游戏的操作。

详细说明:

判断鼠标选定的是哪块土地

在这里土地是菱形土地,所以需要判断点在哪块菱形土地上,经测量,菱形土地宽width160px,高height65px;先让鼠标点击点依次尝试位移九块土地的中心点(点击处坐标-每个菱形中心坐标=点击处相对于每个菱形中心的坐标x,y),

如果|x*width|+|y*height|<=width*height*0.5,说明点击处位于该块菱形土地内,否则位于该块土地外。

详细证明过程参考:/hany3000/article/details/11265499

如果每块土地都判断过一次相对点是否在菱形上,并且点击处都不在其上,说明没有选中可种植土地。

②种植信息的保存

这里使用文本IO的形式进行保存,存储格式是

第一块土地上的种植状态,第一块土地最后一次操作时间;第二块土地种植状态,第二块土地最后一次操作时间;......第九块土地种植状态,第九块土地最后一次操作时间&当前仓库果实数

③种植信息的读取

先读取文本字符串str,使用str.split("&")将文本分割成两段,第一段array1[0]表示9块土地相关信息,第二段array1[1]表示当前仓库果实数量;对array1[0]进行细分,array1[0].split(";")得到每块土地的种植信息和最后一次操作时间拼接得到的字符串array2数组;再对array2[i]进行细分,array2[i].split(",")得到help数组,help[0]表示土地种植状态,help[1]表示土地最后一次操作时间。

④作物状态的转换

每块土地的最后一次操作时间是使用Date对象存储的,上面获取到了每块土地的种植状态和最后一次操作时间,那么可以先使用new Date()获取当前时间,根据当前时间的长整型的毫秒数和最后一次操作时间长整型的毫秒数相减,得到中间相差了subTime毫秒。

创建temp变量暂存变化时间;

如果种植状态是已播种,判断subTime是否大于生长期GROWTIME,如果大于说明现在可以进入到下一阶段,subTime-=GROWTIME,emp+=GROWTIME,并且种植状态改为已生长。

接着如果当前种植状态是已生长,判断subTime是否大于开花期BLOOMTIME,如果大于说明现在可以进入到下一阶段,subTime-=BLOOMTIME,temp+=BLOOMTIME,并且种植时间改为已开花。

再如果当前种植状态是已开花,判断subTime是否大于落果期FRUITTIME,如果大于说明现在可以进入到下一阶段,subTime-=FRUITTIME,temp+=FRUITTIME,并且种植时间改为已结果。

最后判断当前种植状态是什么,将最后一次操作时间+=temp得到新的最后一次操作时间,然后将当前土地对应的作物的图片进行修改,便得到了最新的农场状态。

⑤自动更新游戏数据

创建线程,线程开始时先休眠1000毫秒,再保存游戏数据,读取游戏数据(读取历史游戏数据和更新游戏状态是在同一个方法里做到的);休眠1000毫秒......依次循环

这样可以确保每秒都能及时保存游戏数据,并且保证当前农场状态的正确性。

MainFrame类完整代码:

package farmGame;import java.awt.EventQueue;import java.awt.Image;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 java.io.DataInputStream;import java.io.DataOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.FileWriter;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.Date;import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.SwingConstants;public class MainFrame extends JFrame implements MouseListener,Runnable{int fruitNumber = 0;Farm[] farms = new Farm[9];Crop[] crops = new Crop[9];Farm farm = new Farm();Crop crop = new Crop();JLabel storage;SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");FileInputStream fis = null;FileOutputStream fos = null;DataInputStream dis = null;DataOutputStream dos = null;//生长期1小时,开花期2小时,结果期3小时public static final long GROWTIME = 1000*60,BLOOMTIME = 1000*60*2,FRUITTIME = 1000*60*3;public MainFrame(){super();setTitle("打造自己的开心农场");setBounds(500,200,900,600);//设置窗口位置和大小setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);addMouseListener(this);final BackgroundPanel backgroundPanel = new BackgroundPanel();Image bk = Toolkit.getDefaultToolkit().getImage("D:/Game/FarmGame/farmBackground.png");backgroundPanel.setImage(bk);backgroundPanel.setBounds(0,0,855,553);//设置游戏面板位置和大小getContentPane().add(backgroundPanel);storage = new JLabel();storage.setHorizontalAlignment(SwingConstants.CENTER);storage.setText("您的仓库没有任何果实,快快播种吧!");storage.setBounds(200,70,253,28);//标签位置backgroundPanel.add(storage);initlize();for(Crop temp:crops){backgroundPanel.add(temp);}final JButton button_1 = new JButton();//播种button_1.setRolloverIcon(new ImageIcon("D:/Game/FarmGame/播种1.png"));//移动到图标上显示的图片button_1.setBorderPainted(false);button_1.setContentAreaFilled(false);button_1.setIcon(new ImageIcon("D:/Game/FarmGame/播种.png"));//正常显示图片button_1.addActionListener(new ActionListener(){@Overridepublic void actionPerformed(ActionEvent e) {if(farm == null)//如果没有先选中土地return ;String message = farm.seed(crop, "D:/Game/FarmGame/seed.png");if(!message.equals("")){JOptionPane.showMessageDialog(null, message);}}});button_1.setBounds(140,477,56,56);//29, 185, 56, 56backgroundPanel.add(button_1);final JButton button_2 = new JButton();//生长button_2.setContentAreaFilled(false);button_2.setBorderPainted(false);button_2.setRolloverIcon(new ImageIcon("D:/Game/FarmGame/生长1.png"));button_2.setIcon(new ImageIcon("D:/Game/FarmGame/生长.png"));button_2.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {if(farm == null)//如果没有先选中土地return ;String message = farm.grow(crop, "D:/Game/FarmGame/grow.png");if(!message.equals("")){JOptionPane.showMessageDialog(null, message);}}});backgroundPanel.add(button_2);button_2.setBounds(280,477,56,56);//114,185,56,56final JButton button_3 = new JButton();button_3.setContentAreaFilled(false);button_3.setBorderPainted(false);button_3.setRolloverIcon(new ImageIcon("D:/Game/FarmGame/开花1.png"));button_3.setIcon(new ImageIcon("D:/Game/FarmGame/开花.png"));button_3.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {if(farm == null)//如果没有先选中土地return ;String message = farm.bloom(crop, "D:/Game/FarmGame/bloom.png");if(!message.equals("")){JOptionPane.showMessageDialog(null, message);}}});backgroundPanel.add(button_3);button_3.setBounds(420,477,56,56);//199,185,56,56;final JButton button_4 = new JButton();button_4.setContentAreaFilled(false);button_4.setBorderPainted(false);button_4.setRolloverIcon(new ImageIcon("D:/Game/FarmGame/结果1.png"));button_4.setIcon(new ImageIcon("D:/Game/FarmGame/结果.png"));button_4.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {if(farm == null)//如果没有先选中土地return ;String message = farm.fruit(crop,"D:/Game/FarmGame/fruit.png");if(!message.equals("")){JOptionPane.showMessageDialog(null, message);}}});backgroundPanel.add(button_4);button_4.setBounds(560,477,56,56);final JButton button_5 = new JButton();button_5.setContentAreaFilled(false);button_5.setBorderPainted(false);button_5.setRolloverIcon(new ImageIcon("D:/Game/FarmGame/收获1.png"));button_5.setIcon(new ImageIcon("D:/Game/FarmGame/收获.png"));button_5.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {if(farm == null)//如果没有先选中土地return ;String message = farm.harvest(crop, "");if(!message.equals("")){JOptionPane.showMessageDialog(null, message);}else{fruitNumber++;storage.setText("您的仓库现在有"+fruitNumber+"个果实.");}}});backgroundPanel.add(button_5);button_5.setBounds(700,477,56,56);//369,185,56,56new Thread(this).start();}public void initlize(){for(int i=0;i<9;i++){farms[i] = new Farm();crops[i] = new Crop();}crops[0].setBounds(269, 153, 106, 96);crops[1].setBounds(165, 195, 106, 96);crops[2].setBounds(59, 238, 106, 96);crops[3].setBounds(378, 199, 106, 96);crops[4].setBounds(278, 236, 106, 96);crops[5].setBounds(169, 284, 106, 96);crops[6].setBounds(501, 247, 106, 96);crops[7].setBounds(393, 281, 106, 96);crops[8].setBounds(286, 333, 106, 96);farm = farms[0];//默认选中第一块土地crop = crops[0];//默认第一株植物readNowState();//更新现在状态}@Overridepublic void mouseClicked(MouseEvent e) {// TODO Auto-generated method stubint x = e.getX();int y = e.getY();System.out.println("x is "+x+", y is "+y);if(isInDiamond(x-324,y-258,160,65)){//第一块土地System.out.println("第一块土地");farm = farms[0];crop = crops[0];}else if(isInDiamond(x-220,y-300,160,65)){System.out.println("第二块土地");farm = farms[1];crop = crops[1];}else if(isInDiamond(x-114,y-343,160,65)){System.out.println("第三块土地");farm = farms[2];crop = crops[2];}else if(isInDiamond(x-433,y-304,160,65)){System.out.println("第四块土地");farm = farms[3];crop = crops[3];}else if(isInDiamond(x-333,y-341,160,65)){System.out.println("第五块土地");farm = farms[4];crop = crops[4];}else if(isInDiamond(x-224,y-389,160,65)){System.out.println("第六块土地");farm = farms[5];crop = crops[5];}else if(isInDiamond(x-556,y-352,160,65)){System.out.println("第七块土地");farm = farms[6];crop = crops[6];}else if(isInDiamond(x-448,y-386,160,65)){System.out.println("第八块土地");farm = farms[7];crop = crops[7];}else if(isInDiamond(x-341,y-438,160,65)){//第九块土地System.out.println("第九块土地");farm = farms[8];crop = crops[8];}else{farm = null;crop = null;System.out.println("没有选中任何土地");}}//width菱形宽,height菱形高public boolean isInDiamond(int x,int y,int width,int height){if(Math.abs(x*height)+Math.abs(y*width)<=width*height*0.5){return true;}return false;}public void readNowState(){File file = new File("D://GameRecordAboutSwing");if(!file.exists()){file.mkdirs();}File record = new File("D://GameRecordAboutSwing/recordFarmGame.txt");try{if(!record.exists()){//如果不存在,新建文本record.createNewFile();fos = new FileOutputStream(record);dos = new DataOutputStream(fos);String s = "0,null;0,null;0,null;0,null;0,null;0,null;0,null;0,null;0,null&0";dos.writeBytes(s);System.out.println(record.isFile());;}//读取记录fis = new FileInputStream(record);dis = new DataInputStream(fis);String str = dis.readLine();String[] array1 = str.split("&");//作物相关String[] array2 = array1[0].split(";");//土地相关fruitNumber = Integer.parseInt(array1[1]);//仓库果实if(fruitNumber == 0){storage.setText("您的仓库没有任何果实,快快播种吧!");}else{storage.setText("您的仓库现在有"+fruitNumber+"个果实.");}for(int i=0;i<9;i++){String[] help = array2[i].split(",");int state = Integer.parseInt(help[0]);if(help[1].equals("null")){//未播种,直接跳过continue;}Date lastTime = sdf.parse(help[1]);Date nowTime = new Date();long subTime = nowTime.getTime() - lastTime.getTime();//得到相差毫秒數long temp = 0;//存储farm[i]最后操作的时间到当前时间的时间差(毫秒表示)if(state == 1){//已播种if(subTime>=GROWTIME){subTime -= GROWTIME;temp += GROWTIME;state = 2;}}if(state == 2){//已生长if(subTime>=BLOOMTIME){subTime -= BLOOMTIME;temp += BLOOMTIME;state = 3;}}if(state == 3){//已开花if(subTime>=FRUITTIME){subTime -= FRUITTIME;temp += FRUITTIME;state = 4;}}switch(state){case 1:farms[i].state = 1;farms[i].lastTime = lastTime;crops[i].setIcon("D:/Game/FarmGame/seed.png");break;case 2:farms[i].state = 2;farms[i].lastTime = new Date(lastTime.getTime()+temp);crops[i].setIcon("D:/Game/FarmGame/grow.png");break;case 3:farms[i].state = 3;farms[i].lastTime = new Date(lastTime.getTime()+temp);crops[i].setIcon("D:/Game/FarmGame/bloom.png");break;case 4:farms[i].state = 4;farms[i].lastTime = new Date(lastTime.getTime()+temp);crops[i].setIcon("D:/Game/FarmGame/fruit.png");break;}}}catch(Exception e){e.printStackTrace();}finally{try {if(fis!=null)fis.close();if(dis!=null)dis.close();if(fos!=null)fos.close();if(dos!=null)dos.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}public void saveNowState(){StringBuilder sb = new StringBuilder();String[] strs = new String[9];for(int i=0;i<9;i++){strs[i] = farms[i].lastTime == null?"null":sdf.format(farms[i].lastTime);//土地最后一次操作时间if(i!=8)sb.append(farms[i].state+","+strs[i]+";");elsesb.append(farms[i].state+","+strs[i]);}sb.append("&"+fruitNumber);//System.out.println(sb);File record = new File("D://GameRecordAboutSwing/recordFarmGame.txt");try {//清空原有记录FileWriter fileWriter =new FileWriter(record);fileWriter.write("");fileWriter.flush();fileWriter.close();//重新写入文本fos = new FileOutputStream(record);dos = new DataOutputStream(fos);String s = sb.toString();dos.writeBytes(s);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{try {if(fos!=null)fos.close();if(dos!=null)dos.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}@Overridepublic void run() {try {while(true){Thread.sleep(1000);saveNowState();readNowState();}} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}@Overridepublic void mouseEntered(MouseEvent arg0) {// TODO Auto-generated method stub}@Overridepublic void mouseExited(MouseEvent arg0) {// TODO Auto-generated method stub}@Overridepublic void mousePressed(MouseEvent arg0) {// TODO Auto-generated method stub}@Overridepublic void mouseReleased(MouseEvent arg0) {// TODO Auto-generated method stub}public static void main(String[] args) {EventQueue.invokeLater(new Runnable(){public void run(){try{MainFrame frame = new MainFrame();frame.setVisible(true);}catch(Exception e){e.printStackTrace();}}});}}

游戏代码已经贴完了,虽说游戏功能较弱,但是基本的作物定时生长,种植信息的保存和读取,已经实现了。

后续可能会通过微信小程序的形式对该游戏进行完整的制作(如果毕设老师同意该命题的话^_^),敬请期待(#^.^#)。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。