import javaawt;
import javaawtevent;
import javaapplet;
import javaio;
public class testframe extends Frame implements ActionListener
{
Button b1;
Panel p1;
Label text1;
TextField text2;
TextArea text3;
int num[];
int i;
String str;
int times=0;
int A,B;
public testframe(String str)
{
b1=new Button("确定");
p1=new Panel();
text1=new Label("输入四位整数:");
text2=new TextField(10);
text3=new TextArea(10,10);
p1setLayout(null);
p1setBackground(ColorGRAY);
setSize(300,300);
setVisible(true);
b1setBackground(ColorBLUE);
b1setForeground(ColorWHITE);
b1setSize(80,30);
p1add(text1);
p1add(text2);
p1add(text3);
p1add(b1);
text1setBounds(0,0,100,20);
text2setBounds(0,2text1getBounds()height,150,20);
text3setBounds(0,3text1getBounds()height,150,150);
b1setBounds(200,50,60,30);
add(p1);
b1addActionListener(this);
addWindowListener(new shut());
}
public void rand()
{ num=new int[10];
for(i=0;i<4;i++)
{
num[i]=(int)(Mathrandom()10);
int j=0;
while(j<i)
{if(num[j]==num[i])
{num[i]=(int)(Mathrandom()10);
continue;
}
j++;
}
}
}
public void compair()
{
int x,m,n;
x=IntegerparseInt(text2getText());
A=0;B=0;
for(m=3;m>-1;m--){
for(n=0;n<4;n++){
if((int)(x/Mathpow(10,m))==num[n])
{
if(m+n==3)
A++;
else
B++;
}
}
x=x-(int)(x/Mathpow(10,m))(int)(Mathpow(10,m));
}
}
public void actionPerformed(ActionEvent e)
{
if(egetSource()==b1)
if(times<5){
if(IntegerparseInt(text2getText())<1000||IntegerparseInt(text2getText())>9999)
text2setText("输入数字不合法");
else
{ if(A==4)
text2setText("猜对了");
times++;
compair();
text3append("第");
text3append(StringvalueOf(times));
text3append("猜的结果是:");
text3append(StringvalueOf(A));text3append("A");
text3append(StringvalueOf(B));text3append("B");
text3append("\n");
}
}
else
{
text3setText("超过5次,重新开始\n");
times=0;
rand();
}
}
public static void main(String[] args)
{
new testframe("窗口程序");
}
}
class shut extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
Systemexit(0);
}
}
表1 CheckerDragjava
// CheckerDragjavaimport javaawt;import javaawtevent;public class CheckerDrag extends javaappletApplet{ // 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 = imBuffergetGraphics (); // 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 = egetX (); int y = egetY (); // If mouse is over draggable checker at time // of press (ie, 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 = egetX () - relx; int tmpoy = egetY () - 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 // 绘制图像缓冲的内容 gdrawImage (imBuffer, 0, 0, this); } void paintChecker (Graphics g, int x, int y) { // Set checker shadow color // 设置棋子阴影的颜色 gsetColor (Colorblack); // Paint checker shadow // 绘制棋子的阴影 gfillOval (x, y, CHECKERDIM, CHECKERDIM); // Set checker color // 设置棋子颜色 gsetColor (Colorred); // Paint checker // 绘制棋子 gfillOval (x, y, CHECKERDIM - CHECKERDIM / 13, CHECKERDIM - CHECKERDIM / 13); } void paintCheckerBoard (Graphics g, int x, int y) { // Paint checkerboard outline // 绘制棋盘轮廓线 gsetColor (Colorblack); gdrawRect (x, y, 8 SQUAREDIM + 1, 8 SQUAREDIM + 1); // Paint checkerboard // 绘制棋盘 for (int row = 0; row < 8; row++) { gsetColor (((row & 1) != 0) darkGreen : Colorwhite); for (int col = 0; col < 8; col++) { gfillRect (x + 1 + col SQUAREDIM, y + 1 + row SQUAREDIM, SQUAREDIM, SQUAREDIM); gsetColor ((ggetColor () == darkGreen) Colorwhite : 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); }}
import javaawt;
import javaawtevent;
import javaxswing;
import javautil;
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;
public GreedSnake() {
mainFrame = new JFrame("GreedSnake");
Container cp = mainFramegetContentPane();
labelScore = new JLabel("Score:");
cpadd(labelScore, BorderLayoutNORTH);
paintCanvas = new Canvas();
paintCanvassetSize(canvasWidth+1,canvasHeight+1);
paintCanvasaddKeyListener(this);
cpadd(paintCanvas, BorderLayoutCENTER);
JPanel panelButtom = new JPanel();
panelButtomsetLayout(new BorderLayout());
JLabel labelHelp;
labelHelp = new JLabel("PageUp, PageDown for speed;", JLabelCENTER);
panelButtomadd(labelHelp, BorderLayoutNORTH);
labelHelp = new JLabel("ENTER or R or S for start;", JLabelCENTER);
panelButtomadd(labelHelp, BorderLayoutCENTER);
labelHelp = new JLabel("SPACE or P for pause",JLabelCENTER);
panelButtomadd(labelHelp, BorderLayoutSOUTH);
cpadd(panelButtom,BorderLayoutSOUTH);
mainFrameaddKeyListener(this);
mainFramepack();
mainFramesetResizable(false);
mainFramesetDefaultCloseOperation(JFrameEXIT_ON_CLOSE);
mainFramesetVisible(true);
begin();
}
public void keyPressed(KeyEvent e){
int keyCode = egetKeyCode();
if (snakeModelrunning)
switch(keyCode){
case KeyEventVK_UP:
snakeModelchangeDirection(SnakeModelUP);
break;
case KeyEventVK_DOWN:
snakeModelchangeDirection(SnakeModelDOWN);
break;
case KeyEventVK_LEFT:
snakeModelchangeDirection(SnakeModelLEFT);
break;
case KeyEventVK_RIGHT:
snakeModelchangeDirection(SnakeModelRIGHT);
break;
case KeyEventVK_ADD:
case KeyEventVK_PAGE_UP:
snakeModelspeedUp();
break;
case KeyEventVK_SUBTRACT:
case KeyEventVK_PAGE_DOWN:
snakeModelspeedDown();
break;
case KeyEventVK_SPACE:
case KeyEventVK_P:
snakeModelchangePauseState();
break;
default:
}
if (keyCode == KeyEventVK_R ||
keyCode == KeyEventVK_S ||
keyCode == KeyEventVK_ENTER){
snakeModelrunning = false;
begin();
}
}
public void keyReleased(KeyEvent e){
}
public void keyTyped(KeyEvent e){
}
void repaint(){
Graphics g = paintCanvasgetGraphics();
//draw background
gsetColor(ColorWHITE);
gfillRect(0,0,canvasWidth,canvasHeight);
// draw the snake
gsetColor(ColorBLACK);
LinkedList na = snakeModelnodeArray;
Iterator it = naiterator();
while(ithasNext()){
Node n = (Node)itnext();
drawNode(g,n);
}
// draw the food
gsetColor(ColorRED);
Node n = snakeModelfood;
drawNode(g,n);
updateScore();
}
private void drawNode(Graphics g, Node n){
gfillRect(nxnodeWidth,
nynodeHeight,
nodeWidth-1,
nodeHeight-1);
}
public void updateScore(){
String s = "Score: " + snakeModelscore;
labelScoresetText(s);
}
void begin(){
if (snakeModel == null || !snakeModelrunning){
snakeModel = new SnakeModel(this,
canvasWidth/nodeWidth,
canvasHeight/nodeHeight);
(new Thread(snakeModel))start();
}
}
public static void main(String[] args){
GreedSnake gs = new GreedSnake();
}
}
///////////////////////////////////////////////////
// 文件2
///////////////////////////////////////////////////
import javautil;
import javaxswing;
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 = 075;
boolean paused = false;
int score = 0;
int countMove = 0;
// UP and DOWN should be even
// RIGHT and LEFT should be odd
public static final int UP = 2;
public static final int DOWN = 4;
public static final int LEFT = 1;
public static final int RIGHT = 3;
public SnakeModel(GreedSnake gs, int maxX, int maxY){
thisgs = gs;
thismaxX = maxX;
thismaxY = maxY;
// initial matirx
matrix = new boolean[maxX][];
for(int i=0; i<maxX; ++i){
matrix = new boolean[maxY];
Arraysfill(matrix,false);
}
// initial the snake
int initArrayLength = maxX > 20 10 : maxX/2;
for(int i = 0; i < initArrayLength; ++i){
int x = maxX/2+i;
int y = maxY/2;
nodeArrayaddLast(new Node(x, y));
matrix[x][y] = true;
}
food = createFood();
matrix[foodx][foody] = true;
}
public void changeDirection(int newDirection){
if (direction % 2 != newDirection % 2){
direction = newDirection;
}
}
public boolean moveOn(){
Node n = (Node)nodeArraygetFirst();
int x = nx;
int y = ny;
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 == foodx && y == foody){
nodeArrayaddFirst(food);
int scoreGet = (10000 - 200 countMove) / timeInterval;
score += scoreGet > 0 scoreGet : 10;
countMove = 0;
food = createFood();
matrix[foodx][foody] = true;
return true;
}
else
return false;
}
else{
nodeArrayaddFirst(new Node(x,y));
matrix[x][y] = true;
n = (Node)nodeArrayremoveLast();
matrix[nx][ny] = false;
countMove++;
return true;
}
}
以上就是关于求一个“JAVA拿火柴小游戏”的程序要求如下!!!!!!!跪求!!!!!全部的内容,包括:求一个“JAVA拿火柴小游戏”的程序要求如下!!!!!!!跪求!!!!!、基于Java语言的打地鼠的小游戏源代码是什么、JAVA小游戏的线程简单代码 (两个武士A、B对打)等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)