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

簡單的游戲代碼java

發布時間:2022-08-29 14:13:50

1. 用java編寫一個猜數字游戲,

packageday06;
importjava.util.Scanner;
//猜字元游戲
publicclassGuessingGame{
//主方法
publicstaticvoidmain(String[]args){
Scannerscan=newScanner(System.in);
intcount=0;//猜錯的次數
char[]chs=generate();//隨機生成的字元數組
System.out.println(chs);//作弊
while(true){//自造死循環
System.out.println("猜吧!");
Stringstr=scan.next().toUpperCase();//獲取用戶輸入的字元串
if(str.equals("EXIT")){//判斷str是否是EXIT
System.out.println("下次再來吧!");
break;
}
char[]input=str.toCharArray();//將字元串轉換為字元數組
int[]result=check(chs,input);//對比
if(result[0]==chs.length){//位置對為5
intscore=chs.length*100-count*10;//一個字元100分,錯一次減10分
System.out.println("恭喜你猜對了,得分:"+score);
break;//猜對時跳出循環
}else{//沒猜對
count++;//猜錯次數增1
System.out.println("字元對:"+result[1]+"個,位置對:"+result[0]+"個");
}
}
}
//隨機生成5個字元數組
publicstaticchar[]generate(){
char[]chs=newchar[5];
char[]letters={'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'};
boolean[]flags=newboolean[letters.length];//1.
for(inti=0;i<chs.length;i++){
intindex;
do{
index=(int)(Math.random()*letters.length);//0到25
}while(flags[index]==true);//2.
chs[i]=letters[index];
flags[index]=true;//3.
}
returnchs;
}
//對比隨機數組與用戶輸入的數組
publicstaticint[]check(char[]chs,char[]input){
int[]result=newint[2];
for(inti=0;i<chs.length;i++){
for(intj=0;j<input.length;j++){
if(chs[i]==input[j]){//字元對
result[1]++;//字元對個數增1
if(i==j){//位置對
result[0]++;//位置對個數增1
}
break;
}
}
}
returnresult;
}
}

