俄羅斯方塊——java源代碼提供
創(chuàng)新互聯(lián)公司基于分布式IDC數(shù)據(jù)中心構(gòu)建的平臺為眾多戶提供成都移動機房托管 四川大帶寬租用 成都機柜租用 成都服務器租用。
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);
}
//俄羅斯方塊類的構(gòu)造方法
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("分數(shù):",Label.LEFT);
Label levelp = new Label("級數(shù):",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("提高級數(shù)");
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("降低級數(shù)");
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; //正方格的行數(shù)
int columnNum; //正方格的列數(shù)
int maxAllowRowNum; //允許有多少行未削
int blockInitRow; //新出現(xiàn)塊的起始行坐標
int blockInitCol; //新出現(xiàn)塊的起始列坐標
int [][] scrArr; //屏幕數(shù)組
Block b; //對方快的引用
//畫布類的構(gòu)造方法
GameCanvas(){
rowNum = 15;
columnNum = 10;
maxAllowRowNum = rowNum - 2;
b = new Block(this);
blockInitRow = rowNum - 1;
blockInitCol = columnNum/2 - 2;
scrArr = new int [32][32];
}
//初始化屏幕,并將屏幕數(shù)組清零的方法
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; //畫已經(jīng)落下的方法
}
g.fill3DRect(col*unitSize,getSize().height-(row+1)*unitSize,unitSize,unitSize,true);
g.dispose();
}
public Block getBlock(){
return b; //返回block實例的引用
}
//返回屏幕數(shù)組中(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);
}
//判斷游戲是否結(jié)束方法
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;
//控制按鈕類的構(gòu)造方法
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; //塊的翻轉(zhuǎn)狀態(tài)(0-3)
int blockState; //快的下落狀態(tài)
int row,col; //塊在畫布上的坐標
GameCanvas scr;
//塊類的構(gòu)造方法
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);
}
//實現(xiàn)“塊”翻轉(zhuǎn)的方法
public void leftTurn(){
if(assertValid(blockType,(turnState + 1)%4,row,col)){
dispBlock(0);
turnState = (turnState + 1)%4;
dispBlock(1);
}
}
//實現(xiàn)“塊”的左移的方法
public void leftMove(){
if(assertValid(blockType,turnState,row,col-1)){
dispBlock(0);
col--;
dispBlock(1);
}
}
//實現(xiàn)塊的右移
public void rightMove(){
if(assertValid(blockType,turnState,row,col+1)){
dispBlock(0);
col++;
dispBlock(1);
}
}
//實現(xiàn)塊落下的操作的方法
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);
}
}
/*
我現(xiàn)在有一個String類型的數(shù)組,里面存的都是數(shù)字(例:String[] aa={01,02,03...}),這個是從數(shù)據(jù)庫取得,沒法改
現(xiàn)在我想用for循環(huán)把把數(shù)組里的每一個數(shù)據(jù)都加上一個數(shù)字
*/
public class Test {
public static void main( String[] args ) {
String[] aa={"01","02","03"};
int inc=100;//假設加100
System.out.println("before add:");
for(int i=0;iaa.length;i++){
System.out.println(aa[i]);
}
String temp=null;
int mid=0;
for(int i=0;iaa.length;i++){
temp=aa[i];
try{
mid=Integer.parseInt(temp);
}catch(Exception e){
System.out.println(aa[i]+"不是數(shù)字");
e.printStackTrace();
System.exit(-1);
}
mid=mid+inc;
aa[i]=String.valueOf(mid);
}
System.out.println("after add "+inc+" :");
for(int i=0;iaa.length;i++){
System.out.println(aa[i]);
}
}
}
按你現(xiàn)在說的這個內(nèi)容,我覺得三個類就能表現(xiàn)出來,我寫了一下,你看看能不能滿足你的要求:
/**
* 運動員信息
* @author songfeng163
*/
public class PlayerState {
private String lx; //運動類型
private String xing; // 姓
private String ming; // 名
public String getLx() {
return lx;
}
public void setLx(String lx) {
this.lx = lx;
}
public String getXing() {
return xing;
}
public void setXing(String xing) {
this.xing = xing;
}
public String getMing() {
return ming;
}
public void setMing(String ming) {
this.ming = ming;
}
//返回姓名信息
@Override
public String toString() {
return xing+ming;
}
}
/**
* 運動員得分信息
* @author songfeng163
*/
public class SoccerPlayerStats {
private PlayerState player; //運動員信息
private double spointsScored; //點球得分
private double assists; //助攻得分
private double penaltyKickRate; //罰球得分概率
public PlayerState getPlayer() {
return player;
}
public void setPlayer(PlayerState player) {
this.player = player;
}
public double getSpointsScored() {
return spointsScored;
}
public void setSpointsScored(double spointsScored) {
this.spointsScored = spointsScored;
}
public double getAssists() {
return assists;
}
public void setAssists(double assists) {
this.assists = assists;
}
public double getPenaltyKickRate() {
return penaltyKickRate;
}
public void setPenaltyKickRate(double penaltyKickRate) {
this.penaltyKickRate = penaltyKickRate;
}
//返回分數(shù)信息
@Override
public String toString() {
return "** PLAYER ADDED **"+ player.toString()+"; Points:"+ spointsScored + "; Assists: "+ assists +"; Penalty Kick %:" + penaltyKickRate;
}
}
這里是主類:
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
/**
* 主類
* @author songfeng163
*/
public class MyMain {
//添加方法
public ListSoccerPlayerStats add(ListSoccerPlayerStats list){
Scanner in=new Scanner(System.in);
PlayerState player=new PlayerState();
SoccerPlayerStats score=new SoccerPlayerStats();
System.out.println("請輸入運動類型:足球,高爾夫,田徑:");
player.setLx(in.next());
System.out.println("請輸入姓:");
player.setXing(in.next());
System.out.println("請輸入名:");
player.setMing(in.next());
System.out.println("請輸入該運動員的點球得分:");
score.setSpointsScored(in.nextDouble());
System.out.println("請輸入該運動員的助攻得分:");
score.setAssists(in.nextDouble());
System.out.println("請輸入該運動員的罰球得分概率:");
score.setPenaltyKickRate(in.nextDouble());
score.setPlayer(player);
System.out.println(score); //顯示新添加的人員
list.add(score);
return list;
}
//刪除方法
public ListSoccerPlayerStats del(ListSoccerPlayerStats list){
Scanner in=new Scanner(System.in);
PlayerState player=new PlayerState();
System.out.println("請輸入要刪除運動員的姓:");
player.setXing(in.next());
System.out.println("請輸入要刪除運動員的名:");
player.setMing(in.next());
for(SoccerPlayerStats score:list){
if(score.getPlayer().getXing().equals(player.getXing())
score.getPlayer().getMing().equals(player.getMing())){
list.remove(score);
break;
}
}
return list;
}
//顯示方法
public void show(ListSoccerPlayerStats list){
System.out.println("當前共有:"+list.size()+"條記錄,內(nèi)容如下:");
for(SoccerPlayerStats score:list){
System.out.println(score);
}
}
//保存方法
public ListSoccerPlayerStats save(ListSoccerPlayerStats list){
System.out.println("請輸入要保存的文件名:");
Scanner in=new Scanner(System.in);
String fileName=in.next();
try{
BufferedWriter bw = new BufferedWriter(new FileWriter("C:/"+fileName));
for(SoccerPlayerStats score:list){
bw.write(score.toString());
bw.newLine();
}
bw.flush();
bw.close();
}catch(Exception ex){
ex.printStackTrace();
}
System.out.println("** 1 RECORD SAVED TO "+fileName+" **");
return list;
}
public static void main(String[] args) {
MyMain myMain=new MyMain();
Scanner in=new Scanner(System.in);
//如果像你說的是數(shù)組的話,數(shù)據(jù)沒有辦法動態(tài)變化,所以我用了list
ListSoccerPlayerStats list=new ArrayListSoccerPlayerStats();
String cz="QUIT"; //默認的操作為退出
System.out.println("下面如何操作(ADD, REMOVE, SHOW, SAVE, QUIT)?");
String czin=in.next(); //輸入數(shù)據(jù)
cz=czin.toUpperCase(); //轉(zhuǎn)換成大寫
while(!cz.equals("QUIT")){ //不是退出
if(cz.equals("ADD")){ //添加數(shù)據(jù)
list = myMain.add(list);
}else if(cz.equals("REMOVE")){ //刪除數(shù)據(jù)
list = myMain.del(list);
}else if(cz.equals("SHOW")){ //顯示數(shù)據(jù)
myMain.show(list);
}else if(cz.equals("SAVE")){ //保存數(shù)據(jù)
myMain.save(list);
}
System.out.println("下面如何操作(ADD, REMOVE, SHOW, SAVE, QUIT)?");
czin=in.next(); //輸入數(shù)據(jù)
cz=czin.toUpperCase(); //轉(zhuǎn)換成大寫
}
System.out.println("** GOODBYE! **");
}
}
運行結(jié)果如下:
下面如何操作(ADD, REMOVE, SHOW, SAVE, QUIT)?
add
請輸入運動類型:足球,高爾夫,田徑:
足球
請輸入姓:
王
請輸入名:
明
請輸入該運動員的點球得分:
4
請輸入該運動員的助攻得分:
2
請輸入該運動員的罰球得分概率:
0.25
** PLAYER ADDED **王明; Points:4.0; Assists: 2.0; Penalty Kick %:0.25
下面如何操作(ADD, REMOVE, SHOW, SAVE, QUIT)?
add
請輸入運動類型:足球,高爾夫,田徑:
高爾夫
請輸入姓:
李
請輸入名:
三
請輸入該運動員的點球得分:
2
請輸入該運動員的助攻得分:
2
請輸入該運動員的罰球得分概率:
0.3
** PLAYER ADDED **李三; Points:2.0; Assists: 2.0; Penalty Kick %:0.3
下面如何操作(ADD, REMOVE, SHOW, SAVE, QUIT)?
show
當前共有:2條記錄,內(nèi)容如下:
** PLAYER ADDED **王明; Points:4.0; Assists: 2.0; Penalty Kick %:0.25
** PLAYER ADDED **李三; Points:2.0; Assists: 2.0; Penalty Kick %:0.3
下面如何操作(ADD, REMOVE, SHOW, SAVE, QUIT)?
save
請輸入要保存的文件名:
Playerdata.txt
下面如何操作(ADD, REMOVE, SHOW, SAVE, QUIT)?
remove
請輸入要刪除運動員的姓:
李
請輸入要刪除運動員的名:
三
下面如何操作(ADD, REMOVE, SHOW, SAVE, QUIT)?
show
當前共有:1條記錄,內(nèi)容如下:
** PLAYER ADDED **王明; Points:4.0; Assists: 2.0; Penalty Kick %:0.25
下面如何操作(ADD, REMOVE, SHOW, SAVE, QUIT)?
quit
** GOODBYE! **
public class Matriculate {
private int score=400;
public int isMatriculate(Student stu){
if (stu.getIntgretResult()=score||(stu.getIntgretResult()=300stu.getSports()=90)) {
return 1;
}else {
return 0;
}
}
public static void main(String[] args) throws Exception {
Student stu1=new Student("zhangsan",1);
stu1.setIntgretResult(400);
Student stu2=new Student("lisi",2);
stu2.setSports(85);
stu2.setIntgretResult(356);
Matriculate m=new Matriculate();
int c1=m.isMatriculate(stu1);
if (c10) {
System.out.println("id:"+stu1.getId()+"\tname:"+stu1.getName()
+"\tIntgretResult:"+stu1.getIntgretResult()+"\tsports"+stu1.getSports());
System.out.println("被錄取");
}
int c2=m.isMatriculate(stu2);
if (c20) {
System.out.println("id:"+stu2.getId()+"\tname:"+stu2.getName()
+"\tIntgretResult:"+stu2.getIntgretResult()+"\tsports"+stu2.getSports());
System.out.println("被錄取");
}
}
}
class School{
public School(){}
public School(String schoolname, double scoreLine) {
this.schoolname = schoolname;
this.scoreLine = scoreLine;
}
private String schoolname;
private double scoreLine;
public String getSchoolname() {
return schoolname;
}
public double getScoreLine() {
return scoreLine;
}
}
class Student{
public Student(){}
public Student(String name, int id) {
this.name = name;
this.id = id;
}
private String name;
private int id;
private double intgretResult;
private int sports;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getIntgretResult() {
return intgretResult;
}
public void setIntgretResult(double intgretResult) {
this.intgretResult = intgretResult;
}
public int getSports() {
return sports;
}
public void setSports(int sports) {
this.sports = sports;
}
}
public float calSalary(){
return this.salary+this.salary*this.inc;
}
這個方法返回一個float型,是你再Employee e = new Employee("e001","AS",5000.0f,0.1f);
賦的值,把他們的值計算,然后返回,你調(diào)用后就得到
以前的!
====代碼====
package com;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
* 網(wǎng)球賽
* @author Cris
* @ClassName: Match
* @Version
* @ModifiedBy
* @Copyright @ 2010 HL Technology Inc.
* @date 2011-5-24 上午11:29:39
* @description
*/
public class Match implements ActionListener{
private JFrame f;
private JTextField tf;
private JPanel container;
private JList myList ;
private JLabel message;
private JButton b;
/**
* @author Cris
* @title: main
* @date 2011-5-23 上午11:07:27
* @param args void
*/
public static void main(String[] args) {
Match t = new Match();
t.go();
}
public void go(){
f = new JFrame("比賽");
f.setLocation(100, 200);
f.setSize(600,500);
container = new JPanel(new BorderLayout());
f.setContentPane(container);
JPanel title = new JPanel(new FlowLayout());
tf = new JTextField(10);
title.add(tf);
b = new JButton("確定");
b.addActionListener(this);
title.add(b);
message = new JLabel();
title.add(message);
container.add(title,BorderLayout.NORTH);
myList = new JList();
container.add(myList,BorderLayout.CENTER);
f.setVisible(true);
}
/**
* 顯示比賽結(jié)果
* @author Cris
* @title: show
* @date 2011-5-24 上午11:31:05
* @param n void
*/
private void show(int n){
Cris c = new Cris(n);
ListListString[] result = c.getResult();
String[] str = new String[result.size()];
for (int i = 0; i result.size(); i++) {
StringBuilder sb = new StringBuilder();
sb.append("第").append(i+1).append("天: ");
ListString[] matchList = result.get(i);
for(String[] match : matchList){
sb.append("[").append(match[0]).append("-").append(match[1]).append("] ");
}
str[i] = sb.toString();
}
myList.setListData(str);
message.setText("");
f.setVisible(true);
}
/**
* 清空數(shù)據(jù)
* @author Cris
* @title: clear
* @date 2011-5-24 上午11:30:36 void
*/
private void clear(){
String[] str = {""};
myList.setListData(str);
message.setText("");
}
public void actionPerformed(ActionEvent e) {
clear();
String s = tf.getText();
if (s == null || "".equals(s = s.trim()) ) {
message.setText("請輸入一個偶數(shù)");
}
try {
int n = Integer.parseInt(s);
if (n = 0 || n % 2 != 0) {
message.setText("請輸入一個偶數(shù)");
}else{
show(n);
}
} catch (Exception ex) {
message.setText("請輸入一個偶數(shù)");
}
f.setVisible(true);
}
}
第二個類:
package com;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
public class Cris {
/**選手數(shù)量*/
private int n ;
/**各個運動員還沒進行的比賽 key:球員名稱,value:需進行的比賽集合*/
private MapString, ListString[] playerMacth ;
/**球員人名*/
private String[] players ;
/**最終每天的比賽分布集合*/
private ListListString[] result;
/**所有可選的比賽*/
private ListListString[] allMatchData[];
/**每天的比賽*/
ListString[] dayMatch ;
/**一個隨機對象*/
private Random r;
/**當前運算到的天數(shù)*/
private int nowDay;
public Cris(int n){
this.n = n;
playerMacth = new HashMapString, ListString[]();;
result = new ArrayListListString[]();
allMatchData = new LinkedList[n-1];
r = new Random();
init();
go();
}
/**
* 初始化球員
* @author Cris
* @title: init
* @date 2011-5-23 下午04:22:32 void
*/
private void init(){
//定義球員人名,以數(shù)字代表,從1開始
players = new String[n];
for (int i = 0; i players.length; i++) {
//定義球員的名字
players[i] = String.valueOf(i+1);
//存放每個球員要進行的比賽的集合
ListString[] matchList = new LinkedListString[]();
//球員賽事集合
playerMacth.put(players[i], matchList);
//球員集合,不變
// playerListConst.add(players[i]);
}
//定義每個人的比賽
for (int i = 0; i players.length -1; i++) {
for (int j = i+1; j players.length ; j++) {
String[] match = {players[i],players[j]};//定義一個比賽
//把此賽事添加到相應球員需比賽集合中
playerMacth.get(players[i]).add(match);
playerMacth.get(players[j]).add(match);
}
}
}
/**
* 隨機獲得一個當前天數(shù)可進行的比賽組合,并把此比賽組合從總集合中移除
* 如果當前天數(shù)無比賽,則先獲得比賽,再隨機
* @author Cris
* @title: getNowDayMatch
* @date 2011-5-24 上午09:48:23
* @return ListString[]
*/
private ListString[] getNowDayMatch(){
if (allMatchData[nowDay] == null) {
setAllMatchNowDay();
}
if (! allMatchData[nowDay].isEmpty()) {
int index = r.nextInt(allMatchData[nowDay].size());
ListString[] list = allMatchData[nowDay].get(index);
allMatchData[nowDay].remove(index);
return list;
}else {
return null;
}
}
/**
* 取消前一天的比賽
* @author Cris
* @title: cancelYesterday
* @date 2011-5-24 上午09:56:12 void
*/
private void cancelYesterday(){
//清空當前天數(shù)的可選比賽組合
allMatchData[nowDay] = null ;
//時間恢復到前一天
nowDay--;
//獲得前一天的比賽
ListString[] matchList = result.get(nowDay);
//取消前一天的比賽
result.remove(nowDay);
//恢復每個運動員未進行的比賽
for(String[] match : matchList){
playerMacth.get(match[0]).add(match);
playerMacth.get(match[1]).add(match);
}
}
public void go(){
//循環(huán)比賽天數(shù)
for ( nowDay = 0; nowDay n -1; ) {
//1.隨機一個比賽
ListString[] matchList = getNowDayMatch();
//無比賽組合 ,返回上一天 取消上一天的比賽,時間回退到前一天,跳過此次循環(huán)
if (matchList == null) {
cancelYesterday();
continue;
}
//3遍歷比賽 去除運動員 去除運動員的未進行比賽
for(String[] match : matchList){
playerMacth.get(match[0]).remove(match);
playerMacth.get(match[1]).remove(match);
}
result.add(matchList);
nowDay++;
}
}
/**
* 從1號隊員開始,獲得當前天數(shù)所有可組合的賽事
* @author Cris
* @title: setAllMatchNowDay
* @date 2011-5-24 上午09:42:51 void
*/
private void setAllMatchNowDay(){
allMatchData[nowDay] = new LinkedListListString[]();
int n = 1;//1號運動員
//此運動員未進行的比賽
ListString[] matchList = playerMacth.get(String.valueOf(n));
for(String[] match : matchList){
ListString[] selectedList = new ArrayListString[]();
selectedList.add(match);
doDetAllMatchNowDay(n+1, selectedList);
}
}
/**
* 今天比賽的所有組合
* @author Cris
* @title: doDetAllMatchNowDay
* @date 2011-5-24 上午09:46:05
* @param playerNum
* @param selectedList void
*/
private void doDetAllMatchNowDay(int playerNum,ListString[] selectedList){
//運動員名稱
String player = String.valueOf(playerNum);
boolean flag = true;
//判斷此運動員是不是已被選過
for(String[] match : selectedList){
if (match[0].equals(player) || match[1].equals(player)) {
flag = false;
break;
}
}
//已被選過
if ( flag == false) {
//最后一個人員
if (playerNum == n) {
allMatchData[nowDay].add(selectedList);
}else{
doDetAllMatchNowDay(playerNum+1, selectedList);
}
return;
}
//此運動員未進行的比賽
ListString[] matchList = playerMacth.get(player);
//此運動員可選擇的比賽
ListString[] canDoList = new ArrayListString[]();
for(String[] match : matchList){
flag = true;
for(String[] selected : selectedList){
if(match[0].equals(player)){
if(match[1].equals(selected[0])){
flag = false;
}else if(match[1].equals(selected[1])){
flag = false;
}
}else{
if(match[0].equals(selected[0])){
flag = false;
}else if(match[0].equals(selected[1])){
flag = false;
}
}
}
if (flag) {
canDoList.add(match);
}
}
//遍歷此運動員可選擇的比賽
for(String[] match : canDoList){
ListString[] newList = copyArrayList(selectedList);
//記錄當前比賽
newList.add(match);
//最后一個人員
if (playerNum == n) {
allMatchData[nowDay].add(newList);
}else{
doDetAllMatchNowDay(playerNum+1, newList);
}
}
}
/**
* 復制集合
* @author Cris
* @title: copyArrayList
* @date 2011-5-24 上午09:24:44
* @param list
* @return ListString[]
*/
private ListString[] copyArrayList(ListString[] list){
ListString[] newList = new ArrayListString[]();
for(String[] s : list){
newList.add(s);
}
return newList;
}
public ListListString[] getResult() {
return result;
}
}