java游戏编程小游戏代码(JAVA小游戏代码)

http://www.itjxue.com  2023-01-27 09:38  来源:未知  点击次数: 

求用JAVA编写俄罗斯方块游戏的源代码

俄罗斯方块——java源代码提供 import java.awt.*; import java.awt.event.*; //俄罗斯方块类 public class ERS_Block extends Frame{ public static boolean isPlay=false; public static int level=1,score=0; public static TextField scoreField,levelField; public static MyTimer timer; GameCanvas gameScr; public static void main(String[] argus){ ERS_Block ers = new ERS_Block("俄罗斯方块游戏 V1.0 Author:Vincent"); WindowListener win_listener = new WinListener(); ers.addWindowListener(win_listener); } //俄罗斯方块类的构造方法 ERS_Block(String title){ super(title); setSize(600,480); setLayout(new GridLayout(1,2)); gameScr = new GameCanvas(); gameScr.addKeyListener(gameScr); timer = new MyTimer(gameScr); timer.setDaemon(true); timer.start(); timer.suspend(); add(gameScr); Panel rightScr = new Panel(); rightScr.setLayout(new GridLayout(2,1,0,30)); rightScr.setSize(120,500); add(rightScr); //右边信息窗体的布局 MyPanel infoScr = new MyPanel(); infoScr.setLayout(new GridLayout(4,1,0,5)); infoScr.setSize(120,300); rightScr.add(infoScr); //定义标签和初始值 Label scorep = new Label("分数:",Label.LEFT); Label levelp = new Label("级数:",Label.LEFT); scoreField = new TextField(8); levelField = new TextField(8); scoreField.setEditable(false); levelField.setEditable(false); infoScr.add(scorep); infoScr.add(scoreField); infoScr.add(levelp); infoScr.add(levelField); scorep.setSize(new Dimension(20,60)); scoreField.setSize(new Dimension(20,60)); levelp.setSize(new Dimension(20,60)); levelField.setSize(new Dimension(20,60)); scoreField.setText("0"); levelField.setText("1"); //右边控制按钮窗体的布局 MyPanel controlScr = new MyPanel(); controlScr.setLayout(new GridLayout(5,1,0,5)); rightScr.add(controlScr); //定义按钮play Button play_b = new Button("开始游戏"); play_b.setSize(new Dimension(50,200)); play_b.addActionListener(new Command(Command.button_play,gameScr)); //定义按钮Level UP Button level_up_b = new Button("提高级数"); level_up_b.setSize(new Dimension(50,200)); level_up_b.addActionListener(new Command(Command.button_levelup,gameScr)); //定义按钮Level Down Button level_down_b =new Button("降低级数"); level_down_b.setSize(new Dimension(50,200)); level_down_b.addActionListener(new Command(Command.button_leveldown,gameScr)); //定义按钮Level Pause Button pause_b =new Button("游戏暂停"); pause_b.setSize(new Dimension(50,200)); pause_b.addActionListener(new Command(Command.button_pause,gameScr)); //定义按钮Quit Button quit_b = new Button("退出游戏"); quit_b.setSize(new Dimension(50,200)); quit_b.addActionListener(new Command(Command.button_quit,gameScr)); controlScr.add(play_b); controlScr.add(level_up_b); controlScr.add(level_down_b); controlScr.add(pause_b); controlScr.add(quit_b); setVisible(true); gameScr.requestFocus(); } } //重写MyPanel类,使Panel的四周留空间 class MyPanel extends Panel{ public Insets getInsets(){ return new Insets(30,50,30,50); } } //游戏画布类 class GameCanvas extends Canvas implements KeyListener{ final int unitSize = 30; //小方块边长 int rowNum; //正方格的行数 int columnNum; //正方格的列数 int maxAllowRowNum; //允许有多少行未削 int blockInitRow; //新出现块的起始行坐标 int blockInitCol; //新出现块的起始列坐标 int [][] scrArr; //屏幕数组 Block b; //对方快的引用 //画布类的构造方法 GameCanvas(){ rowNum = 15; columnNum = 10; maxAllowRowNum = rowNum - 2; b = new Block(this); blockInitRow = rowNum - 1; blockInitCol = columnNum/2 - 2; scrArr = new int [32][32]; } //初始化屏幕,并将屏幕数组清零的方法 void initScr(){ for(int i=0;irowNum;i++) for (int j=0; jcolumnNum;j++) scrArr[j]=0; b.reset(); repaint(); } //重新刷新画布方法 public void paint(Graphics g){ for(int i = 0; i rowNum; i++) for(int j = 0; j columnNum; j++) drawUnit(i,j,scrArr[j]); } //画方块的方法 public void drawUnit(int row,int col,int type){ scrArr[row][col] = type; Graphics g = getGraphics(); tch(type){ //表示画方快的方法 case 0: g.setColor(Color.black);break; //以背景为颜色画 case 1: g.setColor(Color.blue);break; //画正在下落的方块 case 2: g.setColor(Color.magenta);break; //画已经落下的方法 } g.fill3DRect(col*unitSize,getSize().height-(row+1)*unitSize,unitSize,unitSize,true); g.dispose(); } public Block getBlock(){ return b; //返回block实例的引用 } //返回屏幕数组中(row,col)位置的属性值 public int getScrArrXY(int row,int col){ if (row 0 || row = rowNum || col 0 || col = columnNum) return(-1); else return(scrArr[row][col]); } //返回新块的初始行坐标方法 public int getInitRow(){ return(blockInitRow); //返回新块的初始行坐标 } //返回新块的初始列坐标方法 public int getInitCol(){ return(blockInitCol); //返回新块的初始列坐标 } //满行删除方法 void deleteFullLine(){ int full_line_num = 0; int k = 0; for (int i=0;irowNum;i++){ boolean isfull = true; L1:for(int j=0;jcolumnNum;j++) if(scrArr[j] == 0){ k++; isfull = false; break L1; } if(isfull) full_line_num++; if(k!=0 k-1!=i !isfull) for(int j = 0; j columnNum; j++){ if (scrArr[j] == 0) drawUnit(k-1,j,0); else drawUnit(k-1,j,2); scrArr[k-1][j] = scrArr[j]; } } for(int i = k-1 ;i rowNum; i++){ for(int j = 0; j columnNum; j++){ drawUnit(i,j,0); scrArr[j]=0; } } ERS_Block.score += full_line_num; ERS_Block.scoreField.setText(""+ERS_Block.score); } //判断游戏是否结束方法 boolean isGameEnd(){ for (int col = 0 ; col columnNum; col ++){ if(scrArr[maxAllowRowNum][col] !=0) return true; } return false; } public void keyTyped(KeyEvent e){ } public void keyReleased(KeyEvent e){ } //处理键盘输入的方法 public void keyPressed(KeyEvent e){ if(!ERS_Block.isPlay) return; tch(e.getKeyCode()){ case KeyEvent.VK_DOWN:b.fallDown();break; case KeyEvent.VK_LEFT:b.leftMove();break; case KeyEvent.VK_RIGHT:b.rightMove();break; case KeyEvent.VK_SPACE:b.leftTurn();break; } } } //处理控制类 class Command implements ActionListener{ static final int button_play = 1; //给按钮分配编号 static final int button_levelup = 2; static final int button_leveldown = 3; static final int button_quit = 4; static final int button_pause = 5; static boolean pause_resume = true; int curButton; //当前按钮 GameCanvas scr; //控制按钮类的构造方法 Command(int button,GameCanvas scr){ curButton = button; this.scr=scr; } //按钮执行方法 public void actionPerformed (ActionEvent e){ tch(curButton){ case button_play:if(!ERS_Block.isPlay){ scr.initScr(); ERS_Block.isPlay = true; ERS_Block.score = 0; ERS_Block.scoreField.setText("0"); ERS_Block.timer.resume(); } scr.requestFocus(); break; case button_levelup:if(ERS_Block.level 10){ ERS_Block.level++; ERS_Block.levelField.setText(""+ERS_Block.level); ERS_Block.score = 0; ERS_Block.scoreField.setText(""+ERS_Block.score); } scr.requestFocus(); break; case button_leveldown:if(ERS_Block.level 1){ ERS_Block.level--; ERS_Block.levelField.setText(""+ERS_Block.level); ERS_Block.score = 0; ERS_Block.scoreField.setText(""+ERS_Block.score); } scr.requestFocus(); break; case button_pause:if(pause_resume){ ERS_Block.timer.suspend(); pause_resume = false; }else{ ERS_Block.timer.resume(); pause_resume = true; } scr.requestFocus(); break; case button_quit:System.exit(0); } } } //方块类 class Block { static int[][] pattern = { {0x0f00,0x4444,0x0f00,0x4444},//用十六进至表示,本行表示长条四种状态 {0x04e0,0x0464,0x00e4,0x04c4}, {0x4620,0x6c00,0x4620,0x6c00}, {0x2640,0xc600,0x2640,0xc600}, {0x6220,0x1700,0x2230,0x0740}, {0x6440,0x0e20,0x44c0,0x8e00}, {0x0660,0x0660,0x0660,0x0660} }; int blockType; //块的模式号(0-6) int turnState; //块的翻转状态(0-3) int blockState; //快的下落状态 int row,col; //块在画布上的坐标 GameCanvas scr; //块类的构造方法 Block(GameCanvas scr){ this.scr = scr; blockType = (int)(Math.random() * 1000)%7; turnState = (int)(Math.random() * 1000)%4; blockState = 1; row = scr.getInitRow(); col = scr.getInitCol(); } //重新初始化块,并显示新块 public void reset(){ blockType = (int)(Math.random() * 1000)%7; turnState = (int)(Math.random() * 1000)%4; blockState = 1; row = scr.getInitRow(); col = scr.getInitCol(); dispBlock(1); } //实现“块”翻转的方法 public void leftTurn(){ if(assertValid(blockType,(turnState + 1)%4,row,col)){ dispBlock(0); turnState = (turnState + 1)%4; dispBlock(1); } } //实现“块”的左移的方法 public void leftMove(){ if(assertValid(blockType,turnState,row,col-1)){ dispBlock(0); col--; dispBlock(1); } } //实现块的右移 public void rightMove(){ if(assertValid(blockType,turnState,row,col+1)){ dispBlock(0); col++; dispBlock(1); } } //实现块落下的操作的方法 public boolean fallDown(){ if(blockState == 2) return(false); if(assertValid(blockType,turnState,row-1,col)){ dispBlock(0); row--; dispBlock(1); return(true); }else{ blockState = 2; dispBlock(2); return(false); } } //判断是否正确的方法 boolean assertValid(int t,int s,int row,int col){ int k = 0x8000; for(int i = 0; i 4; i++){ for(int j = 0; j 4; j++){ if((int)(pattern[t][s]k) != 0){ int temp = scr.getScrArrXY(row-i,col+j); if (temp0||temp==2) return false; } k = k 1; } } return true; } //同步显示的方法 public synchronized void dispBlock(int s){ int k = 0x8000; for (int i = 0; i 4; i++){ for(int j = 0; j 4; j++){ if(((int)pattern[blockType][turnState]k) != 0){ scr.drawUnit(row-i,col+j,s); } k=k1; } } } } //定时线程 class MyTimer extends Thread{ GameCanvas scr; public MyTimer(GameCanvas scr){ this.scr = scr; } public void run(){ while(true){ try{ sleep((10-ERS_Block.level + 1)*100); } catch(InterruptedException e){} if(!scr.getBlock().fallDown()){ scr.deleteFullLine(); if(scr.isGameEnd()){ ERS_Block.isPlay = false; suspend(); }else scr.getBlock().reset(); } } } } class WinListener extends WindowAdapter{ public void windowClosing (WindowEvent l){ System.exit(0); } } 22