2. 求一個簡單的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;//消除方法控制
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 && secondButton!=firstButton){
xiao();
}
}
}
public void xiao() { //相同的情況下能不能消去。仔細分析,不一條條注釋
if((x0==x &&(y0==y+1||y0==y-1)) || ((x0==x+1||x0==x-1)&&(y0==y))){ //判斷是否相鄰
remove();
}
else{
for (j=0;j<7;j++ ) {
if (grid[x0][j]==0){ //判斷第一個按鈕同行哪個按鈕為空
if (y>j) { //如果第二個按鈕的Y坐標大於空按鈕的Y坐標說明第一按鈕在第二按鈕左邊
for (i=y-1;i>=j;i-- ){ //判斷第二按鈕左側直到第一按鈕中間有沒有按鈕
if (grid[x][i]!=0) {
k=0;
break;
}
else{ k=1; } //K=1說明通過了第一次驗證
}
if (k==1) {
linePassOne();
}
}
if (y<j){ //如果第二個按鈕的Y坐標小於空按鈕的Y坐標說明第一按鈕在第二按鈕右邊
for (i=y+1;i<=j ;i++ ){ //判斷第二按鈕左側直到第一按鈕中間有沒有按鈕
if (grid[x][i]!=0){
k=0;
break;
}
else { k=1; }
}
if (k==1){
linePassOne();
}
}
if (y==j ) {
linePassOne();
}
}
if (k==2) {
if (x0==x) {
remove();
}
if (x0<x) {
for (n=x0;n<=x-1;n++ ) {
if (grid[n][j]!=0) {
k=0;
break;
}
if(grid[n][j]==0 && n==x-1) {
remove();
}
}
}
if (x0>x) {
for (n=x0;n>=x+1 ;n-- ) {
if (grid[n][j]!=0) {
k=0;
break;
}
if(grid[n][j]==0 && n==x+1) {
remove();
}
}
}
}
}
for (i=0;i<8;i++ ) { //列
if (grid[i][y0]==0) {
if (x>i) {
for (j=x-1;j>=i ;j-- ) {
if (grid[j][y]!=0) {
k=0;
break;
}
else { k=1; }
}
if (k==1) {
rowPassOne();
}
}
if (x<i) {
for (j=x+1;j<=i;j++ ) {
if (grid[j][y]!=0) {
k=0;
break;
}
else { k=1; }
}
if (k==1) {
rowPassOne();
}
}
if (x==i) {
rowPassOne();
}
}
if (k==2){
if (y0==y) {
remove();
}
if (y0<y) {
for (n=y0;n<=y-1 ;n++ ) {
if (grid[i][n]!=0) {
k=0;
break;
}
if(grid[i][n]==0 && n==y-1) {
remove();
}
}
}
if (y0>y) {
for (n=y0;n>=y+1 ;n--) {
if (grid[i][n]!=0) {
k=0;
break;
}
if(grid[i][n]==0 && n==y+1) {
remove();
}
}
}
}
}
}
}
public void linePassOne(){
if (y0>j){ //第一按鈕同行空按鈕在左邊
for (i=y0-1;i>=j ;i-- ){ //判斷第一按鈕同左側空按鈕之間有沒按鈕
if (grid[x0][i]!=0) {
k=0;
break;
}
else { k=2; } //K=2說明通過了第二次驗證
}
}
if (y0<j){ //第一按鈕同行空按鈕在與第二按鈕之間
for (i=y0+1;i<=j ;i++){
if (grid[x0][i]!=0) {
k=0;
break;
}
else{ k=2; }
}
}
}
public void rowPassOne(){
if (x0>i) {
for (j=x0-1;j>=i ;j-- ) {
if (grid[j][y0]!=0) {
k=0;
break;
}
else { k=2; }
}
}
if (x0<i) {
for (j=x0+1;j<=i ;j++ ) {
if (grid[j][y0]!=0) {
k=0;
break;
}
else { k=2; }
}
}
}
public void remove(){
firstButton.setVisible(false);
secondButton.setVisible(false);
fraction();
pressInformation=false;
k=0;
grid[x0][y0]=0;
grid[x][y]=0;
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==newlyButton){
int grid[][] = new int[8][7];
this.grid = grid;
randomBuild();
mainFrame.setVisible(false);
pressInformation=false;
init();
}
if(e.getSource()==exitButton)
System.exit(0);
if(e.getSource()==resetButton)
reload();
for(int cols = 0;cols < 6;cols++){
for(int rows = 0;rows < 5;rows++ ){
if(e.getSource()==diamondsButton[cols][rows])
estimateEven(cols+1,rows+1,diamondsButton[cols][rows]);
}
}
}
public static void main(String[] args) {
lianliankan llk = new lianliankan();
llk.randomBuild();
llk.init();
}
}

//old 998 lines
//new 318 lines

3. 幾個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;
}
}
我只有一個打字母小游戲

4. 給段最簡單的java代碼 讓我新手看一下

最簡單的java代碼肯定就是這個了,如下:
public class MyFirstApp
{
public static void main(String[] args)
{
System.out.print("Hello world");
}
}
「hello world」就是應該是所有學java的新手看的第一個代碼了。如果是零基礎的新手朋友們可以來我們的java實驗班試聽,有免費的試聽課程幫助學習java必備基礎知識,有助教老師為零基礎的人提供個人學習方案,學習完成後有考評團進行專業測試,幫助測評學員是否適合繼續學習java,15天內免費幫助來報名體驗實驗班的新手快速入門java,更好的學習java!

5. JAVA小游戲的線程簡單代碼 (兩個武士A、B對打)

首先寫個類命名people
public class people
{
//定義人有的屬性
int blood;//血
int force;//攻擊力
//定義構造方法對人進行初始化
public people(int blood,int force)
{
this.blood=blood;
this.force=force;
}
//定義人的方法,比如攻擊
public void attrack(people x)
{
x.blood-=this.force;

}
}

主體中代碼:

people a=new people(100,20);
people b=new people(100,30);
//建一個線程a攻擊b
xiancheng one=new xiancheng(a,b);
thread t1= new Thread(one);
t1.start();
//800毫秒後建一個線程b攻擊a;
thread.sleep(800);
xiancheng two=new xiancheng(b,a);
thread t2= new Thread(two);
t2.start();

