俄羅斯方塊——java源代碼提供
創(chuàng)新互聯(lián)主要從事網站設計制作、成都網站設計、網頁設計、企業(yè)做網站、公司建網站等業(yè)務。立足成都服務義安,十年網站建設經驗,價格優(yōu)惠、服務專業(yè),歡迎來電咨詢建站服務:18980820575
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;
}
//按鈕執(zhí)行方法
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},//用十六進至表示,本行表示長條四種狀態(tài)
{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; //塊的翻轉狀態(tài)(0-3)
int blockState; //快的下落狀態(tài)
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);
}
}
表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繪圖區(qū)域的寬度 int width; // Height of applet drawing area. // applet繪圖區(qū)域的高度 int height; // Image buffer. // 圖像緩沖 Image imBuffer; // Graphics context associated with image buffer. // 圖像緩沖相關聯(lián)的圖形背景 Graphics imG; public void init () { // Obtain the size of the applet's drawing area. // 獲取applet繪圖區(qū)域的尺寸 width = getSize ().width; height = getSize ().height; // Create image buffer. // 創(chuàng)建圖像緩沖 imBuffer = createImage (width, height); // Retrieve graphics context associated with image buffer. // 取出圖像緩沖相關聯(lián)的圖形背景 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添加一個用來監(jiān)聽鼠標按鍵的按下和釋放事件的鼠標監(jiān)聽器 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添加一個用來監(jiān)聽鼠標拖動事件的鼠標運動監(jiān)聽器 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), // 并且刷新顯示區(qū)域(此時的棋子已經位于新坐標上) 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的繪圖區(qū)域清除 // 為背景色,這種繪制之后的清除就導致了閃爍。CheckerDrag重寫了update()來 // 防止背景被清除,從而消除了閃爍。 public void update (Graphics g) { paint (g); }}
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class GameTest extends JFrame implements ActionListener{
/*
* 新建一個主面板(這個類可能是自定義的,本程序和API中沒有)。
*/
MainPanel j=new MainPanel();
JButton jPreview;
JLabel label;
Container container;
JPanel panel;
/**
* 主函數
* @param args
*/
public static void main(String[] args) {
//運行程序
new GameTest();
}
/**
* 構造函數。
*
*/
public GameTest()
{
//新建一個標題為“拼圖”的窗口
JFrame fr =new JFrame("拼圖");
//獲取窗口容器。
container=fr.getContentPane();
//創(chuàng)建菜單條
JMenuBar jMenuBar=new JMenuBar();
//以下初始化菜單,并且設置快捷鍵和添加監(jiān)聽器。
JMenu jMenuGame=new JMenu("游戲(G)");
jMenuGame.setMnemonic('g');
JMenuItem jMenuItemStart = new JMenuItem("開始(S)");
jMenuItemStart.setMnemonic('s');
jMenuItemStart.addActionListener(this);
JMenuItem jMenuItemExit=new JMenuItem("退出(E)");
jMenuItemExit.setMnemonic('e');
jMenuItemExit.addActionListener(this);
jMenuGame.add(jMenuItemStart);
jMenuGame.add(jMenuItemExit);
//初始化按鈕并設置快捷鍵和添加監(jiān)聽器
JButton jChoice=new JButton("選圖(X)");
jChoice.setMnemonic('x');
jChoice.addActionListener(this);
jPreview=new JButton("預覽(P)");
jPreview.setMnemonic('p');
jPreview.addActionListener(this);
//將菜單和按鈕添加到菜單條中
jMenuBar.add(jMenuGame);
jMenuBar.add(jChoice);
jMenuBar.add(jPreview);
//將菜單條設為該窗口的主菜單
fr.setJMenuBar(jMenuBar);
//將主面板添加到該窗口的容器中。
container.add(j);
//設置大小
fr.setSize(315,360 );
fr.setVisible(true);
//設置默認關閉方式。
fr.setDefaultCloseOperation(3);
}
/**
* 事件處理函數。
*/
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand()=="開始(S)")
{
j.Start();
}
if(e.getActionCommand()=="預覽(P)")
{
j.setVisible(false);
panel=new JPanel();
Icon icon=new ImageIcon("pictrue/pic"+"_"+MainPanel.pictureID+".jpg");
label=new JLabel(icon);
label.setBounds(300, 300, 0, 0);
panel.add(label);
panel.setSize(300, 300);
panel.setVisible(true);
this.container.add(panel);
jPreview.setText("返回(P)");
}
if(e.getActionCommand()=="返回(P)")
{
panel.setVisible(false);
j.setVisible(true);
j.repaint();
jPreview.setText("預覽(P)");
}
if(e.getActionCommand()=="退出(E)")
{
System.exit(0);
}
if(e.getActionCommand()=="選圖(X)")
{
//初始化選擇框,并提供選擇。
Choice pic = new Choice();
pic.add("七里香");
pic.add("依然范特西");
pic.add("八度空間");
pic.add("十一月的肖邦");
pic.add("魔杰座");
pic.add("葉惠美");
pic.add("我很忙");
int i=JOptionPane.showConfirmDialog(this, pic, "選擇圖片", JOptionPane.OK_CANCEL_OPTION);
if(i==JOptionPane.YES_OPTION)
{
//選擇圖片
MainPanel.pictureID=pic.getSelectedIndex()+1;
j.removeAll();
j.reLoadPicture();
j.repaint();
}
}
}
}
package com.regex;
import java.io.*;
import java點虐 .URLDecoder;
import java.util.regex.*;
public class Regex {
private int REMARK=0;
private int LOGIC=0;
private int PHYSIC=0;
boolean start=false;
/**
* @param args
*/
public static void main(String[] args) { //測試方法
// TODO Auto-generated method stub
Regex re=new Regex();
re.regCount("Regex.java");
System.out.println("remark Line: "+re.REMARK);
System.out.println("logic Line: "+re.LOGIC);
System.out.println("physic Line: "+re.PHYSIC);
}/**
* @author BlueDance
* @param s
* @deprecated count
*/
public void regCount(String s){
String url=null;
try {
url=URLDecoder.decode(this.getClass().getResource(s).getPath(),"UTF-8");
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
try {
BufferedReader br=new BufferedReader(new FileReader(new File(url)));
String s1=null;
while((s1=br.readLine())!=null){
PHYSIC++;
if(CheckChar(s1)==1){
REMARK++;
System.out.println("純注釋行:"+s1);
}
if(CheckChar(s1)==2){
LOGIC++;
REMARK++;
System.out.println("非純注釋行:"+s1);
}
if(CheckChar(s1)==3)
LOGIC++;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
/**
*
* @param s
* @return int
* @version check s
*/
public int CheckChar(String s){
String s1=null;
if(s!=null)
s1=s.trim();
//System.out.println(regCheck(s1,re));
if(regCheck(s1,"(//.*)")) //判斷//開頭的為純注釋行
return 1;
if(regCheck(s1,"(.*[;{})] *//.*)")) //判斷不是//開頭的非純注釋行
return 2;
if(regCheck(s1,"(//*.*)")){ //判斷/*開頭的純注釋行
start=true;
return 1;
}
if(regCheck(s1,"(.*[;{})]//*.*)")){ //判斷不是/*開頭的非純注釋行
start=true;
return 2;
}
if(regCheck(s1,"(.* */*/)")){ //判斷*/結尾的純注釋行
start=false;
return 1;
}
if(regCheck(s1,"(.* */*/.*)")!strCheck(s1)){ //判斷不是*/結尾的非純注釋行
if(strCheck(s1)){
start=false;
return 2;
}
}
if(start==true) //狀態(tài)代碼,start即/*開始時start=true*/結束時為false
return 1;
return 3;//ssssllll
}//aeee
/**
*
* @param s
* @param re
* @return boolean
*/
public boolean regCheck(String s,String re){ //正則表達試判斷方法
return Pattern.matches(re,s);
}
public boolean strCheck(String s){ //中間有*/的字符判斷 此方法最關鍵
if(s.indexOf("*/")0){
int count=0;
String y[]=s.split("/*/");
boolean boo[]=new boolean[y.length];
for (int i = 0; i y.length-1; i++) {
char c[]=y[i].toCharArray();
for (int j = 0; j c.length; j++) {
if(c[j]=='\\'c[j+1]=='"'){
count++;
}
}
if(count%2==0){
if(countNumber("\"",y[i])%2!=0){
boo[i]=true;
}else{
boo[i]=false;
}
}else{
if(countNumber("\"",y[i])%2==0){
boo[i]=true;
}else{
boo[i]=false;
}
}
}
for(int i=0;iboo.length;i++){
if(!boo[i])
return false;
}
return true;
}
return false;
}
public int countNumber(String s,String y){ //此方法為我前面寫的字符串出現次數統(tǒng)計方法,不懂的可以看我前面的文章
int count=0;
String [] k=y.split(s);
if(y.lastIndexOf(s)==(y.length()-s.length()))
count=k.length;
else
count=k.length-1;
if(count==0)
System.out.println ("字符串\""+s+"\"在字符串\""+y+"\"沒有出現過");
else
return count;
return -1;
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GoodLucky extends JFrame implements ActionListener{
JTextField tf = new JTextField(); //實例化一個文本域
//設置兩個按鈕
JButton b1 = new JButton("開始");
JButton b2 = new JButton("停止");
boolean isGo = false;
//構造函數
public GoodLucky(){
b1.setActionCommand("start");//在開始按鈕上設置一個動作監(jiān)聽 start
JPanel p = new JPanel(); //實例化一個可視化容器
//將兩個按鈕添加到可視化容器上面,用add方法
p.add(b1);
p.add(b2);
//在兩個按鈕上增加監(jiān)聽的屬性,自動調用下面的監(jiān)聽處理方法actionPerformed(ActionEvent e),如果要代碼有更好的可讀性,可用內部類實現動作
//監(jiān)聽處理。
b1.addActionListener(this);
b2.addActionListener(this);
//將停止按鈕設置為不可編輯(即不可按的狀態(tài))
b2.setEnabled(false);
this.getContentPane().add(tf,"North"); //將上面的文本域放在面板的北方,也就是上面(上北下南左西右東)
this.getContentPane().add(p,"South"); //將可視化容器pannel放在南邊,也就是下面
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //設置用戶在此窗體上發(fā)起 "close" 時默認執(zhí)行的操作,參數EXIT_ON_CLOSE是使用 System exit 方法退出應用程序。僅在應用程序中使用
this.setSize(300,200); //設置面板大小,寬和高
this.setLocation(300,300); //設置面板剛開始的出現的位置
Cursor cu = new Cursor(Cursor.HAND_CURSOR); //用指定名稱創(chuàng)建一個新的定制光標對象,參數表示手狀光標類型
this.setCursor(cu); //為指定的光標設置光標圖像,即設置光標圖像為上面所創(chuàng)建的手狀光標類型
this.setVisible(true); //將面板可視化設置為true,即可視,如果為false,即程序運行時面板會隱藏
tf.setText("welcome you! "); //設置面板的標題為歡迎
this.go(); //調用go方法
}
public void go(){
while(true){ //這里是死循環(huán),也就是說用戶不點擊停止按鈕的話他一直循環(huán)出現隨機數,直到用戶點擊停止按鈕循環(huán)才能推出,具體流程在actionPerformed方法中控制。
if(isGo == true){ //上面所定義的isGo的初始值為false,所以程序第一次到此會跳過
String s = ""; //設置空字符串
for(int j = 1; j = 7;j++){ //產生7個隨機數
int i = (int)(Math.random() * 36) + 1;//每個隨機數產生方式,這里定義靈活,可以自由定義隨機數產生的方式
if(i 10){
s = s + " 0" + i; //如果產生的隨機數小于10的話做處理:這里就牽扯到一個重要的概念,簡單敘述一下:
/*
當一個字符串與一個整型數項相加的意思是連接,上面的s = s + " 0" + i的意思是字符串s鏈接0再連接整型i值,而不會導致0和整型的i相加,
產生的效果為s0i,由于s為空字符串(上面定義過的),所以當i小于零時,在個位數前面加上0,比如產生的隨機數i為7的話,顯示效果為 07.
*/
}else{
s = s + " " + i; //如果產生的隨機數比10打的話,那么加上空格顯示,即數字和數字之間有個空格
}
//以上循環(huán)循環(huán)七次,以保證能出現7個隨機數
}
tf.setText(s); //將產生的隨機數全部顯示在文本域上,用文本域對象tf調用它的設置文本的方法setText(String)實現。
}
//以下為線程延遲
try{
Thread.sleep(10); //線程類同步方法sleep,睡眠方法,括號里的單位為ms。
}catch(java.lang.InterruptedException e){
e.printStackTrace(); //異常捕獲,不用多說。
}
}
}
//以下是上面設置的事件監(jiān)聽的具體處理辦法,即監(jiān)聽時間處理方法,自動調用
public void actionPerformed(ActionEvent e){ //傳入一個動作事件的參數e
String s = e.getActionCommand(); //設置字符串s來存儲獲得動作監(jiān)聽,上面的start
/*
以下這個條件語句塊的作用為:用戶點擊開始后(捕獲start,用方法getActionCommand()),將命令觸發(fā)設置為true,從而執(zhí)行上面的go方法中的循環(huán)體(因為循環(huán)體中要求isGo參數為true,而初始為false)。
執(zhí)行循環(huán)快產生隨機數,并將開始按鈕不可編輯化,而用戶只可以使用停止按鈕去停止。如果用戶按下停止時,也就是沒有傳入參數“start”的時候,
執(zhí)行else語句塊中的語句,isGo設置為false,將不執(zhí)行上面go中的循環(huán)語句塊,從而停止產生隨機數,并顯示,并且把開始按鈕設置為可用,而把
停止按鈕設置為不可用,等待用戶按下開始再去開始新一輪循環(huán)產生隨機數。
*/
if(s.equals("start")){ //如果捕獲到start,也就是用戶觸發(fā)了動作監(jiān)聽器,那么下面處理
isGo = true; //設置isGo為true
b1.setEnabled(false); //將開始按鈕設置為不可用
b2.setEnabled(true); //將停止按鈕設置為可用
}else{
isGo = false; //將isGo設置為false,isGo為循環(huán)標志位
b2.setEnabled(false); //設置停止按鈕為不可用(注意看是b2,b2是停止按鈕)
b1.setEnabled(true); //設置開始按鈕為可用
}
}
public static void main(String[] args){
new GoodLucky(); //產生類的實例,執(zhí)行方法
}
}