求java小游戏源代码

表1. CheckerDrag.java

// CheckerDrag.javaimport java.awt.*;import java.awt.event.*;public class CheckerDrag extends java.applet.Applet{ // Dimension of checkerboard square. // 棋盘上每个小方格的尺寸 final static int SQUAREDIM = 40; // Dimension of checkerboard -- includes black outline. // 棋盘的尺寸 – 包括黑色的轮廓线 final static int BOARDDIM = 8 * SQUAREDIM + 2; // Dimension of checker -- 3/4 the dimension of a square. // 棋子的尺寸 – 方格尺寸的3/4 final static int CHECKERDIM = 3 * SQUAREDIM / 4; // Square colors are dark green or white. // 方格的颜色为深绿色或者白色 final static Color darkGreen = new Color (0, 128, 0); // Dragging flag -- set to true when user presses mouse button over checker // and cleared to false when user releases mouse button. // 拖动标记 --当用户在棋子上按下鼠标按键时设为true, // 释放鼠标按键时设为false boolean inDrag = false; // Left coordinate of checkerboard's upper-left corner. // 棋盘左上角的左方向坐标 int boardx; // Top coordinate of checkerboard's upper-left corner. //棋盘左上角的上方向坐标 int boardy; // Left coordinate of checker rectangle origin (upper-left corner). // 棋子矩形原点(左上角)的左方向坐标 int ox; // Top coordinate of checker rectangle origin (upper-left corner). // 棋子矩形原点(左上角)的上方向坐标 int oy; // Left displacement between mouse coordinates at time of press and checker // rectangle origin. // 在按键时的鼠标坐标与棋子矩形原点之间的左方向位移 int relx; // Top displacement between mouse coordinates at time of press and checker // rectangle origin. // 在按键时的鼠标坐标与棋子矩形原点之间的上方向位移 int rely; // Width of applet drawing area. // applet绘图区域的宽度 int width; // Height of applet drawing area. // applet绘图区域的高度 int height; // Image buffer. // 图像缓冲 Image imBuffer; // Graphics context associated with image buffer. // 图像缓冲相关联的图形背景 Graphics imG; public void init () { // Obtain the size of the applet's drawing area. // 获取applet绘图区域的尺寸 width = getSize ().width; height = getSize ().height; // Create image buffer. // 创建图像缓冲 imBuffer = createImage (width, height); // Retrieve graphics context associated with image buffer. // 取出图像缓冲相关联的图形背景 imG = imBuffer.getGraphics (); // Initialize checkerboard's origin, so that board is centered. // 初始化棋盘的原点,使棋盘在屏幕上居中 boardx = (width - BOARDDIM) / 2 + 1; boardy = (height - BOARDDIM) / 2 + 1; // Initialize checker's rectangle's starting origin so that checker is // centered in the square located in the top row and second column from // the left. // 初始化棋子矩形的起始原点,使得棋子在第一行左数第二列的方格里居中 ox = boardx + SQUAREDIM + (SQUAREDIM - CHECKERDIM) / 2 + 1; oy = boardy + (SQUAREDIM - CHECKERDIM) / 2 + 1; // Attach a mouse listener to the applet. That listener listens for // mouse-button press and mouse-button release events. // 向applet添加一个用来监听鼠标按键的按下和释放事件的鼠标监听器 addMouseListener (new MouseAdapter () { public void mousePressed (MouseEvent e) { // Obtain mouse coordinates at time of press. // 获取按键时的鼠标坐标 int x = e.getX (); int y = e.getY (); // If mouse is over draggable checker at time // of press (i.e., contains (x, y) returns // true), save distance between current mouse // coordinates and draggable checker origin // (which will always be positive) and set drag // flag to true (to indicate drag in progress). // 在按键时如果鼠标位于可拖动的棋子上方 // (也就是contains (x, y)返回true),则保存当前 // 鼠标坐标与棋子的原点之间的距离(始终为正值)并且 // 将拖动标志设为true(用来表明正处在拖动过程中) if (contains (x, y)) { relx = x - ox; rely = y - oy; inDrag = true; } } boolean contains (int x, int y) { // Calculate center of draggable checker. // 计算棋子的中心位置 int cox = ox + CHECKERDIM / 2; int coy = oy + CHECKERDIM / 2; // Return true if (x, y) locates with bounds // of draggable checker. CHECKERDIM / 2 is the // radius. // 如果(x, y)仍处于棋子范围内则返回true // CHECKERDIM / 2为半径 return (cox - x) * (cox - x) + (coy - y) * (coy - y) CHECKERDIM / 2 * CHECKERDIM / 2; } public void mouseReleased (MouseEvent e) { // When mouse is released, clear inDrag (to // indicate no drag in progress) if inDrag is // already set. // 当鼠标按键被释放时,如果inDrag已经为true, // 则将其置为false(用来表明不在拖动过程中) if (inDrag) inDrag = false; } }); // Attach a mouse motion listener to the applet. That listener listens // for mouse drag events. //向applet添加一个用来监听鼠标拖动事件的鼠标运动监听器 addMouseMotionListener (new MouseMotionAdapter () { public void mouseDragged (MouseEvent e) { if (inDrag) { // Calculate draggable checker's new // origin (the upper-left corner of // the checker rectangle). // 计算棋子新的原点(棋子矩形的左上角) int tmpox = e.getX () - relx; int tmpoy = e.getY () - rely; // If the checker is not being moved // (at least partly) off board, // assign the previously calculated // origin (tmpox, tmpoy) as the // permanent origin (ox, oy), and // redraw the display area (with the // draggable checker at the new // coordinates). // 如果棋子(至少是棋子的一部分)没有被 // 移出棋盘,则将之前计算的原点 // (tmpox, tmpoy)赋值给永久性的原点(ox, oy), // 并且刷新显示区域(此时的棋子已经位于新坐标上) if (tmpox boardx tmpoy boardy tmpox + CHECKERDIM boardx + BOARDDIM tmpoy + CHECKERDIM boardy + BOARDDIM) { ox = tmpox; oy = tmpoy; repaint (); } } } }); } public void paint (Graphics g) { // Paint the checkerboard over which the checker will be dragged. // 在棋子将要被拖动的位置上绘制棋盘 paintCheckerBoard (imG, boardx, boardy); // Paint the checker that will be dragged. // 绘制即将被拖动的棋子 paintChecker (imG, ox, oy); // Draw contents of image buffer. // 绘制图像缓冲的内容 g.drawImage (imBuffer, 0, 0, this); } void paintChecker (Graphics g, int x, int y) { // Set checker shadow color. // 设置棋子阴影的颜色 g.setColor (Color.black); // Paint checker shadow. // 绘制棋子的阴影 g.fillOval (x, y, CHECKERDIM, CHECKERDIM); // Set checker color. // 设置棋子颜色 g.setColor (Color.red); // Paint checker. // 绘制棋子 g.fillOval (x, y, CHECKERDIM - CHECKERDIM / 13, CHECKERDIM - CHECKERDIM / 13); } void paintCheckerBoard (Graphics g, int x, int y) { // Paint checkerboard outline. // 绘制棋盘轮廓线 g.setColor (Color.black); g.drawRect (x, y, 8 * SQUAREDIM + 1, 8 * SQUAREDIM + 1); // Paint checkerboard. // 绘制棋盘 for (int row = 0; row 8; row++) { g.setColor (((row 1) != 0) ? darkGreen : Color.white); for (int col = 0; col 8; col++) { g.fillRect (x + 1 + col * SQUAREDIM, y + 1 + row * SQUAREDIM, SQUAREDIM, SQUAREDIM); g.setColor ((g.getColor () == darkGreen) ? Color.white : darkGreen); } } } // The AWT invokes the update() method in response to the repaint() method // calls that are made as a checker is dragged. The default implementation // of this method, which is inherited from the Container class, clears the // applet's drawing area to the background color prior to calling paint(). // This clearing followed by drawing causes flicker. CheckerDrag overrides // update() to prevent the background from being cleared, which eliminates // the flicker. // AWT调用了update()方法来响应拖动棋子时所调用的repaint()方法。该方法从 // Container类继承的默认实现会在调用paint()之前,将applet的绘图区域清除 // 为背景色,这种绘制之后的清除就导致了闪烁。CheckerDrag重写了update()来 // 防止背景被清除,从而消除了闪烁。 public void update (Graphics g) { paint (g); }}