class xiancheng implements runnable //繼承runnable介面
{
people x;
people y;
public xiancheng(people x,people y )
{
this.x=x;
this.y=y;
}

pulbic vid run()
{
while(y.blood>0)
{
x.attrack(y);
thread.sleep(800);
}
}
}
//很久沒用java了線程有點忘了,,汗

6. 用JAVA編一個小游戲或者其他程序

貪吃蛇程序:
GreedSnake.java (也是程序入口):

import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Iterator;
import java.util.LinkedList;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class GreedSnake implements KeyListener {
JFrame mainFrame;

Canvas paintCanvas;

JLabel labelScore;// 計分牌

SnakeModel snakeModel = null;// 蛇

public static final int canvasWidth = 200;

public static final int canvasHeight = 300;

public static final int nodeWidth = 10;

public static final int nodeHeight = 10;

// ----------------------------------------------------------------------
// GreedSnake():初始化游戲界面
// ----------------------------------------------------------------------
public GreedSnake() {
// 設置界面元素
mainFrame = new JFrame("GreedSnake");
Container cp = mainFrame.getContentPane();
labelScore = new JLabel("Score:");
cp.add(labelScore, BorderLayout.NORTH);
paintCanvas = new Canvas();
paintCanvas.setSize(canvasWidth + 1, canvasHeight + 1);
paintCanvas.addKeyListener(this);
cp.add(paintCanvas, BorderLayout.CENTER);
JPanel panelButtom = new JPanel();
panelButtom.setLayout(new BorderLayout());
JLabel labelHelp;// 幫助信息
labelHelp = new JLabel("PageUp, PageDown for speed;", JLabel.CENTER);
panelButtom.add(labelHelp, BorderLayout.NORTH);
labelHelp = new JLabel("ENTER or R or S for start;", JLabel.CENTER);
panelButtom.add(labelHelp, BorderLayout.CENTER);
labelHelp = new JLabel("SPACE or P for pause", JLabel.CENTER);
panelButtom.add(labelHelp, BorderLayout.SOUTH);
cp.add(panelButtom, BorderLayout.SOUTH);
mainFrame.addKeyListener(this);
mainFrame.pack();
mainFrame.setResizable(false);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
begin();
}

// ----------------------------------------------------------------------
// keyPressed():按鍵檢測
// ----------------------------------------------------------------------
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (snakeModel.running)
switch (keyCode) {
case KeyEvent.VK_UP:
snakeModel.changeDirection(SnakeModel.UP);
break;
case KeyEvent.VK_DOWN:
snakeModel.changeDirection(SnakeModel.DOWN);
break;
case KeyEvent.VK_LEFT:
snakeModel.changeDirection(SnakeModel.LEFT);
break;
case KeyEvent.VK_RIGHT:
snakeModel.changeDirection(SnakeModel.RIGHT);
break;
case KeyEvent.VK_ADD:
case KeyEvent.VK_PAGE_UP:
snakeModel.speedUp();// 加速
break;
case KeyEvent.VK_SUBTRACT:
case KeyEvent.VK_PAGE_DOWN:
snakeModel.speedDown();// 減速
break;
case KeyEvent.VK_SPACE:
case KeyEvent.VK_P:
snakeModel.changePauseState();// 暫停或繼續
break;
default:
}
// 重新開始
if (keyCode == KeyEvent.VK_R || keyCode == KeyEvent.VK_S
|| keyCode == KeyEvent.VK_ENTER) {
snakeModel.running = false;
begin();
}
}

// ----------------------------------------------------------------------
// keyReleased():空函數
// ----------------------------------------------------------------------
public void keyReleased(KeyEvent e) {
}

// ----------------------------------------------------------------------
// keyTyped():空函數
// ----------------------------------------------------------------------
public void keyTyped(KeyEvent e) {
}

// ----------------------------------------------------------------------
// repaint():繪制游戲界面(包括蛇和食物)
// ----------------------------------------------------------------------
void repaint() {
Graphics g = paintCanvas.getGraphics();
// draw background
g.setColor(Color.WHITE);
g.fillRect(0, 0, canvasWidth, canvasHeight);
// draw the snake
g.setColor(Color.BLACK);
LinkedList na = snakeModel.nodeArray;
Iterator it = na.iterator();
while (it.hasNext()) {
Node n = (Node) it.next();
drawNode(g, n);
}
// draw the food
g.setColor(Color.RED);
Node n = snakeModel.food;
drawNode(g, n);
updateScore();
}

