導航:首頁 > 編程語言 > 簡單java游戲代碼

簡單java游戲代碼

發布時間:2023-07-10 02:43:28

❶ 求java小游戲源代碼

import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;

import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioSystem;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Rectangle;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JSlider;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.Vector;

public class Frame extends JFrame implements Runnable {
JPanel contentPane;

JPanel jPanel1 = new JPanel();

JButton jButton1 = new JButton();

JSlider jSlider1 = new JSlider();

JLabel jLabel1 = new JLabel();

JButton jButton2 = new JButton();

JLabel jLabel2 = new JLabel();

int count = 1, rapidity = 80; // count 當前進行的個數, rapidity 游標的位置

int zhengque = 0, cuowu = 0;

int rush[] = { 10 ,20 ,30 }; //游戲每關的個數 可以自由添加.列 { 10 ,20 ,30 ,40,50}

int rush_count = 0; //記錄關數

char list[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; //隨機出現的數字 可以自由添加

Vector number = new Vector();

String paian = "true";

AudioClip Musci_anjian, Music_shi, Music_chenggong;

public Frame() {
try {
setDefaultCloseOperation(EXIT_ON_CLOSE);

//-----------------聲音文件---------------------
Musci_anjian = Applet.newAudioClip(new File("sounds//anjian.wav")
.toURL());
Music_shi = Applet.newAudioClip(new File("sounds//shi.wav")
.toURL());
Music_chenggong = Applet.newAudioClip(new File(
"sounds//chenggong.wav").toURL());

//---------------------------------------
jbInit();
} catch (Exception exception) {
exception.printStackTrace();
}
}

/**
* Component initialization.
*
* @throws java.lang.Exception
*/
private void jbInit() throws Exception {
contentPane = (JPanel) getContentPane();
contentPane.setLayout(null);
setSize(new Dimension(588, 530));
setTitle("Frame Title");
jPanel1.setBorder(BorderFactory.createEtchedBorder());
jPanel1.setBounds(new Rectangle(4, 4, 573, 419));
jPanel1.setLayout(null);
jButton1.setBounds(new Rectangle(277, 442, 89, 31));
jButton1.setText("開始");
jButton1.addActionListener(new Frame1_jButton1_actionAdapter(this));
jSlider1.setBounds(new Rectangle(83, 448, 164, 21));
jSlider1.setMaximum(100);
jSlider1.setMinimum(1);
jSlider1.setValue(50);
jLabel1.setText("速度");
jLabel1.setBounds(new Rectangle(35, 451, 39, 18));
jButton2.setBounds(new Rectangle(408, 442, 89, 31));
jButton2.setText("結束");
jButton2.addActionListener(new Frame1_jButton2_actionAdapter(this));
jLabel2.setText("第一關:100個");
jLabel2.setBounds(new Rectangle(414, 473, 171, 21));
contentPane.add(jPanel1);
contentPane.add(jButton2);
contentPane.add(jButton1);
contentPane.add(jSlider1);
contentPane.add(jLabel1);
contentPane.add(jLabel2);
this.addKeyListener(new MyListener());
jButton1.addKeyListener(new MyListener());
jSlider1.addKeyListener(new MyListener());
jSlider1.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
rapidity = jSlider1.getValue();
}
});
}

public void run() {
number.clear();
zhengque = 0;
cuowu = 0;
paian = "true";
while (count <= rush[rush_count]) {
try {
Thread t = new Thread(new Tthread());
t.start();
count += 1;
Thread.sleep(1000 + (int) (Math.random() * 2000)); // 生產下組停頓時間
// 最快1快.最慢2秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}

while (true) { // 等待最後一個字元消失
if (number.size() == 0) {
break;
}
}

if (zhengque == 0) { // 為了以後相除..如果全部正確或者錯誤就會出現錯誤. 所以..
zhengque = 1;
}
if (cuowu == 0) {
cuowu = 1;
}

if (paian.equals("true")) { // 判斷是否是自然結束
if (zhengque / cuowu >= 2) {
JOptionPane.showMessageDialog(null, "恭喜你過關了");
rush_count += 1; // 自動加1關
if (rush_count < rush.length) {
if (rapidity > 10) { // 當速度大於10的時候在-5提加速度.怕速度太快
rapidity -= 5; // 速度自動減10毫秒
jSlider1.setValue(rapidity); // 選擇位置
}
Thread t = new Thread(this);
t.start();
} else {
JOptionPane.showMessageDialog(null, "牛B...你通關了..");
rush_count = 0;
count = 0;
}
} else {
JOptionPane.showMessageDialog(null, "請再接再勵");
rush_count = 0;
count = 0;
}
} else {
rush_count = 0;
count = 0;
}
}

public void jButton1_actionPerformed(ActionEvent e) {
Thread t = new Thread(this);
t.start();
}

public void jButton2_actionPerformed(ActionEvent e) {
count = rush[rush_count] + 1;
paian = "flase";
}

class Tthread implements Runnable {
public void run() {
boolean fo = true;
int Y = 0, X = 0;
JLabel show = new JLabel();
show.setFont(new java.awt.Font("宋體", Font.PLAIN, 33));
jPanel1.add(show);
X = 10 + (int) (Math.random() * 400);
String parameter = list[(int) (Math.random() * list.length)] + "";
Bean bean = new Bean();
bean.setParameter(parameter);
bean.setShow(show);
number.add(bean);
show.setText(parameter);
while (fo) {
// ---------------------數字下移--------------------
show.setBounds(new Rectangle(X, Y += 2, 33, 33));
try {
Thread.sleep(rapidity);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (Y >= 419) {
fo = false;
for (int i = number.size() - 1; i >= 0; i--) {
Bean bn = ((Bean) number.get(i));
if (parameter.equalsIgnoreCase(bn.getParameter())) {
cuowu += 1;
jLabel2.setText("正確:" + zhengque + "個,錯誤:" + cuowu
+ "個");
number.removeElementAt(i);
Music_shi.play();
break;
}
}
}
}

}
}

class MyListener extends KeyAdapter {
public void keyPressed(KeyEvent e) {
String uu = e.getKeyChar() + "";
for (int i = 0; i < number.size(); i++) {
Bean bean = ((Bean) number.get(i));
if (uu.equalsIgnoreCase(bean.getParameter())) {
zhengque += 1;
number.removeElementAt(i);
bean.getShow().setVisible(false);
jLabel2.setText("正確:" + zhengque + "個,錯誤:" + cuowu + "個");
Music_chenggong.play();
break;
}
}

Musci_anjian.play();
}
}

public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception exception) {
exception.printStackTrace();
}
Frame frame = new Frame();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = frame.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
frame.setLocation((screenSize.width - frameSize.width) / 2,
(screenSize.height - frameSize.height) / 2);
frame.setVisible(true);
}
}