java程序编写小游戏 要求:程序随机产生20—50根火柴

为什么用AWT不用 swing?

算法思想很简单

是取胜原理

用反推法:欲拿最后一根,必须留2根在那里,欲留2根,必须上一轮留2+3+1=6给对方,(它拿一,你拿三,它拿二,你拿二,它拿三,你拿一。都是留2根)。再向上一轮,就是6+4=10。

取胜原理:把随机产生的火柴数,分解成:2+4的n次方+m,(m≤3),当m=0的时候,后取者胜,当m=1、2、3的时候,先取者胜。先取者取完m,留2+4的n次方给对方,对方不管取多少,你取的数和对方相加等于4,一直到最后,留2根给对方,根据规则,对方只能取一根,留一根给你取胜。

另:取完者胜(含最后一根):最后留4根给对方,不管对方取多少,你都可以一次取完。上一轮同样加4。

取胜原理:把随机产生的火柴数,分解成:4的n次方+m,(m≤3),当m=0的时候,后取者胜,当m=1、2、3的时候,先取者胜。先取者取完m,留4的n次方给对方,对方不管取多少,你取的数和对方相加等于4,一直到最后,留4根给对方。

代码调试可用

自己用GUI搭个界面 二十分钟的事

import java.util.Scanner;

public class MatchGame {

private static Scanner scanner = new Scanner(System.in);;

private int total;

private Computer com;

private static int exit = 1;

public MatchGame(int from, int to, String level) {

if (from = to) {

throw new IllegalArgumentException();

}

total = (int)( Math.random() * (to - from)) + from;

com = new Computer(level);

}

public void start() {

System.out.println("0 means endGame, 4 means restartGame!");

System.out.println("The number of matches is " + total);

System.out.println("~Start~");

System.out.println("----------------------------------------");

while (true) {

int u = scanner.nextInt();

if (u 0 u 4) {

System.out.println("You entered " + u);

if (total - u = 0) {

exit = 2;

endGame();

}

total = total - u;

System.out.println("Total : " + total);

int c = com.play(u, total);

System.out.println("Computer selected " + c + " matches~");

if (total - c = 0) {

exit = 0;

endGame();

}

total = total - c;

System.out.println("Total : " + total);

}else if (u == 0) {

endGame();

}else if (u 4 || u 0) {

System.out.println("You entered Wrong number~");

} else {

restart();

}

}

}

public static void restart() {

MatchGame game;

System.out

.println("Please select Computer Level: 1:HARD 2:NORMAL 3:EASY");

int level = scanner.nextInt();

if (level == 1) {

game = new MatchGame(20, 50, Computer.HARD);

} else if (level == 2) {

game = new MatchGame(20, 50, Computer.NORMAL);

} else {

game = new MatchGame(20, 50, Computer.EASY);

}

game.start();

}

public static void endGame() {

if (exit == 0) {

System.out.println("YOU WIN!!!");

} else if (exit == 2) {

System.out.println("YOU LOSE!!!");

}

System.exit(exit);

}

public static class Computer {

private static String EASY = "EASY";

private static String NORMAL = "NORMAL";

private static String HARD = "HARD";

private static String LEVEL;

private int com;

public Computer(String level) {

LEVEL = level;

}

public int play(int user, int total) {

if (LEVEL.equals(EASY)) {

com = 1;

} else if (LEVEL.equals(NORMAL)) {

com = (int) (Math.random() * 2) + 1;

} else {

int i;

if (total % 4 == 0) {

i = total / 4 - 1;

} else {

i = total / 4;

}

com = total - 4 * i - 1;

if (com == 0) {

com = 4 - user;

}

}

return com;

}

}

public static void main(String[] args) {

MatchGame game;

System.out

.println("Please select Computer Level: 1:HARD 2:NORMAL 3:EASY");

int level = scanner.nextInt();

if (level == 1) {

game = new MatchGame(20, 50, Computer.HARD);

} else if (level == 2) {

game = new MatchGame(20, 50, Computer.NORMAL);

} else {

game = new MatchGame(20, 50, Computer.EASY);

}

game.start();

}

}