// ----------------------------------------------------------------------
// drawNode():繪畫某一結點(蛇身或食物)
// ----------------------------------------------------------------------
private void drawNode(Graphics g, Node n) {
g.fillRect(n.x * nodeWidth, n.y * nodeHeight, nodeWidth - 1,
nodeHeight - 1);
}

// ----------------------------------------------------------------------
// updateScore():改變計分牌
// ----------------------------------------------------------------------
public void updateScore() {
String s = "Score: " + snakeModel.score;
labelScore.setText(s);
}

// ----------------------------------------------------------------------
// begin():游戲開始,放置貪吃蛇
// ----------------------------------------------------------------------
void begin() {
if (snakeModel == null || !snakeModel.running) {
snakeModel = new SnakeModel(this, canvasWidth / nodeWidth,
this.canvasHeight / nodeHeight);
(new Thread(snakeModel)).start();
}
}

// ----------------------------------------------------------------------
// main():主函數
// ----------------------------------------------------------------------
public static void main(String[] args) {
GreedSnake gs = new GreedSnake();
}
}

Node.java:

public class Node {

int x;

int y;

Node(int x, int y) {
this.x = x;
this.y = y;
}

}

SnakeModel.java:

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Random;

import javax.swing.JOptionPane;

public class SnakeModel implements Runnable {
GreedSnake gs;

boolean[][] matrix;// 界面數據保存在數組里

LinkedList nodeArray = new LinkedList();

Node food;

int maxX;// 最大寬度

int maxY;// 最大長度

int direction = 2;// 方向

boolean running = false;

int timeInterval = 200;// 間隔時間(速度)

double speedChangeRate = 0.75;// 速度改變程度

boolean paused = false;// 游戲狀態

int score = 0;

int countMove = 0;

// UP和DOWN是偶數,RIGHT和LEFT是奇數
public static final int UP = 2;

public static final int DOWN = 4;

public static final int LEFT = 1;

public static final int RIGHT = 3;

// ----------------------------------------------------------------------
// GreedModel():初始化界面
// ----------------------------------------------------------------------
public SnakeModel(GreedSnake gs, int maxX, int maxY) {
this.gs = gs;
this.maxX = maxX;
this.maxY = maxY;
matrix = new boolean[maxX][];
for (int i = 0; i < maxX; ++i) {
matrix[i] = new boolean[maxY];
Arrays.fill(matrix[i], false);// 沒有蛇和食物的地區置false
}
// 初始化貪吃蛇
int initArrayLength = maxX > 20 ? 10 : maxX / 2;
for (int i = 0; i < initArrayLength; ++i) {
int x = maxX / 2 + i;
int y = maxY / 2;
nodeArray.addLast(new Node(x, y));
matrix[x][y] = true;// 蛇身處置true
}
food = createFood();
matrix[food.x][food.y] = true;// 食物處置true
}

// ----------------------------------------------------------------------
// changeDirection():改變運動方向
// ----------------------------------------------------------------------
public void changeDirection(int newDirection) {
if (direction % 2 != newDirection % 2)// 避免沖突
{
direction = newDirection;
}
}

// ----------------------------------------------------------------------
// moveOn():貪吃蛇運動函數
// ----------------------------------------------------------------------
public boolean moveOn() {
Node n = (Node) nodeArray.getFirst();
int x = n.x;
int y = n.y;
switch (direction) {
case UP:
y--;
break;
case DOWN:
y++;
break;
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
}
if ((0 <= x && x < maxX) && (0 <= y && y < maxY)) {
if (matrix[x][y])// 吃到食物或者撞到身體
{
if (x == food.x && y == food.y)// 吃到食物
{
nodeArray.addFirst(food);// 在頭部加上一結點
// 計分規則與移動長度和速度有關
int scoreGet = (10000 - 200 * countMove) / timeInterval;
score += scoreGet > 0 ? scoreGet : 10;
countMove = 0;
food = createFood();
matrix[food.x][food.y] = true;
return true;
} else
return false;// 撞到身體
} else// 什麼都沒有碰到
{
nodeArray.addFirst(new Node(x, y));// 加上頭部
matrix[x][y] = true;
n = (Node) nodeArray.removeLast();// 去掉尾部
matrix[n.x][n.y] = false;
countMove++;
return true;
}
}
return false;// 越界(撞到牆壁)
}

// ----------------------------------------------------------------------
// run():貪吃蛇運動線程
// ----------------------------------------------------------------------
public void run() {
running = true;
while (running) {
try {
Thread.sleep(timeInterval);
} catch (Exception e) {
break;
}
if (!paused) {
if (moveOn())// 未結束
{
gs.repaint();
} else// 游戲結束
{
JOptionPane.showMessageDialog(null, "GAME OVER",
"Game Over", JOptionPane.INFORMATION_MESSAGE);
break;
}
}
}
running = false;
}

// ----------------------------------------------------------------------
// createFood():生成食物及放置地點
// ----------------------------------------------------------------------
private Node createFood() {
int x = 0;
int y = 0;
do {
Random r = new Random();
x = r.nextInt(maxX);
y = r.nextInt(maxY);
} while (matrix[x][y]);
return new Node(x, y);
}

// ----------------------------------------------------------------------
// speedUp():加快蛇運動速度
// ----------------------------------------------------------------------
public void speedUp() {
timeInterval *= speedChangeRate;
}

// ----------------------------------------------------------------------
// speedDown():放慢蛇運動速度
// ----------------------------------------------------------------------
public void speedDown() {
timeInterval /= speedChangeRate;
}

// ----------------------------------------------------------------------
// changePauseState(): 改變游戲狀態(暫停或繼續)
// ----------------------------------------------------------------------
public void changePauseState() {
paused = !paused;
}
}