class Frame1_jButton2_actionAdapter implements ActionListener {
private Frame adaptee;

Frame1_jButton2_actionAdapter(Frame adaptee) {
this.adaptee = adaptee;
}

public void actionPerformed(ActionEvent e) {
adaptee.jButton2_actionPerformed(e);
}
}

class Frame1_jButton1_actionAdapter implements ActionListener {
private Frame adaptee;

Frame1_jButton1_actionAdapter(Frame adaptee) {
this.adaptee = adaptee;
}

public void actionPerformed(ActionEvent e) {
adaptee.jButton1_actionPerformed(e);
}
}

class Bean {
String parameter = null;

JLabel show = null;

public JLabel getShow() {
return show;
}

public void setShow(JLabel show) {
this.show = show;
}

public String getParameter() {
return parameter;
}

public void setParameter(String parameter) {
this.parameter = parameter;
}
}

❷ 求一個簡單RPG游戲的代碼,JAva編寫的

packagecom.lxi;

importjava.io.BufferedReader;
importjava.io.InputStreamReader;

publicclassRpg{
@SuppressWarnings("unchecked")
publicstaticvoidmain(String[]args)throwsException{
System.out.println("在這里輸入兩個人物進行PK,以英文逗號分隔:[BM,DH,MK]");
BufferedReaderbr=newBufferedReader(newInputStreamReader(System.in));
Class<Person>c1;
Class<Person>c2;
try{
Stringtemp=br.readLine();
String[]str=temp.split(",");
if(str.length!=2){
thrownewException("輸入格式有誤,按默認PK");
}
c1=(Class<Person>)Class.forName("com.lxi."
+str[0].toUpperCase());
c2=(Class<Person>)Class.forName("com.lxi."
+str[1].toUpperCase());
}catch(Exceptione){
//TODOAuto-generatedcatchblock
c1=(Class<Person>)Class.forName("com.lxi.BM");
c2=(Class<Person>)Class.forName("com.lxi.DH");
}
try{
Personp1=c1.newInstance();
Personp2=c2.newInstance();
longtime=System.currentTimeMillis();
longnextTime1=(long)(time+p1.coldTime*1000);//
longnextTime2=(long)(time+p2.coldTime*1000);//發動攻擊的時間
System.out.println("---游戲開始---");
while(true){
longcurrenTime=System.currentTimeMillis();

if(nextTime1<currenTime){//時間到則發動攻擊
p1.hit(p2);
nextTime1+=p1.coldTime*1000+p1.waitTime*1000;//下次攻擊時間=冷卻時間+被暈眩時間
p1.waitTime=0;//回合結束,重置被暈眩時間為0
}
if(nextTime2<currenTime){
p2.hit(p1);
nextTime2+=p2.coldTime*1000+p2.waitTime*1000;
p2.waitTime=0;
}
}
}catch(ClassCastExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(InstantiationExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(IllegalAccessExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(Exceptione){
e.printStackTrace();
}
}
}




packagecom.lxi;

importjava.util.Random;

classBMextendsPerson{
publicBM(){
val=650;
coldTime=1.5;
fight=40;
chanceHit=3;
chanceDefense=3;
waitTime=0;
}

intcount=0;//防禦技能發動的次數
inttemp=40;//攻擊力,值同fight
booleanhitFlag=false;
booleandefenseFlag=false;
Randomrand=newRandom();

publicvoidhit(Personp){
if(rand.nextInt(10)<chanceHit){
fight=fight*2;//發動雙倍攻擊
hitFlag=true;
}
inthurt=p.defense(this);
p.val=p.val-hurt;
fight=temp;//還原為單倍攻擊
if(p.val<=0){
System.out.println(this.getClass().getSimpleName()+"勝出!");
System.exit(0);
}
System.out.println(this.getClass().getSimpleName()+"攻擊"
+p.getClass().getSimpleName()+","
+this.getClass().getSimpleName()
+(this.hitFlag?"發動攻擊技能":"未發動攻擊技能")
+p.getClass().getSimpleName()
+(this.defenseFlag?"發動防禦技能":"未發動防禦技能")
+this.getClass().getSimpleName()+":"+this.val+","
+p.getClass().getSimpleName()+":"+p.val);
hitFlag=false;
defenseFlag=false;
}

publicintdefense(Personp){
if(rand.nextInt(10)<chanceDefense){
if(count!=0){
p.val=p.val-p.fight;
count++;
defenseFlag=true;
if(p.val<=0){
System.out.println(this.getClass().getSimpleName()+"勝出!");
System.exit(0);
}
}
}
returnp.fight;
}
}

classMKextendsPerson{
publicMK(){
val=700;
coldTime=2.5;
fight=50;
chanceDefense=6;
chanceHit=3;
waitTime=0;
}

booleanhitFlag=false;
booleandefenseFlag=false;
Randomrand=newRandom();

publicvoidhit(Personp){
if(rand.nextInt(10)<chanceHit){
p.waitTime=3;//使對方暈眩3s
hitFlag=true;
}
inthurt=p.defense(this);
p.val=p.val-hurt;
if(p.val<=0){
System.out.println(this.getClass().getSimpleName()+"勝出!");
System.exit(0);
}
System.out.println(this.getClass().getSimpleName()+"攻擊"
+p.getClass().getSimpleName()+","
+this.getClass().getSimpleName()
+(this.hitFlag?"發動攻擊技能":"未發動攻擊技能")
+p.getClass().getSimpleName()
+(this.defenseFlag?"發動防禦技能":"未發動防禦技能")
+this.getClass().getSimpleName()+":"+this.val+","
+p.getClass().getSimpleName()+":"+p.val);
hitFlag=false;
defenseFlag=false;
}

publicintdefense(Personp){
if(rand.nextInt(10)<chanceDefense){
defenseFlag=true;
returnp.fight/2;//防禦技能發動,傷害減半
}
returnp.fight;
}
}


packagecom.lxi;

importjava.io.BufferedReader;
importjava.io.InputStreamReader;
importjava.util.Random;

//三個人物的基類
abstractclassPerson{
intval;//生命值
doublecoldTime;//冷卻時間
intwaitTime;//暈眩時間
intfight;//攻擊力
intchanceHit;//發起主動技能的概率
intchanceDefense;//發起防禦技能的概率

abstractvoidhit(Personp);//攻擊技能

abstractintdefense(Personp);//防禦技能,返回被傷害點數
}

classDHextendsPerson{
publicDH(){
val=600;
coldTime=1.0;
fight=30;
chanceHit=3;//表示30%的概率
chanceDefense=3;
waitTime=0;
}

Randomrand=newRandom();
booleanhitFlag=false;//主動技能發動的標識
booleandefenseFlag=false;//防禦技能發動的標識

publicvoidhit(Personp){
if(rand.nextInt(10)<chanceHit){//發動主動技能
inthurt=p.defense(this);
p.val=p.val-hurt;
if(p.val<=0){
System.out.println(this.getClass().getSimpleName()+"勝出!");
System.exit(0);
}
val=val+hurt;
if(val>600)
val=600;
hitFlag=true;//標記主動技能已經發動
}else{//進行普通攻擊
inthurt=p.defense(this);
p.val=p.val-hurt;
if(p.val<=0){
System.out.println(this.getClass().getSimpleName()+"勝出!");
System.exit(0);
}
}
System.out.println(this.getClass().getSimpleName()+"攻擊"
+p.getClass().getSimpleName()+","
+this.getClass().getSimpleName()
+(this.hitFlag?"發動攻擊技能":"未發動攻擊技能")
+p.getClass().getSimpleName()
+(this.defenseFlag?"發動防禦技能":"未發動防禦技能")
+this.getClass().getSimpleName()+":"+this.val+","
+p.getClass().getSimpleName()+":"+p.val);
hitFlag=false;//
defenseFlag=false;//重置標記,下次重用
}

publicintdefense(Personp){
if(rand.nextInt(10)<chanceDefense){
defenseFlag=true;//標記防禦技能已經發動
return0;
}else{
returnp.fight;
}
}
}

❸ 跪求java小項目,經典小游戲代碼

五子棋

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class mypanel extends Panel implements MouseListener
{
int chess[][] = new int[11][11];
boolean Is_Black_True;
mypanel()
{
Is_Black_True = true;
for(int i = 0;i < 11;i++)
{
for(int j = 0;j < 11;j++)
{
chess[i][j] = 0;
}
}
addMouseListener(this);
setBackground(Color.BLUE);
setBounds(0, 0, 360, 360);
setVisible(true);
}
public void mousePressed(MouseEvent e)
{
int x = e.getX();
int y = e.getY();

if(x < 25 || x > 330 + 25 ||y < 25 || y > 330+25)
{
return;
}
if(chess[x/30-1][y/30-1] != 0)
{
return;
}
if(Is_Black_True == true)
{
chess[x/30-1][y/30-1] = 1;
Is_Black_True = false;
repaint();
Justisewiner();
return;
}
if(Is_Black_True == false)
{
chess[x/30-1][y/30-1] = 2;
Is_Black_True = true;
repaint();
Justisewiner();
return;
}
}
void Drawline(Graphics g)
{
for(int i = 30;i <= 330;i += 30)
{
for(int j = 30;j <= 330; j+= 30)
{
g.setColor(Color.WHITE);
g.drawLine(i, j, i, 330);
}
}

for(int j = 30;j <= 330;j += 30)
{
g.setColor(Color.WHITE);
g.drawLine(30, j, 330, j);
}

}
void Drawchess(Graphics g)
{
for(int i = 0;i < 11;i++)
{
for(int j = 0;j < 11;j++)
{
if(chess[i][j] == 1)
{
g.setColor(Color.BLACK);
g.fillOval((i + 1) * 30 - 8, (j + 1) * 30 - 8, 16, 16);
}
if(chess[i][j] == 2)
{
g.setColor(Color.WHITE);
g.fillOval((i + 1) * 30 - 8, (j + 1) * 30 - 8, 16, 16);
}
}
}
}
void Justisewiner()
{
int black_count = 0;
int white_count = 0;
int i = 0;

for(i = 0;i < 11;i++)//橫向判斷
{
for(int j = 0;j < 11;j++)
{
if(chess[i][j] == 1)
{
black_count++;
if(black_count == 5)
{
JOptionPane.showMessageDialog(this, "黑棋勝利");
Clear_Chess();
return;
}
}
else
{
black_count = 0;
}
if(chess[i][j] == 2)
{
white_count++;
if(white_count == 5)
{
JOptionPane.showMessageDialog(this, "白棋勝利");
Clear_Chess();
return;
}
}
else
{
white_count = 0;
}
}
}

for(i = 0;i < 11;i++)//豎向判斷
{
for(int j = 0;j < 11;j++)
{
if(chess[j][i] == 1)
{
black_count++;
if(black_count == 5)
{
JOptionPane.showMessageDialog(this, "黑棋勝利");
Clear_Chess();
return;
}
}
else
{
black_count = 0;
}
if(chess[j][i] == 2)
{
white_count++;
if(white_count == 5)
{
JOptionPane.showMessageDialog(this, "白棋勝利");
Clear_Chess();
return;
}
}
else
{
white_count = 0;
}
}
}

for(i = 0;i < 7;i++)//左向右斜判斷
{
for(int j = 0;j < 7;j++)
{
for(int k = 0;k < 5;k++)
{
if(chess[i + k][j + k] == 1)
{
black_count++;
if(black_count == 5)
{
JOptionPane.showMessageDialog(this, "黑棋勝利");
Clear_Chess();
return;
}
}
else
{
black_count = 0;
}
if(chess[i + k][j + k] == 2)
{
white_count++;
if(white_count == 5)
{
JOptionPane.showMessageDialog(this, "白棋勝利");
Clear_Chess();
return;
}
}
else
{
white_count = 0;
}
}
}
}

for(i = 4;i < 11;i++)//右向左斜判斷
{
for(int j = 6;j >= 0;j--)
{
for(int k = 0;k < 5;k++)
{
if(chess[i - k][j + k] == 1)
{
black_count++;
if(black_count == 5)
{
JOptionPane.showMessageDialog(this, "黑棋勝利");
Clear_Chess();
return;
}
}
else
{
black_count = 0;
}
if(chess[i - k][j + k] == 2)
{
white_count++;
if(white_count == 5)
{
JOptionPane.showMessageDialog(this, "白棋勝利");
Clear_Chess();
return;
}
}
else
{
white_count = 0;
}
}
}
}

}
void Clear_Chess()
{
for(int i=0;i<11;i++)
{
for(int j=0;j<11;j++)
{
chess[i][j]=0;
}
}
repaint();
}
public void paint(Graphics g)
{
Drawline(g);
Drawchess(g);
}
public void mouseExited(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
public void mouseClicked(MouseEvent e){}

}

class myframe extends Frame implements WindowListener
{
mypanel panel;
myframe()
{
setLayout(null);
panel = new mypanel();
add(panel);
panel.setBounds(0,23, 360, 360);
setTitle("單人版五子棋");
setBounds(200, 200, 360, 383);
setVisible(true);
addWindowListener(this);

}
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
public void windowDeactivated(WindowEvent e){}
public void windowActivated(WindowEvent e){}
public void windowOpened(WindowEvent e){}
public void windowClosed(WindowEvent e){}
public void windowIconified(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
}
public class mywindow
{
public static void main(String argc [])
{
myframe f = new myframe();
}
}

❹ java掃雷游戲代碼

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Frame
extends JFrame {
JTextField text;
JLabel nowBomb, setBomb;
int BombNum, BlockNum; // 當前雷數,當前方塊數
int rightBomb, restBomb, restBlock; // 找到的地雷數,剩餘雷數,剩餘方塊數

JButton start = new JButton(" 開始 ");
JPanel MenuPamel = new JPanel();
JPanel bombPanel = new JPanel();
Bomb[][] bombButton;

JPanel c;
BorderLayout borderLayout1 = new BorderLayout();
GridLayout gridLayout1 = new GridLayout();
public Frame() {
try {
setDefaultCloseOperation(EXIT_ON_CLOSE);
jbInit();
}
catch (Exception exception) {
exception.printStackTrace();
}
}

private void jbInit() throws Exception {
c = (JPanel) getContentPane();
setTitle("掃雷");
c.setBackground(Color.WHITE);
MenuPamel.setBackground(Color.GRAY);
c.setLayout(borderLayout1);
setSize(new Dimension(600, 600));
setResizable(false);

BlockNum = 144;
BombNum = 10;
text = new JTextField("10 ", 3);
nowBomb = new JLabel("當前雷數" + ":" + BombNum);
setBomb = new JLabel("設置地雷數");
start.addActionListener(new Frame1_start_actionAdapter(this));

MenuPamel.add(setBomb);
MenuPamel.add(text);
MenuPamel.add(start);
MenuPamel.add(nowBomb);
c.add(MenuPamel, java.awt.BorderLayout.SOUTH);

bombPanel.setLayout(gridLayout1);
gridLayout1.setColumns( (int) Math.sqrt(BlockNum));
gridLayout1.setRows( (int) Math.sqrt(BlockNum));
bombButton = new Bomb[ (int) Math.sqrt(BlockNum)][ (int) Math.sqrt(BlockNum)];
for (int i = 0; i < (int) Math.sqrt(BlockNum); i++) {
for (int j = 0; j < (int) Math.sqrt(BlockNum); j++) {
bombButton[i][j] = new Bomb(i, j);
//bombButton[i][j].setSize(10, 10);
bombButton[i][j].setFont(new Font("", Font.PLAIN, 14));//設置字體大小

bombButton[i][j].setForeground(Color.white);
bombButton[i][j].addMouseListener(new Bomb_mouseAdapter(this));
bombButton[i][j].addActionListener(new Bomb_actionAdapter(this));
bombPanel.add(bombButton[i][j]);
}
}
c.add(bombPanel, java.awt.BorderLayout.CENTER);

startBomb();
}

/* 開始按鈕 */

public void start_actionPerformed(ActionEvent e) {
int num=Integer.parseInt(text.getText().trim());
if (num >= 5 && num < 50) {
BombNum = num;
startBomb();
}
else if (num < 5) {
JOptionPane.showMessageDialog(null, "您設置的地雷數太少了,請重設!", "錯誤",
JOptionPane.ERROR_MESSAGE);
num=10;
BombNum = num;
}
else {
JOptionPane.showMessageDialog(null, "您設置的地雷數太多了,請重設!", "錯誤",
JOptionPane.ERROR_MESSAGE);
num=10;
BombNum = num;
}
}

/* 開始,布雷 */

public void startBomb() {
nowBomb.setText("當前雷數" + ":" + BombNum);
for (int i = 0; i < (int) Math.sqrt(BlockNum); i++) {
for (int j = 0; j < (int) Math.sqrt(BlockNum); j++) {
bombButton[i][j].isBomb = false;
bombButton[i][j].isClicked = false;
bombButton[i][j].isRight = false;
bombButton[i][j].BombFlag = 0;
bombButton[i][j].BombRoundCount = 9;
bombButton[i][j].setEnabled(true);
bombButton[i][j].setText("");
bombButton[i][j].setFont(new Font("", Font.PLAIN, 14));//設置字體大小
bombButton[i][j].setForeground(Color.BLUE);
rightBomb = 0;
restBomb = BombNum;
restBlock = BlockNum - BombNum;
}
}

for (int i = 0; i < BombNum; ) {
int x = (int) (Math.random() * (int) (Math.sqrt(BlockNum) - 1));
int y = (int) (Math.random() * (int) (Math.sqrt(BlockNum) - 1));

if (bombButton[x][y].isBomb != true) {
bombButton[x][y].isBomb = true;
i++;
}
}
CountRoundBomb();
}

/* 計算方塊周圍雷數 */

public void CountRoundBomb() {
for (int i = 0; i < (int) Math.sqrt(BlockNum); i++) {
for (int j = 0; j < (int) Math.sqrt(BlockNum); j++) {
int count = 0;
// 當需要檢測的單元格本身無地雷的情況下,統計周圍的地雷個數
if (bombButton[i][j].isBomb != true) {
for (int x = i - 1; x < i + 2; x++) {
for (int y = j - 1; y < j + 2; y++) {
if ( (x >= 0) && (y >= 0)
&& (x < ( (int) Math.sqrt(BlockNum)))
&& (y < ( (int) Math.sqrt(BlockNum)))) {
if (bombButton[x][y].isBomb == true) {
count++;
}
}
}
}
bombButton[i][j].BombRoundCount = count;
}
}
}
}

/* 是否挖完了所有的雷 */

public void isWin() {
restBlock = BlockNum - BombNum;
for (int i = 0; i < (int) Math.sqrt(BlockNum); i++) {
for (int j = 0; j < (int) Math.sqrt(BlockNum); j++) {
if (bombButton[i][j].isClicked == true) {
restBlock--;
}
}
}

if (rightBomb == BombNum || restBlock == 0) {
JOptionPane.showMessageDialog(this, "您挖完了所有的雷,您勝利了!", "勝利",
JOptionPane.INFORMATION_MESSAGE);
startBomb();
}
}

/** 當選中的位置為空,則翻開周圍的地圖* */

public void isNull(Bomb ClickedButton) {
int i, j;
i = ClickedButton.num_x;
j = ClickedButton.num_y;

for (int x = i - 1; x < i + 2; x++) {
for (int y = j - 1; y < j + 2; y++) {
if ( ( (x != i) || (y != j)) && (x >= 0) && (y >= 0)
&& (x < ( (int) Math.sqrt(BlockNum)))
&& (y < ( (int) Math.sqrt(BlockNum)))) {
if (bombButton[x][y].isBomb == false
&& bombButton[x][y].isClicked == false
&& bombButton[x][y].isRight == false) {
turn(bombButton[x][y]);
}
}
}
}
}

/* 翻開 */

public void turn(Bomb ClickedButton) {
ClickedButton.setEnabled(false);
ClickedButton.isClicked = true;
if (ClickedButton.BombRoundCount > 0) {
ClickedButton.setText(ClickedButton.BombRoundCount + "");
}
else {
isNull(ClickedButton);
}
}

/* 左鍵點擊 */

public void actionPerformed(ActionEvent e) {
if ( ( (Bomb) e.getSource()).isClicked == false
&& ( (Bomb) e.getSource()).isRight == false) {
if ( ( (Bomb) e.getSource()).isBomb == false) {
turn( ( (Bomb) e.getSource()));
isWin();
}

else {
for (int i = 0; i < (int) Math.sqrt(BlockNum); i++) {
for (int j = 0; j < (int) Math.sqrt(BlockNum); j++) {
if (bombButton[i][j].isBomb == true) {
bombButton[i][j].setText("b");
}
}
}
( (Bomb) e.getSource()).setForeground(Color.RED);
( (Bomb) e.getSource()).setFont(new Font("", Font.BOLD, 20));
( (Bomb) e.getSource()).setText("X");
JOptionPane.showMessageDialog(this, "你踩到地雷了,按確定重來", "踩到地雷", 2);
startBomb();
}
}
}

/* 右鍵點擊 */

public void mouseClicked(MouseEvent e) {
Bomb bombSource = (Bomb) e.getSource();
boolean right = SwingUtilities.isRightMouseButton(e);

if ( (right == true) && (bombSource.isClicked == false)) {
bombSource.BombFlag = (bombSource.BombFlag + 1) % 3;
if (bombSource.BombFlag == 1) {
if (restBomb > 0) {
bombSource.setForeground(Color.RED);
bombSource.setText("F");
bombSource.isRight = true;
restBomb--;
}
else {
bombSource.BombFlag = 0;
}
}
else if (bombSource.BombFlag == 2) {
restBomb++;
bombSource.setText("Q");
bombSource.isRight = false;
}
else {
bombSource.setText("");
}

if (bombSource.isBomb == true) {
if (bombSource.BombFlag == 1) {
rightBomb++;
}
else if (bombSource.BombFlag == 2) {
rightBomb--;
}
}
nowBomb.setText("當前雷數" + ":" + restBomb);
isWin();
}
}

public static void main(String[] args) {
Frame frame = new Frame();
frame.setVisible(true);
}
}

class Frame1_start_actionAdapter
implements ActionListener {
private Frame adaptee;
Frame1_start_actionAdapter(Frame adaptee) {
this.adaptee = adaptee;
}

public void actionPerformed(ActionEvent e) {
adaptee.start_actionPerformed(e);
}
}

////////////////////////////
class Bomb
extends JButton {
int num_x, num_y; // 第幾號方塊
int BombRoundCount; // 周圍雷數
boolean isBomb; // 是否為雷
boolean isClicked; // 是否被點擊
int BombFlag; // 探雷標記
boolean isRight; // 是否點擊右鍵

public Bomb(int x, int y) {
num_x = x;
num_y = y;
BombFlag = 0;
BombRoundCount = 9;
isBomb = false;
isClicked = false;
isRight = false;
}
}

class Bomb_actionAdapter
implements ActionListener {
private Frame adaptee;
Bomb_actionAdapter(Frame adaptee) {
this.adaptee = adaptee;
}

public void actionPerformed(ActionEvent e) {
adaptee.actionPerformed(e);
}
}

class Bomb_mouseAdapter
extends MouseAdapter {
private Frame adaptee;
Bomb_mouseAdapter(Frame adaptee) {
this.adaptee = adaptee;
}

public void mouseClicked(MouseEvent e) {
adaptee.mouseClicked(e);
}
}

❺ 幾個Java小游戲代碼

package rece;
import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioSystem;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Rectangle;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JSlider;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.Vector;
public class Frame extends JFrame implements Runnable {
JPanel contentPane;
JPanel jPanel1 = new JPanel();
JButton jButton1 = new JButton();
JSlider jSlider1 = new JSlider();
JLabel jLabel1 = new JLabel();
JButton jButton2 = new JButton();
JLabel jLabel2 = new JLabel();
int count = 1, rapidity = 80; // count 當前進行的個數, rapidity 游標的位置
int zhengque = 0, cuowu = 0;
int rush[] = { 10 ,20 ,30 }; //游戲每關的個數 可以自由添加.列 { 10 ,20 ,30 ,40,50}
int rush_count = 0; //記錄關數
char list[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; //隨機出現的數字 可以自由添加
Vector number = new Vector();
String paian = "true";
AudioClip Musci_anjian, Music_shi, Music_chenggong;
public Frame() {
try {
setDefaultCloseOperation(EXIT_ON_CLOSE);

//-----------------聲音文件---------------------
Musci_anjian = Applet.newAudioClip(new File("sounds//anjian.wav")
.toURL());
Music_shi = Applet.newAudioClip(new File("sounds//shi.wav")
.toURL());
Music_chenggong = Applet.newAudioClip(new File(
"sounds//chenggong.wav").toURL());

//---------------------------------------
jbInit();
} catch (Exception exception) {
exception.printStackTrace();
}
}
/**
* Component initialization.
*
* @throws java.lang.Exception
*/
private void jbInit() throws Exception {
contentPane = (JPanel) getContentPane();
contentPane.setLayout(null);
setSize(new Dimension(588, 530));
setTitle("Frame Title");
jPanel1.setBorder(BorderFactory.createEtchedBorder());
jPanel1.setBounds(new Rectangle(4, 4, 573, 419));
jPanel1.setLayout(null);
jButton1.setBounds(new Rectangle(277, 442, 89, 31));
jButton1.setText("開始");
jButton1.addActionListener(new Frame1_jButton1_actionAdapter(this));
jSlider1.setBounds(new Rectangle(83, 448, 164, 21));
jSlider1.setMaximum(100);
jSlider1.setMinimum(1);
jSlider1.setValue(50);
jLabel1.setText("速度");
jLabel1.setBounds(new Rectangle(35, 451, 39, 18));
jButton2.setBounds(new Rectangle(408, 442, 89, 31));
jButton2.setText("結束");
jButton2.addActionListener(new Frame1_jButton2_actionAdapter(this));
jLabel2.setText("第一關:100個");
jLabel2.setBounds(new Rectangle(414, 473, 171, 21));
contentPane.add(jPanel1);
contentPane.add(jButton2);
contentPane.add(jButton1);
contentPane.add(jSlider1);
contentPane.add(jLabel1);
contentPane.add(jLabel2);
this.addKeyListener(new MyListener());
jButton1.addKeyListener(new MyListener());
jSlider1.addKeyListener(new MyListener());
jSlider1.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
rapidity = jSlider1.getValue();
}
});
}
public void run() {
number.clear();
zhengque = 0;
cuowu = 0;
paian = "true";
while (count <= rush[rush_count]) {
try {
Thread t = new Thread(new Tthread());
t.start();
count += 1;
Thread.sleep(1000 + (int) (Math.random() * 2000)); // 生產下組停頓時間
// 最快1快.最慢2秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
while (true) { // 等待最後一個字元消失
if (number.size() == 0) {
break;
}
}
if (zhengque == 0) { // 為了以後相除..如果全部正確或者錯誤就會出現錯誤. 所以..
zhengque = 1;
}
if (cuowu == 0) {
cuowu = 1;
}
if (paian.equals("true")) { // 判斷是否是自然結束
if (zhengque / cuowu >= 2) {
JOptionPane.showMessageDialog(null, "恭喜你過關了");
rush_count += 1; // 自動加1關
if (rush_count < rush.length) {
if (rapidity > 10) { // 當速度大於10的時候在-5提加速度.怕速度太快
rapidity -= 5; // 速度自動減10毫秒
jSlider1.setValue(rapidity); // 選擇位置
}
Thread t = new Thread(this);
t.start();
} else {
JOptionPane.showMessageDialog(null, "牛B...你通關了..");
rush_count = 0;
count = 0;
}
} else {
JOptionPane.showMessageDialog(null, "請再接再勵");
rush_count = 0;
count = 0;
}
} else {
rush_count = 0;
count = 0;
}
}
public void jButton1_actionPerformed(ActionEvent e) {
Thread t = new Thread(this);
t.start();
}
public void jButton2_actionPerformed(ActionEvent e) {
count = rush[rush_count] + 1;
paian = "flase";
}
class Tthread implements Runnable {
public void run() {
boolean fo = true;
int Y = 0, X = 0;
JLabel show = new JLabel();
show.setFont(new java.awt.Font("宋體", Font.PLAIN, 33));
jPanel1.add(show);
X = 10 + (int) (Math.random() * 400);
String parameter = list[(int) (Math.random() * list.length)] + "";
Bean bean = new Bean();
bean.setParameter(parameter);
bean.setShow(show);
number.add(bean);
show.setText(parameter);
while (fo) {
// ---------------------數字下移--------------------
show.setBounds(new Rectangle(X, Y += 2, 33, 33));
try {
Thread.sleep(rapidity);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (Y >= 419) {
fo = false;
for (int i = number.size() - 1; i >= 0; i--) {
Bean bn = ((Bean) number.get(i));
if (parameter.equalsIgnoreCase(bn.getParameter())) {
cuowu += 1;
jLabel2.setText("正確:" + zhengque + "個,錯誤:" + cuowu
+ "個");
number.removeElementAt(i);
Music_shi.play();
break;
}
}
}
}
}
}
class MyListener extends KeyAdapter {
public void keyPressed(KeyEvent e) {
String uu = e.getKeyChar() + "";
for (int i = 0; i < number.size(); i++) {
Bean bean = ((Bean) number.get(i));
if (uu.equalsIgnoreCase(bean.getParameter())) {
zhengque += 1;
number.removeElementAt(i);
bean.getShow().setVisible(false);
jLabel2.setText("正確:" + zhengque + "個,錯誤:" + cuowu + "個");
Music_chenggong.play();
break;
}
}
Musci_anjian.play();
}
}
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception exception) {
exception.printStackTrace();
}
Frame frame = new Frame();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = frame.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
frame.setLocation((screenSize.width - frameSize.width) / 2,
(screenSize.height - frameSize.height) / 2);
frame.setVisible(true);
}
}
class Frame1_jButton2_actionAdapter implements ActionListener {
private Frame adaptee;
Frame1_jButton2_actionAdapter(Frame adaptee) {
this.adaptee = adaptee;
}
public void actionPerformed(ActionEvent e) {
adaptee.jButton2_actionPerformed(e);
}
}
class Frame1_jButton1_actionAdapter implements ActionListener {
private Frame adaptee;
Frame1_jButton1_actionAdapter(Frame adaptee) {
this.adaptee = adaptee;
}
public void actionPerformed(ActionEvent e) {
adaptee.jButton1_actionPerformed(e);
}
}
class Bean {
String parameter = null;
JLabel show = null;
public JLabel getShow() {
return show;
}
public void setShow(JLabel show) {
this.show = show;
}
public String getParameter() {
return parameter;
}
public void setParameter(String parameter) {
this.parameter = parameter;
}
}
我只有一個打字母小游戲

❻ 急求簡單的手機java小游戲代碼 能運行的 簡單的就可以

package test;

import java.util.Random;
import java.util.Scanner;

public class TestGame {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

Scanner sc = new Scanner(System.in);
int r = new Random().nextInt(999999);
int count =0 ;
while(true){

System.out.println("猜數字游戲,請輸入一個數0到999999,輸入-1結束游戲:");
int i = sc.nextInt() ;
if(i==-1){
break ;
}
count ++ ;
if(i<r){
System.out.print("你猜小了。");
System.out.println("你已經猜了"+count+"次");
}else if(i>r){
System.out.println("你猜大了。");
System.out.println("你已經猜了"+count+"次");
}else{
System.out.println("恭喜你大對了,但是沒獎勵!");
}

}

System.out.println("游戲結束");
}

}

❼ 求一個簡單的JAVA游戲代碼,100行左右,謝謝!

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Painter extends JFrame{
/**
*
*/
private static final long serialVersionUID = 8160427604782702376L;
CanvasPanel canvas = new CanvasPanel();;
public Painter() {
super("Star");
this.add(canvas);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setResizable(false);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public static void main(String[] args) {
new Painter();
}
}
class CanvasPanel extends JPanel implements ActionListener{
/**
*
*/
private static final long serialVersionUID = -464252885453878L;
private JButton[] btn = new JButton[4];
private String[] btn_name = {"+", "-", "R", "L"};
private int center_x = 200, center_y = 200, radius = 100, degree = 0;
public CanvasPanel() {
this.setPreferredSize(new Dimension(400, 500));
this.setLayout(null);
for(int i = 0; i < 4; i++) {
btn[i] = new JButton(btn_name[i]);
btn[i].setBounds(160 + i * 60, 425, 50, 50);
btn[i].addActionListener(this);
this.add(btn[i]);
}
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
for(int i = 0; i < 5; i++) {
g.drawLine( (int) (center_x + radius * Math.sin(Math.toRadians(degree + 72 * i))),
(int) (center_y - radius * Math.cos(Math.toRadians(degree + 72 * i))),
(int) (center_x + radius * Math.sin(Math.toRadians(degree + 72 * i + 144))),
(int) (center_y - radius * Math.cos(Math.toRadians(degree + 72 * i + 144))));
}
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getActionCommand() == "+") {
if(radius < 200)
radius += 2;
repaint();
} else if(e.getActionCommand() == "-") {
if(radius > 0)
radius -= 2;
repaint();
} else if(e.getActionCommand() == "R") {
degree = (degree + 2) % 360;
repaint();
} else if(e.getActionCommand() == "L") {
degree = (degree - 2) % 360;
repaint();
}
}
}

❽ 求一個簡單又有趣的JAVA小游戲代碼

具體如下:

連連看的小源碼

package Lianliankan;

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;//消除方法控制

代碼(code)是程序員用開發工具所支持的語言寫出來的源文件,是一組由字元、符號或信號碼元以離散形式表示信息的明確的規則體系。

對於字元和Unicode數據的位模式的定義,此模式代表特定字母、數字或符號(例如 0x20 代表一個空格,而 0x74 代表字元「t」)。一些數據類型每個字元使用一個位元組;每個位元組可以具有 256 個不同的位模式中的一個模式。

在計算機中,字元由不同的位模式(ON 或 OFF)表示。每個位元組有 8 位,這 8 位可以有 256 種不同的 ON 和 OFF 組合模式。對於使用 1 個位元組存儲每個字元的程序,通過給每個位模式指派字元可表示最多 256 個不同的字元。2 個位元組有 16 位,這 16 位可以有 65,536 種唯一的 ON 和 OFF 組合模式。使用 2 個位元組表示每個字元的程序可表示最多 65,536 個字元。

單位元組代碼頁是字元定義,這些字元映射到每個位元組可能有的 256 種位模式中的每一種。代碼頁定義大小寫字元、數字、符號以及 !、@、#、% 等特殊字元的位模式。每種歐洲語言(如德語和西班牙語)都有各自的單位元組代碼頁。

雖然用於表示 A 到 Z 拉丁字母表字元的位模式在所有的代碼頁中都相同,但用於表示重音字元(如"é"和"á")的位模式在不同的代碼頁中卻不同。如果在運行不同代碼頁的計算機間交換數據,必須將所有字元數據由發送計算機的代碼頁轉換為接收計算機的代碼頁。如果源數據中的擴展字元在接收計算機的代碼頁中未定義,那麼數據將丟失。

如果某個資料庫為來自許多不同國家的客戶端提供服務,則很難為該資料庫選擇這樣一種代碼頁,使其包括所有客戶端計算機所需的全部擴展字元。而且,在代碼頁間不停地轉換需要花費大量的處理時間。

閱讀全文

與簡單java游戲代碼相關的資料

熱點內容
如何驗證web伺服器是否正常工作 瀏覽:132
全球最大的加密貨幣網站 瀏覽:284
解壓文件為什麼有問號 瀏覽:389
php考試系統模板 瀏覽:431
pdf導出圖片模糊 瀏覽:610
我的世界編玩邊學伺服器地址 瀏覽:456
基於單片機的火災報警系統 瀏覽:166
上海追星用什麼app 瀏覽:425
海馬m5壓縮機維修 瀏覽:98
抖音怎麼給自己喜歡的加密 瀏覽:247
中國五大加密貨幣 瀏覽:263
程序員手疼7年查6處骨腫瘤 瀏覽:39
python列表對象的創建與刪除 瀏覽:467
python刪除excel表格中的一行 瀏覽:521
android資料庫的增刪改查 瀏覽:632
雲伺服器2g4g有什麼區別 瀏覽:324
顯示文件夾所有文件的文件名函數 瀏覽:213
可以在網站寫代碼的編譯器 瀏覽:76
王者換伺服器怎麼不用重玩 瀏覽:328
武漢編譯ipfs雲存儲器 瀏覽:52