用java编写一个猜数字游戏,

package?day06;

import?java.util.Scanner;

//猜字符游戏

public?class?GuessingGame?{

//主方法

public?static?void?main(String[]?args)?{

Scanner?scan?=?new?Scanner(System.in);

int?count?=?0;?//猜错的次数

char[]?chs?=?generate();?//随机生成的字符数组

System.out.println(chs);?//作弊

while(true){?//自造死循环

System.out.println("猜吧!");

String?str?=?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

int?score?=?chs.length*100?-?count*10;?//一个字符100分,错一次减10分

System.out.println("恭喜你猜对了,得分:"?+?score);

break;?//猜对时跳出循环

}else{?//没猜对

count++;?//猜错次数增1

System.out.println("字符对:"+result[1]+"个,位置对:"+result[0]+"个");

}

}

}

//随机生成5个字符数组

public?static?char[]?generate(){

char[]?chs?=?new?char[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?=?new?boolean[letters.length];?//1.

for(int?i=0;ichs.length;i++){

int?index;

do{

index?=?(int)(Math.random()*letters.length);?//0到25

}while(flags[index]==true);?//2.

chs[i]?=?letters[index];

flags[index]?=?true;?//3.

}

return?chs;

}

//对比随机数组与用户输入的数组

public?static?int[]?check(char[]?chs,char[]?input){

int[]?result?=?new?int[2];

for(int?i=0;ichs.length;i++){

for(int?j=0;jinput.length;j++){

if(chs[i]==input[j]){?//字符对

result[1]++;?//字符对个数增1

if(i==j){?//位置对

result[0]++;?//位置对个数增1

}

break;

}

}

}

return?result;

}

}

