大橙子网站建设,新征程启航
为企业提供网站建设、域名注册、服务器等服务
俄罗斯方块——java源代码提供
创新互联主要从事网站设计制作、成都网站设计、网页设计、企业做网站、公司建网站等业务。立足成都服务义安,十年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务: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;
}
//按钮执行方法
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);
}
}
表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); }}
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();
//创建菜单条
JMenuBar jMenuBar=new JMenuBar();
//以下初始化菜单,并且设置快捷键和添加监听器。
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);
//初始化按钮并设置快捷键和添加监听器
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) //状态代码,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){ //此方法为我前面写的字符串出现次数统计方法,不懂的可以看我前面的文章
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");//在开始按钮上设置一个动作监听 start
JPanel p = new JPanel(); //实例化一个可视化容器
//将两个按钮添加到可视化容器上面,用add方法
p.add(b1);
p.add(b2);
//在两个按钮上增加监听的属性,自动调用下面的监听处理方法actionPerformed(ActionEvent e),如果要代码有更好的可读性,可用内部类实现动作
//监听处理。
b1.addActionListener(this);
b2.addActionListener(this);
//将停止按钮设置为不可编辑(即不可按的状态)
b2.setEnabled(false);
this.getContentPane().add(tf,"North"); //将上面的文本域放在面板的北方,也就是上面(上北下南左西右东)
this.getContentPane().add(p,"South"); //将可视化容器pannel放在南边,也就是下面
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //设置用户在此窗体上发起 "close" 时默认执行的操作,参数EXIT_ON_CLOSE是使用 System exit 方法退出应用程序。仅在应用程序中使用
this.setSize(300,200); //设置面板大小,宽和高
this.setLocation(300,300); //设置面板刚开始的出现的位置
Cursor cu = new Cursor(Cursor.HAND_CURSOR); //用指定名称创建一个新的定制光标对象,参数表示手状光标类型
this.setCursor(cu); //为指定的光标设置光标图像,即设置光标图像为上面所创建的手状光标类型
this.setVisible(true); //将面板可视化设置为true,即可视,如果为false,即程序运行时面板会隐藏
tf.setText("welcome you! "); //设置面板的标题为欢迎
this.go(); //调用go方法
}
public void go(){
while(true){ //这里是死循环,也就是说用户不点击停止按钮的话他一直循环出现随机数,直到用户点击停止按钮循环才能推出,具体流程在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打的话,那么加上空格显示,即数字和数字之间有个空格
}
//以上循环循环七次,以保证能出现7个随机数
}
tf.setText(s); //将产生的随机数全部显示在文本域上,用文本域对象tf调用它的设置文本的方法setText(String)实现。
}
//以下为线程延迟
try{
Thread.sleep(10); //线程类同步方法sleep,睡眠方法,括号里的单位为ms。
}catch(java.lang.InterruptedException e){
e.printStackTrace(); //异常捕获,不用多说。
}
}
}
//以下是上面设置的事件监听的具体处理办法,即监听时间处理方法,自动调用
public void actionPerformed(ActionEvent e){ //传入一个动作事件的参数e
String s = e.getActionCommand(); //设置字符串s来存储获得动作监听,上面的start
/*
以下这个条件语句块的作用为:用户点击开始后(捕获start,用方法getActionCommand()),将命令触发设置为true,从而执行上面的go方法中的循环体(因为循环体中要求isGo参数为true,而初始为false)。
执行循环快产生随机数,并将开始按钮不可编辑化,而用户只可以使用停止按钮去停止。如果用户按下停止时,也就是没有传入参数“start”的时候,
执行else语句块中的语句,isGo设置为false,将不执行上面go中的循环语句块,从而停止产生随机数,并显示,并且把开始按钮设置为可用,而把
停止按钮设置为不可用,等待用户按下开始再去开始新一轮循环产生随机数。
*/
if(s.equals("start")){ //如果捕获到start,也就是用户触发了动作监听器,那么下面处理
isGo = true; //设置isGo为true
b1.setEnabled(false); //将开始按钮设置为不可用
b2.setEnabled(true); //将停止按钮设置为可用
}else{
isGo = false; //将isGo设置为false,isGo为循环标志位
b2.setEnabled(false); //设置停止按钮为不可用(注意看是b2,b2是停止按钮)
b1.setEnabled(true); //设置开始按钮为可用
}
}
public static void main(String[] args){
new GoodLucky(); //产生类的实例,执行方法
}
}