用java编写的小游戏源代码分析
Java语言实现拼图游戏源代码
Java语言实现拼图游戏源代码/** JA V A小游戏-拼图我做的第一个小游戏* Cell类是继承的按钮类,并加上相应图形,形成方格*MyCanvas是一个面板,加载Cell类的对象(方格),是这三个类中的核心*/import java.awt.Rectangle;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import javax.swing.Icon;import javax.swing.ImageIcon;import javax.swing.JOptionPane;import javax.swing.JPanel;import java.awt.BorderLayout;import java.awt.Button;import java.awt.Choice;import java.awt.Color;import java.awt.Container;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import javax.swing.Icon;import javax.swing.ImageIcon;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;import javax.swing.Icon;import javax.swing.JButton;public class MyMainFrame extends JFrame implements ActionListener { MyCanvas myCanvas;JPanel panelNorth,panelPreview;//定义上方的面板,及预览所需的面板Button start,preview,set;//定义开始,预览,设定按钮Container container;//容器,得到内容面板public MyMainFrame() {//初使化container=this.getContentPane();start=new Button("开始");start.addActionListener(this);preview=new Button("预览");preview.addActionListener(this);set = new Button("设置");set.addActionListener(this);panelPreview=new JPanel();panelPreview.setLayout(null);Icon icon=new ImageIcon("pic_"+MyCanvas.pictureID+".jpg");JLabel label=new JLabel(icon);label.setBounds(0,0,300,300);panelPreview.add(label);panelNorth=new JPanel();panelNorth.setBackground(Color.red);panelNorth.add(start);panelNorth.add(preview);panelNorth.add(set);myCanvas=new MyCanvas();container.add(myCanvas,BorderLayout.CENTER);container.add(panelNorth,BorderLayout.NORTH);this.setTitle("拼图小游戏-明");this.setLocation(300,200);this.setSize(308,365);this.setResizable(false);this.setVisible(true);this.setDefaultCloseOperation(3);}public static void main(String[] args) {// TODO 自动生成方法存根new MyMainFrame();}public void actionPerformed(ActionEvent arg0) {//对三个按钮事件的处理// TODO 自动生成方法存根Button button=(Button)arg0.getSource();if(button==start){myCanvas.Start();}else if(button==preview){if(button.getLabel()=="预览"){container.remove(myCanvas);container.add(panelPreview);panelPreview.updateUI();container.repaint();button.setLabel("返回");}else{container.remove(panelPreview);container.add(myCanvas);container.repaint();button.setLabel("预览");}}else if(button==set){//修改所选图片Choice pic = new Choice();pic.add("小猫");pic.add("小猪");pic.add("云");pic.add("QQ");pic.add("卡通");pic.add("花");int i=JOptionPane.showConfirmDialog(this, pic, "选择图片", JOptionPane.OK_CANCEL_OPTION);if(i==JOptionPane.YES_OPTION){MyCanvas.pictureID=pic.getSelectedIndex()+1;myCanvas.reLoadPictrue();Icon icon=new ImageIcon("pic_"+MyCanvas.pictureID+".jpg");JLabel label=new JLabel(icon);label.setBounds(0,0,300,300);panelPreview.removeAll();panelPreview.add(label);panelPreview.repaint();}}}}class MyCanvas extends JPanel implements MouseListener {boolean hasAddActionListener=false;//设置方格的动作监听器的标志位,TRUE为已经添加上动作事件,FALSE是尚未添加动作事件Cell cell[];//定义方格Rectangle cellNull;//定义空方格区域public static int pictureID=1;//当前选择的图片代号public MyCanvas() {this.setLayout(null);this.setSize(400,400);cellNull=new Rectangle(200,200,100,100);//空方格区域在第三行每三列cell=new Cell[9];Icon icon;for (int i = 0; i < 3; i++) {//为9个方格加载图片,并初使化坐标,形成三行三列for(int j=0;j<3;j++){icon=new ImageIcon("pic_"+pictureID+"_"+(i*3+j+1)+".jpg");cell[i*3+j]=new Cell(icon);cell[i*3+j].setLocation(j*100,i*100);this.add(cell[i*3+j]);}}this.remove(cell[8]);//移除最后一个多余的方格}文章转自上海青大实训:。
JAVA小游戏代码(剪刀石头布)
JAVA⼩游戏代码(剪⼑⽯头布) /** 创建⼀个类Game,⽯头,剪⼑,布的游戏。
*/public class Game {/*** @param args*/String[] s ={"⽯头","剪⼑","布"};//获取电脑出拳String getComputer(int i){String computerGuess = s[i];return computerGuess;}//判断⼈出拳是否为⽯头,剪⼑,布boolean isOrder(String guess){boolean b = false;for(int x = 0;x < s.length; x++){if(guess.equals(s[x])){b = true;break;}}return b;}//⽐较void winOrLose(String guess1,String guess2){if(guess1.equals(guess2)){System.out.println("你出:" + guess1 + ",电脑出:" + guess2 + "。
平了");}else if(guess1.equals("⽯头")){if(guess2.equals("剪⼑"))System.out.println("你出:" + guess1 + ",电脑出:" + guess2 + "。
You Win!");}else{System.out.println("你出:" + guess1 + ",电脑出:" + guess2 + "。
You Lose!");}}else if(guess1.equals("剪⼑")){if(guess2.equals("布")){System.out.println("你出:" + guess1 + ",电脑出:" + guess2 + "。
小游戏系统代码
小游戏系统
V1.0
} } public static void main(String[] args) { ZhuCe zhuce = new ZhuCe(); } } 三、 package game; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class DengLu extends JFrame implements ActionListener { JPanel row = new JPanel(); JLabel nameLabel = new JLabel("姓名:",JLabel.RIGHT); JTextField name = new JTextField(30); JLabel passwordLabel = new JLabel("密码:",JLabel.RIGHT); JPasswordField password = new JPasswordField(30); JButton OK = new JButton("确定"); JButton forget = new JButton("忘记密码"); Boolean i = true; public DengLu() { super("登录"); setBounds(450,250,300,120); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(i); setResizable(false); //不许用户改变窗口大小 GridLayout layout = new GridLayout(3,2,50,10); row.setLayout(layout); row.add(nameLabel); row.add(name); row.add(passwordLabel); row.add(password); row.add(OK);
Java游戏源代码
flag=2;
}
}
}
try
{
Thread.sleep(5);
}catch(Exception e){}
repaint();
}
}
public void mouseReleased(MouseEvent arg0)
{
x++;
y++;
if(x>760)
{
flag=1;
}
if(y>540)
{
flag=3;
}
for(int i=0;i<count;i++)
{
if((y==point[i][1])&&x>=point[mport java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyClass {
public static void main(String args[])
{
JFrame w = new JFrame();
//System.out.println("bbb");
}
}
}
if(flag==2)
{
x--;
y--;
if(x<0)
{
flag=3;
}
if(y<0)
{
flag=1;
{
}
public void mouseMoved(MouseEvent arg0)
java小游戏源代码
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猜拳小游戏源代码
第一个文件:public class Computer {String name;int score;public int showfist(){int quan;quan=(int)(Math.random()*10);if(quan<=2){quan=1;}else if(quan<=5){quan=2;}else{quan=3;}switch(quan){case 1:System.out.println(name+"出拳:剪刀");break;case 2:System.out.println(name+"出拳:石头");break;case 3:System.out.println(name+"出拳:布");break;}return quan;}}第二个文件:import java.util.Scanner;public class Game {int count=0;int countP=0;Person person=new Person();Computer computer=new Computer();Scanner input=new Scanner(System.in);public void initial(){System.out.print("请选择你的角色(1.刘备 2.孙权 3.曹操):");int juese=input.nextInt();switch(juese){case 1:="刘备";break;case 2:="孙权";break;case 3:="曹操";break;}System.out.print("请选择对手角色(1.关羽 2.张飞 3.赵云):");int JueSe=input.nextInt();switch(JueSe){case 1:="关羽";break;case 2:="张飞";break;case 3:="赵云";break;}}public void begin(){System.out.print("\n要开始吗? (y/n)");String ans=input.next();if(ans.equals("y")){String answ;do{int a=person.showFist();int b=computer.showfist();if(a==1&&b==3||a==2&&b==1||a==3&&b==2){System.out.println("结果:你赢了!");person.score++;}else if(a==1&&b==1||a==2&&b==2||a==3&&b==3){System.out.println("结果:平局,真衰!嘿嘿,等着瞧吧!");countP++;}else{System.out.println("结果:你输了!");computer.score++;}count++;System.out.print("\n是否开始下一轮? (y/n)");answ=input.next();}while(answ.equals("y"));}}public String calcResult(){String a;if(person.score>computer.score){a="最终结果:恭喜恭喜!你赢了!";}else if(person.score==computer.score){a="最终结果:打成平手,下次再和你一决高下!";}else{a="最终结果:呵呵,你输了!笨笨,下次加油啊!";}return a;}public void showResult(){System.out.println("---------------------------------------------------");System.out.println("\t\t"++" VS"++"\n");System.out.println("对战次数:"+count+"次");System.out.println("平局:"+countP+"次");System.out.println(+"得:"+person.score+"分");System.out.println(+"得:"+computer.score+"分\n");System.out.println(calcResult());System.out.println("---------------------------------------------------");}}第三个文件:import java.util.Scanner;public class Person {String name;int score;Scanner input=new Scanner(System.in);public int showFist(){System.out.print("\n请出拳:1.剪刀2.石头3.布");int quan=input.nextInt();switch(quan){case 1:System.out.println("你出拳:剪刀");break;case 2:System.out.println("你出拳:石头");break;case 3:System.out.println("你出拳:布");break;}return quan;}}第四个文件:public class Test {public static void main(String[]args){Game g=new Game();System.out.println("-----------------欢迎进入游戏世界--------------------\n\n");System.out.println("\t\t******************");System.out.println("\t\t** 猜拳开始 **");System.out.println("\t\t******************\n\n");System.out.println("出拳规则:1.剪刀2.石头3.布");g.initial();g.begin();g.showResult();}}。
JAVA小程序—贪吃蛇源代码
JAVA贪吃蛇源代码SnakeGame。
javapackage SnakeGame;import javax.swing。
*;public class SnakeGame{public static void main( String[]args ){JDialog。
setDefaultLookAndFeelDecorated( true ); GameFrame temp = new GameFrame();}}Snake.javapackage SnakeGame;import java。
awt.*;import java。
util。
*;class Snake extends LinkedList{public int snakeDirection = 2;public int snakeReDirection = 4;public Snake(){this。
add( new Point( 3, 3 ));this。
add(new Point(4, 3 ));this.add( new Point(5,3 ) );this。
add( new Point(6,3 ) );this。
add(new Point(7,3 ));this。
add( new Point( 8,3 ) );this。
add( new Point( 9, 3 ));this。
add( new Point( 10,3 ));}public void changeDirection( Point temp, int direction ) {this。
snakeDirection = direction;switch(direction ){case 1://upthis.snakeReDirection = 3;this。
add( new Point(temp.x,temp.y - 1 ));break;case 2://rightthis。
JAVA小游戏源代码
Java 小游戏
public class GameA_B { public static void main(String[] args) { Scanner reader=new Scanner(System.in); int area; System.out.println("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=reader.nextInt(); switch((area-1)/3) { case 0:System.out.println("You choose easy! ");break; case 1:System.out.println("You choose middle! ");break; case 2:System.out.println("You choose hard! ");break; } System.out.println("Good Luck!"); GameProcess game1=new GameProcess(area); game1.process(); }
Байду номын сангаас
JAVA抓螃蟹小游戏源代码
鼠标点击事件:package muitl;import java.applet.Applet;import java.awt.Cursor;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.io.File;import .MalformedURLException;import javax.swing.JLabel;public class Catcher extends MouseAdapter{public void mousePressed(MouseEvent e){if (e.getButton() != MouseEvent.BUTTON1)return;Object source = e.getSource();//获取事件源if (source instanceof JLabel) { // 如果事件源是标签组件JLabel carb = (JLabel) source; // 强制转换为JLabel标签if (carb.getIcon() != null) {carb.setIcon(Image.crab2); // 为该标签添加螃蟹图片}}//螃蟹叫声try{CommUtil.audioClip = Applet.newAudioClip(new File(Class.class.getResource("/com/insigma/music/cap.au").getPath()).toURI().toURL());} catch (MalformedURLException e1){// TODO Auto-generated catch blocke1.printStackTrace();}CommUtil.audioClip.play();// 播放try{Thread.sleep(1000);} catch (InterruptedException e2){// TODO Auto-generated catch blocke2.printStackTrace();} // 使线程休眠1秒}public void mouseReleased(MouseEvent e) {if (e.getButton() != MouseEvent.BUTTON1)return;Object source = e.getSource(); // 获取事件源,即螃蟹标签if (source instanceof JLabel) { // 如果事件源是标签组件JLabel carb = (JLabel) source; // 强制转换为JLabel标签carb.setIcon(null);// 清除标签中的螃蟹图片}}}图片类:package muitl;import javax.swing.ImageIcon;public class Image{/*** 背景图片*/public static final ImageIcon background = new ImageIcon(Class.class.getResource("/com/insigma/images/background.jpg").getPath());/*** 螃蟹图片*/public static final ImageIcon crab1 = new ImageIcon(Class.class.getResource("/com/insigma/images/crab.png").getPath());public static final ImageIcon crab2 = new ImageIcon(Class.class.getResource("/com/insigma/images/crab2.png").getPath());/*** 鼠标图片*/public static final ImageIcon hand1 = new ImageIcon(Class.class.getResource("/com/insigma/images/hand.jpg").getPath());public static final ImageIcon hand2 = new ImageIcon(Class.class.getResource("/com/insigma/images/hand2.jpg").getPath());}背景音乐:package muitl;import java.applet.Applet;import java.applet.AudioClip;import java.io.File;import .MalformedURLException;public class PlayMusic extends Thread{public void run(){// 以下是编写背景音乐类,并加入到main方法中启动while (true){if (CommUtil.audioClip == null){try{try{CommUtil.audioClip = Applet.newAudioClip(new File(Class.class.getResource("/com/insigma/music/backgroup.au").getPath()).toURI().toURL());} catch (MalformedURLException e1){e1.printStackTrace();}CommUtil.audioClip.play();// 播放CommUtil.audioClip.loop(); // 循环播放} catch (Exception e){e.printStackTrace();}}}}}工具类:package muitl;import java.applet.AudioClip;public class CommUtil{public static AudioClip audioClip = null; }。
推箱子小游戏——代码分析
推箱⼦⼩游戏——代码分析代码组成本项⽬主要分类三个Activity类:MainActivity: 主活动类游戏初始界⾯GameActivity:游戏界⾯GameLevelActivity:关卡选择界⾯三个活动类对应的三个布局:activity_main.xml: 主活动布局。
act_game_activity.xml:游戏活动布局。
act_xuan_guan_qia.xml: 选择关卡布局其他辅助类:GameBitmaps: ⽤来加载图⽚GameLevels:⽤来存放关卡信息和返回关卡信息数组GameState:⽤来使⽤StringBuffer存储当前关卡状态GameView:⾃定义的View类,绘制游戏界⾯,监听touch动作,对⾏为进⾏逻辑判断TCell: ⾃定义的类,⽤于表⽰旗帜位置代码调⽤关系MainActivitypublic class MainActivity extends AppCompatActivity{@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(yout.activity_main);Button btnGameIntro = (Button) findViewById(R.id.btn_game_intro);btnGameIntro.setOnClickListener(new View.OnClickListener(){@Overridepublic void onClick(View view){Intent intent = new Intent(MainActivity.this, GameIntroActivity.class);startActivity(intent);Toast.makeText(MainActivity.this, "按了游戏简介按钮", Toast.LENGTH_SHORT).show();}});Button btnExitGame = (Button) findViewById(R.id.btn_exit);btnExitGame.setOnClickListener(new View.OnClickListener(){@Overridepublic void onClick(View view) {finish();}});Button btnStartGame = (Button) findViewById(R.id.btn_start_game);btnStartGame.setOnClickListener(new View.OnClickListener(){@Overridepublic void onClick(View view) {Intent intent = new Intent(MainActivity.this, GameLevelActivity.class);startActivity(intent);}});}}在主活动类的onCreate⽅法中构建其布局layout⽂件,在通过三个Button类和findViewById⽅法与布局中三个Button 绑定,并对三个Button建⽴Click监听器。
java小游戏连连看源代码
Java小游戏——连连看源码连连看java源代码import javax.swing.*;import java.awt.*;import java.awt.event.*;public class lianliankan implements ActionListener{JFrame mainFrame; //主面板Container thisContainer;JPanel centerPanel,southPanel,northPanel; //子面板JButton diamondsButton[][] = new JButton[6][5];//游戏按钮数组JButton exitButton,resetButton,newlyButton; //退出,重列,重新开始按钮JLabel fractionLable=new JLabel("0"); //分数标签JButton firstButton,secondButton; //分别记录两次被选中的按钮int grid[][] = new int[8][7];//储存游戏按钮位置static boolean pressInformation=false; //判断是否有按钮被选中int x0=0,y0=0,x=0,y=0,fristMsg=0,secondMsg=0,validateLV; //游戏按钮的位置坐标int i,j,k,n;//消除方法控制public void init(){mainFrame=new JFrame("JKJ连连看");thisContainer = mainFrame.getContentPane();thisContainer.setLayout(new BorderLayout());centerPanel=new JPanel();southPanel=new JPanel();northPanel=new JPanel();thisContainer.add(centerPanel,"Center");thisContainer.add(southPanel,"South");thisContainer.add(northPanel,"North");centerPanel.setLayout(new GridLayout(6,5));for(int cols = 0;cols < 6;cols++){for(int rows = 0;rows < 5;rows++ ){diamondsButton[cols][rows]=new JButton(String.valueOf(grid[cols+1][rows+1])); diamondsButton[cols][rows].addActionListener(this);centerPanel.add(diamondsButton[cols][rows]);}}exitButton=new JButton("退出");exitButton.addActionListener(this);resetButton=new JButton("重列");resetButton.addActionListener(this);newlyButton=new JButton("再来一局");newlyButton.addActionListener(this);southPanel.add(exitButton);southPanel.add(resetButton);southPanel.add(newlyButton);fractionLable.setText(String.valueOf(Integer.parseInt(fractionLable.getText()))); northPanel.add(fractionLable);mainFrame.setBounds(280,100,500,450);mainFrame.setVisible(true);}public void randomBuild() {int randoms,cols,rows;for(int twins=1;twins<=15;twins++) {randoms=(int)(Math.random()*25+1);for(int alike=1;alike<=2;alike++) {cols=(int)(Math.random()*6+1);rows=(int)(Math.random()*5+1);while(grid[cols][rows]!=0) {cols=(int)(Math.random()*6+1);rows=(int)(Math.random()*5+1);}this.grid[cols][rows]=randoms;}}}public void fraction(){fractionLable.setText(String.valueOf(Integer.parseInt(fractionLable.getText())+100)); }public void reload() {int save[] = new int[30];int n=0,cols,rows;int grid[][]= new int[8][7];for(int i=0;i<=6;i++) {for(int j=0;j<=5;j++) {if(this.grid[i][j]!=0) {save[n]=this.grid[i][j];n++;}}}n=n-1;this.grid=grid;while(n>=0) {cols=(int)(Math.random()*6+1);rows=(int)(Math.random()*5+1);while(grid[cols][rows]!=0) {cols=(int)(Math.random()*6+1);rows=(int)(Math.random()*5+1);}this.grid[cols][rows]=save[n];n--;}mainFrame.setVisible(false);pressInformation=false; //这里一定要将按钮点击信息归为初始init();for(int i = 0;i < 6;i++){for(int j = 0;j < 5;j++ ){if(grid[i+1][j+1]==0)diamondsButton[i][j].setVisible(false);}}}public void estimateEven(int placeX,int placeY,JButton bz) {if(pressInformation==false) {x=placeX;y=placeY;secondMsg=grid[x][y];secondButton=bz;pressInformation=true;}else {x0=x;y0=y;fristMsg=secondMsg;firstButton=secondButton;x=placeX;y=placeY;secondMsg=grid[x][y];secondButton=bz;if(fristMsg==secondMsg。
Java猜拳小游戏程序设计实验报告
Java猜拳小游戏程序设计实验报告第一篇:Java猜拳小游戏程序设计实验报告Java程序设计实验报告班级:学号:姓名:实验题目:猜拳小游戏实验要求:用java编写一个人机对战的猜拳小游戏。
人选择性出拳,电脑随机出拳,判断输赢,记录输赢情况。
有简单的操作界面。
实验内容:1、问题分析过程:(1)首先分析猜拳游戏本身的玩法:人选择性出拳,电脑随机出拳,判断输赢,记录输赢情况。
(2)用面向对象的思想来分析:在游戏过程中有几个对象组成人电脑游戏规则抽象出3个类:Person、Computer、Game Person类有哪些属性和行为呢?属性:名字name,输赢次数(比分)score 行为:出拳ShowFirst()选择性Computer类有哪些属性和行为呢?属性:名字name,输赢次数(比分)score 行为:出拳showFist()随机Game类有哪些属性和行为呢?属性:游戏的双方(person、computer)、对战局数count 行为:产生角色initial()、游戏规则startGame()、显示比赛结果showResult()、统计比赛结果calcResul()2、主要实现代码:import java.util.*;public class StartGame { public static void main(String[]args){Game start = new Game();//实例化游戏类start.initial();//调用初始化方法start.startGame();//调用游戏开始方法start.showResult();//调用游戏结果显示方法} } import java.util.*;public class Person { String name;//名字属性int score;//积分属性//出拳方法public int showFist(){System.out.print(“n请出拳:1.剪刀2.石头3.布(输入相应数字):”);Scanner input = new Scanner(System.in);int num = input.nextInt();String fist = “";//保存出拳switch(num){ case 1:fist = ”剪刀“;break;case 2:fist = ”石头“;break;case 3:fist = ”布“;break;}System.out.println(name + ”出拳:“ + fist);return num;} } import java.util.*;public class Game { //Person person;//甲方//Computer computer;//乙方int count;//对战次数Person person = new Person();//实例化用户类Computer computer = new Computer();//实例化计算机类//初始化方法public int initial(){count = 0;return count;} //游戏开始方法public void startGame(){//显示游戏开始界面System.out.println(”---------------欢迎进入游戏世System.out.println(“tt******************************”);System.out.println(“tt**^_^ 猜拳,Start ^_^**”);System.out.println(“tt*****************************”);界--------------n“);System.out.println(”nn出拳规则:1.剪刀 2.石头 3.布“);//选择计算机角色System.out.print(”请选择对方角色:1.刘备2.孙权3.曹操:“);Scanner input = new Scanner(System.in);int num = input.nextInt();switch(num){ case 1: = ”刘备“;break;case 2: = ”孙权“;break;case 3: } = ”曹操“;break;//输入用户角色名System.out.print(”请输入你的姓名:“); = input.next();//显示对战双方System.out.print( + ” VS “ + + ” 对战n“);//开始游戏System.out.print(”n要开始吗?(y/n)“);String con = input.next();int perFist;//用户出的拳 int compFist;//计算机出的拳if(con.equals(”y“)){//判断是否开始String answer = ”y“;while(”y“.equals(answer)){//循环条件是是否开始下一轮//出拳perFist = person.showFist();//调用用户出拳方法compFist = computer.showFist();//调用计算机出拳方法//裁决if((perFist == 1 && compFist == 1)||(perFist == 2 && compFist == 2)||(perFist == 3 && compFist == 3)){Syst em.out.println(”结果:和局,真衰!n“);//平局}else if((perFist == 1 && compFist == 3)||(perFist == 2 && compFist == 1)||(perFist == 3 && compFist == 2)){System.out.println(”结果:恭喜, 你赢了!n“);//用户赢person.score++;//累计用户积分}else{}} System.out.println(”结果说:^_^,你输了,真笨!n“);//计算机赢computer.score++;//累计计算机积分 } count++;//累计对战次数System.out.print(”是否开始下一轮(y/n):“);answer = input.next();}//比较得分情况的方法public void showResult(){ System.out.println(”-----------------------“);System.out.println( + ” VS “ + person.na me);System.out.println(”对战次数:“ + count);System.out.println(”n姓名t得分n“ + + ”t“ + person.score+ ”n“ + + ”t“ + computer.score + ”n“);//比较积分if(computer.score == person.score){System.out.println(”结果:打成平手,下次再和你一分高下!“);}else if(computer.score < person.score){System.out.println(”结果:你果然是高手,“ + + ”佩服!“);}else{System.out.println(”结果:呵呵,笨笨,下次加油哦!“);}System.out.println(”-----------------------“);} } public class Computer {String name;//名字属性 int score;//积分属性 //出拳方法public int showFist(){ int num =(int)(Math.random()*3)+ 1;String fist = ”“;switch(num){ case 1:fist = ”剪刀“;break;case 2:fist = ”石头“;break;case 3:fist = ”布“;break;}System.out.println(name + ”出拳:" + fist);return num;} } 运行界面:3、实验心得体会:从本次课程设计的完成中,我发现我有很多不足的地方,最突出的是所掌握的知识太少,学到的知识应用不到实践中。
2020年java小游戏源代码
System. out .println(
"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:"
{
t =random .nextInt(
arrcount );
//System.out.println(t);
sysNum [ i ]= base [ t ];
System. out .println(
base [ t ]);
delarr( t );
}
}
void delarr( int t)
{
f or ( int j=t;j< arrcount -1;j++)
{ base [i]=i; //System.out.println(base[i]);
} }
void process()
{
r and();
while ( right != area ) {
s canf();
c ompare();
p rint();
c heck();
}
}
void rand()
{
f or ( i =0; i < area ; i ++)
基于java的2048小游戏的设计文档
目录一、实现方案 (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实现贪吃蛇游戏代码(附完整源码)先给⼤家分享源码,喜欢的朋友。
游戏界⾯GUI界⾯java实现贪吃蛇游戏需要创建⼀个桌⾯窗⼝出来,此时就需要使⽤java中的swing控件创建⼀个新窗⼝JFrame frame = new JFrame("贪吃蛇游戏");//设置⼤⼩frame.setBounds(10, 10, 900, 720);向窗⼝中添加控件可以直接⽤add⽅法往窗⼝中添加控件这⾥我创建GamePanel类继承⾃Panel,最后使⽤add⽅法添加GamePanel加载图⽚图⽚加载之后可以添加到窗⼝上public static URL bodyUrl = GetImage.class.getResource("/picture/body.png");public static ImageIcon body = new ImageIcon(bodyUrl);逻辑实现//每次刷新页⾯需要进⾏的操作@Overridepublic void actionPerformed(ActionEvent e) {//当游戏处于开始状态且游戏没有失败时if(gameStart && !isFail) {//蛇头所在的位置就是下⼀次蛇⾝体的位置bodyX[++bodyIndexRight] = headX;bodyY[bodyIndexRight] = headY;//bodyIndexLeft++;//长度到达数组的尾部if(bodyIndexRight==480) {for(int i=bodyIndexLeft, j=0; i<=bodyIndexRight; i++,j++) {bodyX[j]=bodyX[i];bodyY[j]=bodyY[i];}bodyIndexLeft=0;bodyIndexRight=length-1;}//更新头部位置if(fdirection==1) {//头部⽅向为上,将蛇头向上移动⼀个单位headY-=25;}else if(fdirection==2) {//头部⽅向为下,将蛇头向下移动⼀个单位headY+=25;}else if(fdirection==3) {//头部⽅向为左,将蛇头向左移动⼀个单位headX-=25;}else if(fdirection==4) {//头部⽅向为右,将蛇头向右移动⼀个单位headX+=25;}//当X坐标与Y坐标到达极限的时候,从另⼀端出来if(headX<25)headX = 850;if(headX>850)headX = 25;if(headY<75)headY = 650;if(headY>650)headY = 75;//当头部坐标和⾷物坐标重合时if(headX==foodX && headY==foodY){length++;score+=10;//重新⽣成⾷物,判断⾷物坐标和蛇⾝坐标是否重合,效率较慢while(true) {foodX = 25 + 25* random.nextInt(34);foodY = 75 + 25* random.nextInt(24);//判断⾷物是否和头部⾝体重合boolean isRepeat = false;//和头部重合if(foodX == headX && foodY == headY)isRepeat = true;//和⾝体重合for(int i=bodyIndexLeft; i<=bodyIndexRight; i++) {if(foodX == bodyX[i] && foodY == bodyY[i]){isRepeat = true;}}//当不重复的时候,⾷物⽣成成功,跳出循环if(isRepeat==false)break;}}else bodyIndexLeft++;//判断头部是否和⾝体重合for(int i=bodyIndexLeft; i<=bodyIndexRight;i++) {if(headX==bodyX[i] && headY==bodyY[i]){//游戏失败isFail = true;break;}}repaint();}timer.start();}键盘监听实现KeyListener接⼝,重写KeyPressed⽅法,在其中写当键盘按下时所对应的操作。
新人Eclipse编写的Java小游戏
Eclipse编写的Java小游戏初学java时编写的简单小游戏,非界面版,纯java基础组成,新人都能看得懂可以做的来,主要是其中的逻辑思想。
使用eclipse编程,直接建立一个java 复制代码进去就可以了。
希望对大家学习java编程有点帮助游戏一:随即取5个数排列,要求猜出这5个数package day;import java.util.Random;import java.util.Scanner;import java.util.regex.Matcher;import java.util.regex.Pattern;public class Game {public static void main(String[] args) {Random r = new Random();int a1 = r.nextInt(10);int a2 = r.nextInt(10);int a3 = r.nextInt(10);int a4 = r.nextInt(10);int a5 = r.nextInt(10);System.out.println("游戏规则:随即取5个数,请输入5个数,数字顺序要求一致,会告诉你答对几个,看你能在几次猜对");Scanner scan = new Scanner(System.in);for(int i=1;;i++){int c=0;System.out.println("请输入5个数:");String dir = scan.nextLine();Pattern pattern = pile("^[0-9]{5}$");Matcher matcher = pattern.matcher(dir);if(matcher.find()){int b1 = Integer.parseInt(dir.substring(0,1));int b2 = Integer.parseInt(dir.substring(1,2));int b3 = Integer.parseInt(dir.substring(2,3));int b4 = Integer.parseInt(dir.substring(3,4));int b5 = Integer.parseInt(dir.substring(4,5));if(a1==b1){c++;}if(a2==b2){c++;}if(a3==b3){c++;}if(a4==b4){c++;}if(a5==b5){c++;}if(c==5){if(i<=5){System.out.println("恭喜你猜对了,猜对次数"+i+",妖才级别");break;}else if(i<=15){System.out.println("恭喜你猜对了,猜对次数"+i+",天才级别");break;}else if(i<=25){System.out.println("恭喜你猜对了,猜对次数"+i+",聪明人级别");break;}else if(i<=40){System.out.println("恭喜你猜对了,猜对次数"+i+",常人级别");break;}else if(i<=60){System.out.println("恭喜你猜对了,猜对次数"+i+",迟钝级别");break;}else{System.out.println("恭喜你猜对了,猜对次数"+i+",傻瓜级别");break;}}else{System.out.println("猜对了"+c+"个,请继续努力");}}else{System.out.println("只能输入5位数字,请重试");}}}}游戏二:package day;import java.util.Arrays;import java.util.Random;import java.util.Scanner;import java.util.regex.Matcher;import java.util.regex.Pattern;public class Game1 {public static void main(String[] args) {String[] str = {"鼠","牛","虎","兔","龙","蛇","马","羊","猴","鸡","狗","猪"};System.out.println("玩个小游戏,现在你手上有100分,从十二生肖中选择押注,只能压一个数目不限,随机选取5次");System.out.println("中1个翻1倍,2个翻3倍,3个翻6倍,4个翻10倍,5个翻15倍(输入如:龙5)。
java简易小游戏制作代码
java简易⼩游戏制作代码java简易⼩游戏制作游戏思路:设置⼈物移动,游戏规则,积分系统,随机移动的怪物,游戏胜负判定,定时器。
游戏内容部分package 代码部分;import javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.util.Random;public class TestGamePanel extends JPanel implements KeyListener, ActionListener {//初始化⼈物坐标int p1X;int p1Y;int p2X;int p2Y;boolean isStart = false; //游戏是否开始boolean p1isFail = false; //游戏是否失败boolean p2isFail = false;String fx1; //左:L,右:R,上:U,下:DString fx2;Timer timer = new Timer(50,this);//定时器//积分int p1score = 0;int p2score = 0;//苹果int AppleX;int AppleY;//怪物int monster1X;int monster1Y;int monster2X;int monster2Y;int monster3X;int monster3Y;int monster4X;int monster4Y;int monster5X;int monster5Y;//随机积分Random random = new Random();public TestGamePanel() {init();this.setFocusable(true);this.addKeyListener(this);timer.start();}//初始化public void init() {p1X = 25;p1Y = 150;p2X = 700;p2Y = 550;fx1 = "L";fx2 = "R";monster1X = 25*random.nextInt(28);monster1Y = 100 + 25*random.nextInt(18);monster2X = 25*random.nextInt(28);monster2Y = 100 + 25*random.nextInt(18);monster3X = 25*random.nextInt(28);monster3Y = 100 + 25*random.nextInt(18);monster4X = 25*random.nextInt(28);monster4Y = 100 + 25*random.nextInt(18);monster5X = 25*random.nextInt(28);monster5Y = 100 + 25*random.nextInt(18);AppleX = 25*random.nextInt(28);AppleY = 100 + 25*random.nextInt(18);add(kaishi);add(chongkai);guize.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {new TestGameRule();}});}//游戏功能按钮JButton kaishi = new JButton("开始");JButton chongkai = new JButton("重新开始");JButton guize = new JButton("游戏规则");//画板@Overrideprotected void paintComponent(Graphics g) {super.paintComponent(g);TestGameData.header.paintIcon(this,g,0,0);g.setColor(Color.CYAN);g.fillRect(0,100,780,520);//画⼈物TestGameData.p1player1.paintIcon(this,g,p1X,p1Y);TestGameData.p2player1.paintIcon(this,g,p2X,p2Y);//画得分g.setFont(new Font("华⽂彩云",Font.BOLD,18)); //设置字体g.setColor(Color.RED);g.drawString("玩家1:" + p1score,20,20 );g.drawString("玩家2:" + p2score,680,20);//画苹果TestGameData.apple.paintIcon(this,g,AppleX,AppleY);//画静态怪物TestGameData.monster.paintIcon(this,g,monster1X,monster1Y);TestGameData.monster.paintIcon(this,g,monster2X,monster2Y);TestGameData.monster.paintIcon(this,g,monster3X,monster3Y);TestGameData.monster.paintIcon(this,g,monster4X,monster4Y);TestGameData.monster.paintIcon(this,g,monster5X,monster5Y);//游戏提⽰,是否开始if(!isStart) {g.setColor(Color.BLACK);g.setFont(new Font("华⽂彩云",Font.BOLD,30));g.drawString("请点击开始游戏",300,300);}//游戏结束提⽰,是否重新开始if(p2isFail || p1score == 15) {g.setColor(Color.RED);g.setFont(new Font("华⽂彩云",Font.BOLD,30));g.drawString("玩家⼀获胜,请点击重新开始游戏",200,300);if(p1isFail || p2score == 15) {g.setColor(Color.RED);g.setFont(new Font("华⽂彩云",Font.BOLD,30));g.drawString("玩家⼆获胜,请点击重新开始游戏",200,300); }}//键盘监听事件@Overridepublic void keyPressed(KeyEvent e) {//控制⼈物⾛动//玩家1if(isStart == true && (p1isFail == false && p2isFail == false)) { if(e.getKeyCode() == KeyEvent.VK_D) {fx1 = "R";p1X += 25;if(p1X >= 750) {p1X = 750;}}else if(e.getKeyCode() == KeyEvent.VK_A) {fx1 = "L";p1X -= 25;if(p1X <= 0) {p1X = 0;}}else if(e.getKeyCode() == KeyEvent.VK_W) {fx1 = "U";p1Y -= 25;if(p1Y <= 100) {p1Y = 100;}}else if(e.getKeyCode() == KeyEvent.VK_S) {fx1 = "D";p1Y += 25;if(p1Y >= 600) {p1Y = 600;}}//玩家2if(e.getKeyCode() == KeyEvent.VK_RIGHT) {fx2 = "R";p2X += 25;if(p2X >= 750) {p2X = 750;}}else if(e.getKeyCode() == KeyEvent.VK_LEFT) {fx2 = "L";p2X -= 25;if(p2X <= 0) {p2X = 0;}}else if(e.getKeyCode() == KeyEvent.VK_UP) {fx2 = "U";p2Y -= 25;if(p2Y <= 100) {p2Y = 100;}}else if(e.getKeyCode() == KeyEvent.VK_DOWN) {fx2 = "D";p2Y += 25;if(p2Y >= 600) {p2Y = 600;}}}repaint();}@Overridepublic void actionPerformed(ActionEvent e) {kaishi.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {isStart = true;}});chongkai.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {if(p1isFail) { p1isFail = !p1isFail; init(); }if(p2isFail) { p2isFail = !p2isFail; init(); }}});add(kaishi);add(chongkai);add(guize);if(isStart == true && (p1isFail == false && p2isFail == false)) { //让⼈动起来if(fx1.equals("R")) {p1X += 25;if(p1X >= 750) { p1X = 750; }}if(fx1.equals("L")) {p1X -= 25;if(p1X <= 0) { p1X = 0; }}if(fx1.equals("U")) {p1Y -= 25;if(p1Y <= 100) { p1Y = 100; }}if(fx1.equals("D")) {p1Y += 25;if(p1Y >= 600) { p1Y = 600; }}if(fx2.equals("R")) {p2X += 25;if(p2X >= 750) { p2X = 750; }}if(fx2.equals("L")) {p2X -= 25;if(p2X <= 0) { p2X = 0; }}if(fx2.equals("U")) {p2Y -= 25;if(p2Y <= 100) { p2Y = 100; }}if(fx2.equals("D")) {p2Y += 25;if(p2Y >= 600) { p2Y = 600; }}//让怪物动起来//怪物1int i = random.nextInt(4) + 1;if(i == 1) {monster1X += 5;if(monster1X >= 750) {monster1X = 750;}}if(i == 2) {monster1X -= 5;if(monster1X <= 0) {monster1X = 0;}}if(i == 3) {monster1Y += 5;if(monster1Y >= 600) {monster1Y = 600;}if(i == 4) {monster1Y -= 5;if(monster1Y <= 100) {monster1Y = 100;}}//怪物2int j = random.nextInt(4) + 1;if(j == 1) {monster2X += 5;if(monster2X >= 750) {monster2X = 750;}}if(j == 2) {monster2X -= 5;if(monster2X <= 0) {monster2X = 0;}}if(j == 3) {monster2Y += 5;if(monster2Y >= 600) {monster2Y = 600;}}if(j == 4) {monster2Y -= 5;if(monster2Y <= 100) {monster2Y = 100;}}//怪物3int k = random.nextInt(4) + 1;if(k == 1) {monster3X += 5;if(monster3X >= 750) {monster3X = 750;}}if(k == 2) {monster3X -= 5;if(monster3X <= 0) {monster3X = 0;}}if(k == 3) {monster3Y += 5;if(monster3Y >= 600) {monster3Y = 600;}}if(k == 4) {monster3Y -= 5;if(monster3Y <= 100) {monster3Y = 100;}}//怪物4int n= random.nextInt(4) + 1;if(n == 1) {monster4X += 5;if(monster4X >= 750) {monster4X = 750;}}if(n == 2) {monster4X -= 5;if(monster4X <= 0) {monster4X = 0;}}if(n == 3) {monster4Y += 5;if(monster4Y >= 600) {monster4Y = 600;}}if(n == 4) {monster4Y -= 5;if(monster4Y <= 100) {monster4Y = 100;}}//怪物5int m = random.nextInt(4) + 1;if(m == 1) {monster5X += 5;if(monster5X >= 750) {monster5X = 750;}}if(m == 2) {monster5X -= 5;if(monster5X <= 0) {monster5X = 0;}}if(m == 3) {monster5Y += 5;if(monster5Y >= 600) {monster5Y = 600;}}if(m == 4) {monster5Y -= 5;if(monster5Y <= 100) {monster5Y = 100;}}//如果有玩家吃到⾷物if(p1X == AppleX && p1Y == AppleY) {p1score++;AppleX = 25*random.nextInt(28);AppleY = 100 + 25*random.nextInt(18);} else if(p2X == AppleX && p2Y == AppleY) {p2score++;AppleX = 25*random.nextInt(28);AppleY = 100 + 25*random.nextInt(18);}//如果有玩家碰到怪物,判定死亡,游戏结束后续有修改,暂⽤ //怪物1死亡if(p1X >= monster1X -25 && p1X <= monster1X +25) {if(p1Y == monster1Y) { p1isFail = !p1isFail; p1score = p2score = 0;} }if(p1Y >= monster1Y -25 && p1Y <= monster1Y +25) {if(p1X == monster1X) { p1isFail = !p1isFail; p1score = p2score = 0;} }if(p2X >= monster1X -25 && p2X <= monster1X +25) {if(p2Y == monster1Y) { p2isFail = !p2isFail; p1score = p2score = 0;} }if(p2Y >= monster1Y -25 && p2Y <= monster1Y +25) {if(p2X == monster1X) { p2isFail = !p2isFail; p1score = p2score = 0;} }//怪物2死亡if(p1X >= monster2X -25 && p1X <= monster2X +25) {if(p1Y == monster2Y) { p1isFail = !p1isFail; p1score = p2score = 0;} }if(p1Y >= monster2Y -25 && p1Y <= monster2Y +25) {if(p1X == monster2X) { p1isFail = !p1isFail; p1score = p2score = 0;} }if(p2X >= monster2X -25 && p2X <= monster2X +25) {if(p2Y == monster2Y) { p2isFail = !p2isFail; p1score = p2score = 0;} }if(p2Y >= monster2Y -25 && p2Y <= monster2Y +25) {if(p2X == monster2X) { p2isFail = !p2isFail; p1score = p2score = 0;} }//怪物3死亡if(p1X >= monster3X -25 && p1X <= monster3X +25) {if(p1Y == monster3Y) { p1isFail = !p1isFail; p1score = p2score = 0;} }if(p1Y >= monster3Y -25 && p1Y <= monster3Y +25) {if(p1X == monster3X) { p1isFail = !p1isFail; p1score = p2score = 0;} }if(p2X >= monster3X -25 && p2X <= monster3X +25) {if(p2Y == monster3Y) { p2isFail = !p2isFail; p1score = p2score = 0;}if(p2Y >= monster3Y -25 && p2Y <= monster3Y +25) {if(p2X == monster3X) { p2isFail = !p2isFail; p1score = p2score = 0;}}//怪物4死亡if(p1X >= monster4X -25 && p1X <= monster4X +25) {if(p1Y == monster4Y) { p1isFail = !p1isFail; p1score = p2score = 0;}}if(p1Y >= monster4Y -25 && p1Y <= monster4Y +25) {if(p1X == monster1X) { p1isFail = !p1isFail; p1score = p2score = 0;}}if(p2X >= monster4X -25 && p2X <= monster4X +25) {if(p2Y == monster4Y) { p2isFail = !p2isFail; p1score = p2score = 0;}}if(p2Y >= monster4Y -25 && p2Y <= monster4Y +25) {if(p2X == monster4X) { p2isFail = !p2isFail; p1score = p2score = 0;}}//怪物5死亡if(p1X >= monster5X -25 && p1X <= monster5X +25) {if(p1Y == monster5Y) { p1isFail = !p1isFail; p1score = p2score = 0;}}if(p1Y >= monster5Y -25 && p1Y <= monster5Y +25) {if(p1X == monster5X) { p1isFail = !p1isFail; p1score = p2score = 0;}}if(p2X >= monster5X -25 && p2X <= monster5X +25) {if(p2Y == monster5Y) { p2isFail = !p2isFail; p1score = p2score = 0;}}if(p2Y >= monster5Y -25 && p2Y <= monster5Y+25) {if(p2X == monster5X) { p2isFail = !p2isFail; p1score = p2score = 0;}}//如果有玩家达到指定积分,判定获胜,游戏结束if(p1score == 15) { p2isFail = !p2isFail; }if(p2score == 15) { p1isFail = !p1isFail; }repaint();}timer.start();}@Overridepublic void keyTyped(KeyEvent e) {}@Overridepublic void keyReleased(KeyEvent e) {}}游戏规则(使⽤弹窗)部分package 代码部分;import javax.swing.*;import java.awt.*;public class TestGameRule extends JDialog {private int num = 1;public TestGameRule() {TextArea textArea = new TextArea(20,10);textArea.setText("游戏中有五个怪物随机移动,碰到怪物算死亡\\\n游戏中有随机出现的苹果,碰到⼀个苹果加⼀分,\\\n先达到⼗五分或者对⼿死亡算游戏胜利!"); JScrollPane jScrollPane = new JScrollPane(textArea);this.add(jScrollPane);this.setBounds(200,200,400,400);this.setVisible(true);textArea.setEditable(false);setResizable(false);textArea.setBackground(Color.PINK);}}图⽚素材package 代码部分;import javax.swing.*;import .URL;public class TestGameData {public static URL headerurl = TestGameData.class.getResource("/图⽚素材/header.jpg");public static URL p1player1url = TestGameData.class.getResource("/图⽚素材/1.jpg");public static URL p2player2url = TestGameData.class.getResource("/图⽚素材/2.jpg");public static URL appleurl = TestGameData.class.getResource("/图⽚素材/apple.jpg");public static URL monsterurl = TestGameData.class.getResource("/图⽚素材/monster.jpg");public static ImageIcon p1player1 = new ImageIcon(p1player1url);public static ImageIcon p2player1 = new ImageIcon(p2player2url);public static ImageIcon header = new ImageIcon(headerurl);public static ImageIcon apple = new ImageIcon(appleurl);public static ImageIcon monster = new ImageIcon(monsterurl);}主函数package 代码部分;import javax.swing.*;public class TestStartGame {public static void main(String[] args) {//制作窗⼝JFrame jFrame = new JFrame("2D对战⼩游戏");jFrame.setBounds(10,10,790,660);jFrame.setResizable(false);jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//添加游戏⾯板jFrame.add(new TestGamePanel());//设置可见jFrame.setVisible(true);}}实现效果到此这篇关于java简易⼩游戏制作代码的⽂章就介绍到这了,更多相关java简易⼩游戏内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!。
java推箱子游戏源代码(含推箱子的判断)
第一个Java文件:package xiaoA;import java.awt.Color;import java.awt.HeadlessException;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import javax.swing.ImageIcon;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JPanel;public class GameFrame extends JFrame {JPanel zhuobu = new JPanel();//工人JLabel worker = null;//箱子JLabel box = null;//目的地JLabel goal = null;JLabel[] walls = null;public static final int SPEED = 12;//设置图片大小int imgSize = 48;public void setImgSize(int imgSize){this.imgSize = imgSize;}public GameFrame(String title) throws HeadlessException { super(title);//构造方法中调用本类的其它方法this.initContentPane();this.addKeyListener(new KeyListener() {//键盘按下事件public void keyPressed(KeyEvent e) {//[2.5] 使工人可以移动int xSpeed = 0, ySpeed = 0;switch (e.getKeyCode()) {case KeyEvent.VK_LEFT :xSpeed = -SPEED;worker.setIcon(new ImageIcon("image/workerUp.gif"));break;case KeyEvent.VK_RIGHT :xSpeed = SPEED;worker.setIcon(new ImageIcon("image/workerUp.gif"));break;case KeyEvent.VK_UP :ySpeed = -SPEED;worker.setIcon(new ImageIcon("image/workerUp.gif"));break;case KeyEvent.VK_DOWN :ySpeed = SPEED;worker.setIcon(new ImageIcon("image/workerUp.gif"));break;default:return;}worker.setBounds(worker.getX() + xSpeed, worker.getY() + ySpeed, worker.getWidth(), worker.getHeight());//[2.7] 判断工人是否撞到墙壁for (int i = 0; i < walls.length; i++) {if(worker.getBounds().intersects(walls[i].getBounds())) {worker.setBounds(worker.getX() - xSpeed, worker.getY() - ySpeed, worker.getWidth(), worker.getHeight());}}//[3.2] 使工人可以推动箱子if (worker.getBounds().intersects(box.getBounds())) {box.setBounds(box.getX() + xSpeed, box.getY() + ySpeed, box.getWidth(), box.getHeight());//[3.3] 判断箱子是否撞到墙壁for (int i = 0; i < walls.length; i++) {if (box.getBounds().intersects(walls[i].getBounds())) {worker.setBounds(worker.getX() - xSpeed, worker.getY() - ySpeed, worker.getWidth(), worker.getHeight());box.setBounds(box.getX() - xSpeed, box.getY() - ySpeed, box.getWidth(), box.getHeight());}}//[3.4] 判断是否胜利if (box.getX()==goal.getX() && box.getY()==goal.getY()) { JOptionPane.showMessageDialog(null, "您赢啦!");}}}public void keyReleased(KeyEvent e) {}public void keyTyped(KeyEvent e) {}});}/***设置内容面板*/public void initContentPane() {zhuobu.setBackground(Color.red);zhuobu.setLayout(null);//调用父类的属性和方法super.setContentPane(zhuobu);}/***把某个图片以组件的方式加入窗体*@param imgPath图片路径*@param x x*@param y y*@param width宽度*@param height高度*@return添加完的组件*/public void addComponent(int tag, String imgPath, int x, int y) { ImageIcon img = new ImageIcon(imgPath);//创建JLabel并把ImageIcon通过构造方法传参传入//把食物放到盘子里JLabel componet = new JLabel(img);//设置盘子在桌布上的位置和大小componet.setBounds(x, y, imgSize, imgSize);//把盘子放到桌布上zhuobu.add(componet);switch (tag) {case 1:box = componet;break;case 2:goal = componet;break;case 3:worker = componet;break;}}public void addWall(String imgPath, int[][] loactions) { ImageIcon wallImg = new ImageIcon(imgPath);walls = new JLabel[66 + loactions.length];for (int i = 0; i < walls.length; i++) {//创建没每一个围墙,他们使用的是同一个图片walls[i] = new JLabel(wallImg);}for (int i = 0; i < walls.length; i++) {//创建没每一个围墙,他们使用的是同一个图片walls[i] = new JLabel(wallImg);}int index = 0;/*分别设置各个图片位置*/for (int i = 0; i < 14; i++) {//左边墙walls[index].setBounds(0, i * imgSize, imgSize, imgSize);zhuobu.add(walls[index]);index++;//右边墙walls[index].setBounds(20 * imgSize, i * imgSize, imgSize, imgSize);zhuobu.add(walls[index]);index++;}for (int i = 0; i < 19; i++) {//上边墙walls[index].setBounds((i + 1) * imgSize, 0, imgSize, imgSize);zhuobu.add(walls[index]);index++;//下边墙walls[index].setBounds((i + 1) * imgSize, 13 * imgSize, imgSize, imgSize);zhuobu.add(walls[index]);index++;}//添加中间障碍耦合解耦for (int i = 0; i < loactions.length; i++) {walls[index].setBounds(loactions[i][0]* imgSize, loactions[i][1]* imgSize, imgSize, imgSize);zhuobu.add(walls[index]);index++;}}}第二个Java文件:public class Run {public static void main(String[] args) {GameFrame gameFrame = new GameFrame("推箱子游戏…");//设置大小gameFrame.setBounds(100, 50, 21 * 48 + 5, 14 * 48 + 25);//窗体大小不可变gameFrame.setResizable(false);gameFrame.setImgSize(48);gameFrame.addComponent(3, "workerUp.png", 400, 100);gameFrame.addComponent(1, "box.png", 160, 60);gameFrame.addComponent(2, "goal.png", 80, 520);int[][] wallLocations ={{4, 5},{5, 5},{6, 5},{7, 5},{8, 5},{9, 5},{10, 5},{6, 8},{7, 8},{8, 8},{9, 8},{10, 8},{11, 5}};gameFrame.addWall("wall.png", wallLocations);gameFrame.setVisible(true);}}。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
}
void begin(){
if (snakeModel == null || !snakeModel.running){
snakeModel = new SnakeModel(this,
canvasWidth/nodeWidth,
case KeyEvent.VK_LEFT:
snakeModel.changeDirection(SnakeModel.LEFT);
break;
case KeyEvent.VK_RIGHT:
snakeModel.changeDirection(SnakeModel.RIGHT);
paintCanvas.setSize(canvasWidth+1,canvasHeight+1);
paintCanvas.addKeyListener(this);
cp.add(paintCanvas, BorderLayout.CENTER);
JPanel panelButtom = new JPanel();
case KeyEvent.VK_PAGE_DOWN:
snakeModel.speedDown();
break;
case KeyEvent.VK_SPACE:
case KeyEvent.VK_P:
snakeModel.changePauseState();
LinkedList na = snakeModel.nodeArray;
Iterator it = na.iterator();
while(it.hasNext()){
Node n = (Node)it.next();
drawNode(g,n);
mainFrame.setResizable(false);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
begin();
}
import javax.swing.*;
class SnakeModel implements Runnable{
GreedSnake gs;
boolean[][] matrix;
LinkedList nodeArray = new LinkedList();
}
}
///////////////////////////////////////////////////
// 文件2
///////////////////////////////////////////////////
import java.util.*;
panelButtom.add(labelHelp, BorderLayout.SOUTH);
cp.add(panelButtom,BorderLayout.SOUTH);
mainFrame.addKeyListener(this);
mainFrame.pack();
}
// draw the food
g.setColor(Color.RED);
Node n = snakeModel.food;
drawNode(g,n);
updateScore();
}
private void drawNode(Graphics g, Node n){
boolean paused = false;
int score = 0;
int countMove = 0;
// UP and DOWN should be even
// RIGHT and LEFT should be odd
public static final int UP = 2;
JFrame mainFrame;
Canvas paintCanvas;
JLabel labelScore;
SnakeModel snakeModel = null;
public static final int canvasWidth = 200;
public static final int canvasHeight = 300;
begin();
}
}
public void keyReleased(KeyEvent e){
}
public void keyTyped(KeyEvent e){
}
void repaint(){
Graphics g = paintCanvas.getGraphics();
snakeModel.changeDirection(SnakeModel.UP);
break;
case KeyEvent.VK_DOWN:
snakeModel.changeDirection(SnakeModel.DOWN);
break;
Node food;
int maxX;
int maxY;
int direction = 2;
boolean running = false;
int timeInterval = 200;
double speedChangeRate = 0.75;
panelButtom.setLayout(new BorderLayout());
JLabel labelHelp;
labelHelp = new JLabel("PageUp, PageDown for speed;", JLabel.CENTER)
panelButtom.add(labelHelp, BorderLayout.NORTH);
public static final int DOWN = 4;
public static final int LEFT = 1;
public static final int RIGHT = 3;
public SnakeModel(GreedSnake gs, int maxX, int maxY){
public static final int nodeWidth = 10;
public static final int nodeHeight = 10;
public GreedSnake() {
mainFrame = new JFrame("GreedSnake");
this.gs = gs;
this.maxX = maxX;
this.maxY = maxY;
// initial matirx
matrix = new boolean[maxX][];
for(int i=0; i<maxX; ++i){
public void keyPressed(KeyEvent e){
int keyCode = e.getKeyCode();
if (snakeModel.running)
switch(keyCode){
case KeyEvent.VK_UP:
break;
case KeyEvent.VK_ADD:
case KeyEvent.VK_PAGE_UP:
snakeModel.speedUp();
break;
case KeyEvent.VK_SUBTRACT:
matrix[i] = new boolean[maxY];
Arrays.fill(matrix[i],false);
}
// initial the snake
int initArrayLength = maxX > 20 ? 10 : maxX/2;
break;
default:
}
if (keyCode == KeyEvent.VK_R ||
keyCode == KeyEvent.VK_S ||
keyCode == KeyEvent.VK_ENTER){
snakeModel.running = false;
//draw background
g.setColor(Color.WHITE);
g.fillRect(0,0,canvasWidth,canvasHeight);
// draw the snake
g.setColor(Color.BLACK);
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class GreedSnake implements KeyListener{
Container cp = mainFrame.getContentPane();
labelScore = new JLabel("Score:");
cp.add(labelScore, BorderLayout.NORTH);
paintCanvas = new Canvas();
canvasHeight/nodeHeight);
(new Thread(snakeModel)).start();
}
}
public static void main(String[] args){
GreedSnake gs = new GreedSnake();