JAVA小游戏程序代码

这个是比较有名的那个烟花,不知道你有没有用:

建个工程,以Fireworks为类即可

import java.awt.*;

import java.applet.*;

import java.awt.event.*;

import javax.swing.*;

public class Fireworks extends Applet implements MouseListener,Runnable

{

int x,y;

int top,point;

/**

*对小程序进行变量和颜色的初始化。

*/

public void init()

{

x = 0;

y = 0;

//设置背景色为黑色

setBackground(Color.black);

addMouseListener(this);

}

public void paint(Graphics g)

{

}

/**

*使该程序可以作为应用程序运行。

*/

public static void main(String args[]) {

Fireworks applet = new Fireworks();

JFrame frame = new JFrame("TextAreaNew");

frame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e){

System.exit(0);

}

});

frame.getContentPane().add(

applet, BorderLayout.CENTER);

frame.setSize(800,400);

applet.init();

applet.start();

frame.setVisible(true);

}

/**

*程序主线程,对一个烟花进行绘制。

*/

public void run()

{

//变量初始化

Graphics g1;

g1 = getGraphics();

int y_move,y_click,x_click;

int v;

x_click = x;

y_click = y;

y_move = 400;

v = 3;

int r,g,b;

while(y_move y_click)

{

g1.setColor(Color.black);

g1.fillOval(x_click,y_move,5,5);

y_move -= 5;

r = (((int)Math.round(Math.random()*4321))%200)+55;

g = (((int)Math.round(Math.random()*4321))%200)+55;

b = (((int)Math.round(Math.random()*4321))%200)+55;

g1.setColor(new Color(r,g,b));

g1.fillOval(x_click,y_move,5,5);

for(int j = 0 ;j=10;j++)

{

if(r55) r -= 20;

if(g55) g -= 20;

if(b55) b -=20;

g1.setColor(new Color(r,g,b));

g1.fillOval(x_click,y_move+j*5,5,5);

}

g1.setColor(Color.black);

g1.fillOval(x_click,y_move+5*10,5,5);

try

{

Thread.currentThread().sleep(v++);

} catch (InterruptedException e) {}

}

for(int j=12;j=0;j--)

{

g1.setColor(Color.black);

g1.fillOval(x_click,y_move+(j*5),5,5);

try

{

Thread.currentThread().sleep((v++)/3);

} catch (InterruptedException e) {}

}

y_move = 400;

g1.setColor(Color.black);

while(y_move y_click)

{

g1.fillOval(x_click-2,y_move,9,5);

y_move -= 5;

}

v = 15;

for(int i=0;i=25;i++)

{

r = (((int)Math.round(Math.random()*4321))%200)+55;

g = (((int)Math.round(Math.random()*4321))%200)+55;

b = (((int)Math.round(Math.random()*4321))%200)+55;

g1.setColor(new Color(r,g,b));

g1.drawOval(x_click-3*i,y_click-3*i,6*i,6*i);

if(i23)

{

g1.drawOval(x_click-3*(i+1),y_click-3*(i+1),6*(i+1),6*(i+1));

g1.drawOval(x_click-3*(i+2),y_click-3*(i+2),6*(i+2),6*(i+2));

}

try

{

Thread.currentThread().sleep(v++);

} catch (InterruptedException e) {}

g1.setColor(Color.black);

g1.drawOval(x_click-3*i,y_click-3*i,6*i,6*i);

}

}