7. 用Java編寫一個猜數字的游戲

新手炒瀝青初期需要投入多少資金?
我這邊是3W,最低沒有門檻,你就是入兩千都可以玩,但問題是兩千隻能操作1手,而且沒有抗風險資金了,你買了之後只要點位瞬間波動一個點你就直接平倉了,沒法玩的,所以我都是入金五萬以上玩的。

8. 如何學習JAVA,並求個簡單JAVA游戲代碼

學習Java可從下面做起:
1.繼續深入理解面向對象的含義。
2.java封裝,繼承和訪問機制,事件。輔助書籍:《java編程思想》,《java模式》。
3.jsp的基本應用,javascript的基本應用。輔助書籍:《Tomcat與Java Web開發技術詳解》
4.strust.輔助書籍:孫衛琴編著《精通Struts:基於MVC的Java Web設計與開發》
5.spring. 輔助書籍:《spring in action》
6.hibernate. 輔助書籍:《深入淺出Hibernate》、《精通Hibernate:Java對象持久化技術詳解》
7.j2ee 輔助書籍:《J2EE企業級應用開發》(電子工業出版社)
8.EJB 輔助書籍:《精通EJB(第三版)》
9.以上書籍可下電子書,但是電子的看久了蠻累,眼睛受不了。
10.補充:ORACLE一定要學好(SQL語句,存儲過程,觸發器)給你個簡單連連看代碼:import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class 連連看 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);
}
}
}

9. 急求簡單的手機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("游戲結束");
}

}

10. 求一個簡單的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相關的資料

熱點內容
卸載聯想app哪個好 瀏覽:719
php文字轉圖片 瀏覽:328
豆客後台怎麼加密碼 瀏覽:574
jpg轉換pdf破解版 瀏覽:978
php基礎書籍推薦 瀏覽:775
伺服器與外網不通如何驗證 瀏覽:351
電子版是不是就是文件夾 瀏覽:50
游戲屬性文件加密 瀏覽:462
如何讓安卓手機桌面圖標下移 瀏覽:528
ubuntuphp5環境搭建 瀏覽:99
賭癮解壓視頻 瀏覽:917
晉城移動dns伺服器地址 瀏覽:294
php開源文庫系統 瀏覽:134
android記事本源碼 瀏覽:407
安卓11小游戲怎麼玩法 瀏覽:189
gif有損壓縮 瀏覽:936
windows下安裝linux命令操作 瀏覽:843
米家app怎麼設置進門亮燈 瀏覽:652
任我行伺服器為什麼會影響截圖 瀏覽:296
安卓留言板怎麼刪除 瀏覽:18