本文目錄一覽:
求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源代碼一份
貪吃蛇
import java.awt.*;
import java.awt.event.*;
public class GreedSnake //主類
{
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new MyWindow();
}
}
class MyPanel extends Panel implements KeyListener,Runnable//自定義面板類,繼承了鍵盤和線程介面
{
Button snake[]; //定義蛇按鈕
int shu=0; //蛇的節數
int food[]; //食物數組
boolean result=true; //判定結果是輸 還是贏
Thread thread; //定義線程
static int weix,weiy; //食物位置
boolean t=true; //判定遊戲是否結束
int fangxiang=0; //蛇移動方向
int x=0,y=0; //蛇頭位置
MyPanel()
{
setLayout(null);
snake=new Button[20];
food=new int [20];
thread=new Thread(this);
for(int j=0;j20;j++)
{
food[j]=(int)(Math.random()*99);//定義20個隨機食物
}
weix=(int)(food[0]*0.1)*60; //十位*60為橫坐標
weiy=(int)(food[0]%10)*40; //個位*40為縱坐標
for(int i=0;i20;i++)
{
snake[i]=new Button();
}
add(snake[0]);
snake[0].setBackground(Color.black);
snake[0].addKeyListener(this); //為蛇頭添加鍵盤監視器
snake[0].setBounds(0,0,10,10);
setBackground(Color.cyan);
}
public void run() //接收線程
{
while(t)
{
if(fangxiang==0)//向右
{
try
{
x+=10;
snake[0].setLocation(x, y);//設置蛇頭位置
if(x==weixy==weiy) //吃到食物
{
shu++;
weix=(int)(food[shu]*0.1)*60;
weiy=(int)(food[shu]%10)*40;
repaint(); //重繪下一個食物
add(snake[shu]); //增加蛇節數和位置
snake[shu].setBounds(snake[shu-1].getBounds());
}
thread.sleep(100); //睡眠100ms
}
catch(Exception e){}
}
else if(fangxiang==1)//向左
{
try
{
x-=10;
snake[0].setLocation(x, y);
if(x==weixy==weiy)
{
shu++;
weix=(int)(food[shu]*0.1)*60;
weiy=(int)(food[shu]%10)*40;
repaint();
add(snake[shu]);
snake[shu].setBounds(snake[shu-1].getBounds());
}
thread.sleep(100);
}
catch(Exception e){}
}
else if(fangxiang==2)//向上
{
try
{
y-=10;
snake[0].setLocation(x, y);
if(x==weixy==weiy)
{
shu++;
weix=(int)(food[shu]*0.1)*60;
weiy=(int)(food[shu]%10)*40;
repaint();
add(snake[shu]);
snake[shu].setBounds(snake[shu-1].getBounds());
}
thread.sleep(100);
}
catch(Exception e){}
}
else if(fangxiang==3)//向下
{
try
{
y+=10;
snake[0].setLocation(x, y);
if(x==weixy==weiy)
{
shu++;
weix=(int)(food[shu]*0.1)*60;
weiy=(int)(food[shu]%10)*40;
repaint();
add(snake[shu]);
snake[shu].setBounds(snake[shu-1].getBounds());
}
thread.sleep(100);
}
catch(Exception e){}
}
int num1=shu;
while(num11)//判斷是否咬自己的尾巴
{
if(snake[num1].getBounds().x==snake[0].getBounds().xsnake[num1].getBounds().y==snake[0].getBounds().y)
{
t=false;
result=false;
repaint();
}
num1–;
}
if(x0||x=this.getWidth()||y0||y=this.getHeight())//判斷是否撞牆
{
t=false;
result=false;
repaint();
}
int num=shu;
while(num0) //設置蛇節位置
{
snake[num].setBounds(snake[num-1].getBounds());
num–;
}
if(shu==15) //如果蛇節數等於15則勝利
{
t=false;
result=true;
repaint();
}
}
}
public void keyPressed(KeyEvent e) //按下鍵盤方向鍵
{
if(e.getKeyCode()==KeyEvent.VK_RIGHT)//右鍵
{
if(fangxiang!=1)//如果先前方向不為左
fangxiang=0;
}
else if(e.getKeyCode()==KeyEvent.VK_LEFT)
{ if(fangxiang!=0)
fangxiang=1;
}
else if(e.getKeyCode()==KeyEvent.VK_UP)
{ if(fangxiang!=3)
fangxiang=2;
}
else if(e.getKeyCode()==KeyEvent.VK_DOWN)
{ if(fangxiang!=2)
fangxiang=3;
}
}
public void keyTyped(KeyEvent e)
{
}
public void keyReleased(KeyEvent e)
{
}
public void paint(Graphics g) //在面板上繪圖
{
int x1=this.getWidth()-1;
int y1=this.getHeight()-1;
g.setColor(Color.red);
g.fillOval(weix, weiy, 10, 10);//食物
g.drawRect(0, 0, x1, y1); //牆
if(t==falseresult==false)
g.drawString(“GAME OVER!”, 250, 200);//輸出遊戲失敗
else if(t==falseresult==true)
g.drawString(“YOU WIN!”, 250, 200);//輸出遊戲成功
}
}
class MyWindow extends Frame implements ActionListener//自定義窗口類
{
MyPanel my;
Button btn;
Panel panel;
MyWindow()
{
super(“GreedSnake”);
my=new MyPanel();
btn=new Button(“begin”);
panel=new Panel();
btn.addActionListener(this);
panel.add(new Label(“begin後請按Tab鍵選定蛇”));
panel.add(btn);
panel.add(new Label(“按上下左右鍵控制蛇行動”));
add(panel,BorderLayout.NORTH);
add(my,BorderLayout.CENTER);
setBounds(100,100,610,500);
setVisible(true);
validate();
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)//按下begin按鈕
{
if(e.getSource()==btn)
{
try
{
my.thread.start(); //開始線程
my.validate();
}
catch(Exception ee){}
}
}
}
基於Java語言的打地鼠的小遊戲源代碼是什麼?
public void mouseClicked(MouseEvent e){
Object source=e.getSource(); //獲取事件源,即地滑鼠簽
if(source instanceof JLabel){ //如果事件是標籤組件
JLabel mouse=(JLabel)source; //強制轉換為JLabel標籤
mouse.setIcon(null); //取消標籤圖標
}
}
});
this.getContentPane().add(mouses[i]); //添加顯示地鼠的標籤到窗體
}
mouses[0].setLocation(253, 300); //設置每個標籤的位置
mouses[1].setLocation(333, 250);
mouses[2].setLocation(388, 296);
mouses[3].setLocation(362, 364);
mouses[4].setLocation(189, 353);
mouses[5].setLocation(240, 409);
final JLabel backLabel=new JLabel(); //創建顯示背景的標籤
backLabel.setBounds(0, 0, img.getIconWidth(), img.getIconHeight());
this.setBounds(100,100,img.getIconWidth(),img.getIconHeight());
backLabel.setIcon(img); //添加背景到標籤
this.getContentPane().add(backLabel); //添加背景標籤到窗體
}
/**
* 線程的核心方法
*/
public void run(){
while(true){ //使用無限循環
try{
Thread.sleep(3000); //使線程休眠3秒
int index=(int)(Math.random()*6); //生成隨機的地鼠索引
if(mouses[index].getIcon()==null){ //如果地滑鼠簽沒有設置圖片
mouses[index].setIcon(imgMouse); //為該標籤添加地鼠圖片
}
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
原創文章,作者:NBKH,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/145500.html