/**

*对鼠标事件进行监听。

*临听其鼠标按下事件。

*当按下鼠标时,产生一个新线程。

*/

public void mousePressed(MouseEvent e)

{

x = e.getX();

y = e.getY();

Thread one;

one = new Thread(this);

one.start();

one = null;

}

/**

*实现MouseListener接中的方法。为一个空方法。

*/

public void mouseReleased(MouseEvent e)

{

}

/**

*实现MouseListener接中的方法。为一个空方法。

*/

public void mouseEntered(MouseEvent e)

{

}

/**

*实现MouseListener接中的方法。为一个空方法。

*/

public void mouseExited(MouseEvent e)

{

}

/**

*实现MouseListener接中的方法。为一个空方法。

*/

public void mouseClicked(MouseEvent e)

{

}

}

java游戏编程1A2B是一款十分经典的猜数字游戏,每局开始,计算机都会随机生成四个数字?

package com.test;

import java.util.Random;

import java.util.Scanner;

/**

* 我的测试类

*

* @author 刘逸晖

*

*/

public class MyTest {

/**

* 生成不同的正整数随机数,返回字符串数组

*

* @param count

* 需要生成随机数的数量

* @param max

* 随机数的最大值

* @param min

* 随机数的最小值

* @return 生成的随机数

*/

private static String[] generateRandomNumber(int count, int min, int max) {

if (count 0 min -1 max min) {

String[] numbers = new String[count];

Random random = new Random();

// 生成随机数。

for (int i = 0; i numbers.length; i++) {

numbers[i] = min + random.nextInt(max - min) + "";

}

// 检查是否存在重复的随机数。

int equalIndex = areEqual(numbers);

while (equalIndex != -1) {

numbers[equalIndex] = min + random.nextInt(max - min) + "";

equalIndex = areEqual(numbers);

}

return numbers;

} else {// 参数不合法。

return null;

}

}

/**

* 判断字符串数组中的元素是否存在相等的

*

* @param array

* 预判断的数组

* @return 如果数组中有相等的元素,返回其下标;如果数组中没有相等的元素,或数组为空返回-1

*/

private static int areEqual(String[] array) {

if (array != null array.length 0) {

// 将数组中的每一个成员与其之前的所有成员进行比较,判断是否有相等的。

for (int current = 0; current array.length; current++) {

// 将当前便利的数组成员与其之前的所有成员进行比较,判断是否有相等的。

for (int previous = 0; previous current; previous++) {

if (array[current].equals(array[previous])) {

return previous;

}

}

}

}

return -1;

}

/**

* 搜索字符串数组

*

* @param array

* 数组

* @param value

* 预搜索的值

* @return 如果数组中有成员的值与预搜索的值相等返回成员下标,否则返回-1

*/

private static int search(String[] array, String value) {

if (array != null array.length -1 value != null) {

for (int i = 0; i array.length; i++) {

if (array[i].equals(value)) {

return i;

}

}

}

return -1;

}

public static void main(String[] args) {

System.out.println("欢迎你来到1a2b,输入n退出,输入y重新开始");

System.out.println("系统会随机产生4个0到9之间不同的数字,请你来猜");

System.out.println("输出a不仅代表你猜中了,还代表你猜对它的位置了哦!\r\n输出b则代表你猜中了,但位置不对哦");

// 开始循环,一次循环代表一局游戏。一局结束后立刻开启下一局。

while (true) {

System.out.println("新的一局开始了!");

// 产生随机数。

String[] randomNumbers = generateRandomNumber(4, 0, 9);

Scanner scanner = new Scanner(System.in);

// 创建变量存放输入记录。

String[] records = new String[] { "", "", "", "" };

// 创建变量存放ab结果。

String result = "";

// 请用户输入4次值。为什么请用户输入4次?因为数组中有4个成员。

for (int i = 0; i randomNumbers.length; i++) {

// 获得输入的值。

String inputValue = scanner.nextLine();

// 判断是否需要退出。

if (inputValue.equals("n") || inputValue.equals("")) {

System.out.println("Goodbye");

return;

}

// 创建变量定义是否忽略本次输入。

boolean ignore = false;

// 判断是否需要重新开始。

if (inputValue.equals("y")) {

ignore = true;

i = randomNumbers.length;

}

// 判断是否重复输入。

for (String record : records) {

if (inputValue.equals(record)) {

ignore = true;

i--;

System.out.println("这个值你已经输入过了哦!\r\n在给你一次机会。");

continue;

}

}

if (ignore) {

continue;

}

// 对输入的值进行搜索。

int searchResult = search(randomNumbers, inputValue);

// 如果搜索到了相关的值。

if (searchResult -1) {

// 记录。

records[i] = inputValue;

// 不仅搜索到了输入的值,并且位置正确。

if (searchResult == i) {

result = result + "a";

System.out.println("a");

} else {// 搜索到了输入的值,但位置错误。

result = result + "b";

System.out.println("b");

}

} else {// 输入错误。

System.out.println("这里没有这个值哦!\r\n再给你一次机会!");

i--;

}

}

System.out.println(result);

}

}

}

(责任编辑:IT教学网)

更多

推荐数据库文章