俄羅斯方塊java源碼
可以給每一個小方塊設置為一個坐標,變為一個三階行列式,3*3矩陣,轉變為二元數組旋轉。觀察一下左旋:
11 12 13 31 21 11
21 22 23 →→ 32 22 12
31 32 33 33 23 13
坐標變換如下:(1,1)變為(1,3),(1,2)變為(2,3),(1,3)變為(3,3)
(2,1)變為(1,2),(2,2)變為(2,2),(2,3)變為(3,2)
(3,1)變為(1,1),(3,2)變為(2,1),(3,3)變為(3,1)
規律就是(i,j)變為(j,3-i+1):
如果是2*2的方格,就可以變為二階行列式,也就是2*2的二元數組,這里給出3*3九宮格改變的示意,我的代碼如下:
importjava.util.Random;
publicclassT{
publicstaticvoidmain(String[]args){
int[][]a=newint[3][3];
System.out.println("");
Randomr=newRandom();
for(inti=0;i<3;i++){
for(intj=0;j<3;j++){
a[i][j]=r.nextInt(10);
}
}
System.out.println("thearrayisshownasfollows:");
for(inti=0;i<3;i++){
for(intj=0;j<3;j++){
System.out.print(a[i][j]+"");
}
System.out.println();
}
System.out.println("左轉九十度");
for(inti=0;i<a.length;i++){
for(intj=0;j<a[i].length;j++){
System.out.print(a[a[i].length-1-j][i]+"");
}
System.out.println();
}
}
}
❷ 急需一份俄羅斯方塊源代碼,Java寫的
使用Java實現小游戲:俄羅斯方塊
使用一個二維數組保存游戲的地圖:
//游戲地圖格子,每個格子保存一個方塊,數組紀錄方塊的狀態
privateStatemap[][]=newState[rows][columns];123
游戲前先將所有地圖中的格子初始化為空:
/*初始化所有的方塊為空*/
for(inti=0;i<map.length;i++){
for(intj=0;j<map[i].length;j++){
map[i][j]=State.EMPTY;
}
}1234567
玩游戲過程中,我們能夠看到界面上的方塊,那麼就得將地圖中所有的方塊繪制出來,當然,除了需要繪制方塊外,游戲積分和游戲結束的字元串在必要的時候也需要繪制:
/**
*繪制窗體內容,包括游戲方塊,游戲積分或結束字元串
*/
@Override
publicvoidpaint(Graphicsg){
super.paint(g);
for(inti=0;i<rows;i++){
for(intj=0;j<columns;j++){
if(map[i][j]==State.ACTIVE){//繪制活動塊
g.setColor(activeColor);
g.fillRoundRect(j*BLOCK_SIZE,i*BLOCK_SIZE+25,
BLOCK_SIZE-1,BLOCK_SIZE-1,BLOCK_SIZE/5,
BLOCK_SIZE/5);
}elseif(map[i][j]==State.STOPED){//繪制靜止塊
g.setColor(stopedColor);
g.fillRoundRect(j*BLOCK_SIZE,i*BLOCK_SIZE+25,
BLOCK_SIZE-1,BLOCK_SIZE-1,BLOCK_SIZE/5,
BLOCK_SIZE/5);
}
}
}
/*列印得分*/
g.setColor(scoreColor);
g.setFont(newFont("TimesNewRoman",Font.BOLD,30));
g.drawString("SCORE:"+totalScore,5,70);
//游戲結束,列印結束字元串
if(!isGoingOn){
g.setColor(Color.RED);
g.setFont(newFont("TimesNewRoman",Font.BOLD,40));
g.drawString("GAMEOVER!",this.getWidth()/2-140,
this.getHeight()/2);
}
}
通過隨機數的方式產生方塊所組成的幾種圖形,一般七種圖形:條形、田形、正7形、反7形、T形、Z形和反Z形,如生成條形:
map[0][randPos]=map[0][randPos-1]=map[0][randPos+1]
=map[0][randPos+2]=State.ACTIVE;123
生成圖形後,實現下落的操作。如果遇到阻礙,則不能再繼續下落:
isFall=true;//是否能夠下落
//從當前行檢查,如果遇到阻礙,則停止下落
for(inti=0;i<blockRows;i++){
for(intj=0;j<columns;j++){
//遍歷到行中塊為活動塊,而下一行塊為靜止塊,則遇到阻礙
if(map[rowIndex-i][j]==State.ACTIVE
&&map[rowIndex-i+1][j]==State.STOPED){
isFall=false;//停止下落
break;
}
}
if(!isFall)
break;
}123456789101112131415
如果未遇到阻礙,則下落的時候,方塊圖形整體向下移動一行:
//圖形下落一行
for(inti=0;i<blockRows;i++){
for(intj=0;j<columns;j++){
if(map[rowIndex-i][j]==State.ACTIVE){//活動塊向下移動一行
map[rowIndex-i][j]=State.EMPTY;//原活動塊變成空塊
map[rowIndex-i+1][j]=State.ACTIVE;//下一行塊變成活動塊
}
}
}12345678910
向左、向右方向移動時是類似的操作:
/**
*向左走
*/
privatevoidleft(){
//標記左邊是否有阻礙
booleanhasBlock=false;
/*判斷是否左邊有阻礙*/
for(inti=0;i<blockRows;i++){
if(map[rowIndex-i][0]==State.ACTIVE){//判斷左邊是否為牆
hasBlock=true;
break;//有阻礙,不用再循環判斷行
}else{
for(intj=1;j<columns;j++){//判斷左邊是否有其它塊
if(map[rowIndex-i][j]==State.ACTIVE
&&map[rowIndex-i][j-1]==State.STOPED){
hasBlock=true;
break;//有阻礙,不用再循環判斷列
}
}
if(hasBlock)
break;//有阻礙,不用再循環判斷行
}
}
/*左邊沒有阻礙,則將圖形向左移動一個塊的距離*/
if(!hasBlock){
for(inti=0;i<blockRows;i++){
for(intj=1;j<columns;j++){
if(map[rowIndex-i][j]==State.ACTIVE){
map[rowIndex-i][j]=State.EMPTY;
map[rowIndex-i][j-1]=State.ACTIVE;
}
}
}
//重繪
repaint();
}
}3738394041
向下加速移動時,就是減小每次正常狀態下落的時間間隔:
/**
*向下直走
*/
privatevoiddown(){
//標記可以加速下落
immediate=true;
}12345678
如何變換圖形方向,這里僅使用了非常簡單的方法來實現方向變換,當然可以有更優的演算法實現方向變換操作,大家可以自己研究:
/**
*旋轉方塊圖形
*/
privatevoidrotate(){
try{
if(shape==4){//方形,旋轉前後是同一個形狀
return;
}elseif(shape==0){//條狀
//臨時數組,放置旋轉後圖形
State[][]tmp=newState[4][4];
intstartColumn=0;
//找到圖形開始的第一個方塊位置
for(inti=0;i<columns;i++){
if(map[rowIndex][i]==State.ACTIVE){
startColumn=i;
break;
}
}
//查找旋轉之後是否有阻礙,如果有阻礙,則不旋轉
for(inti=0;i<4;i++){
for(intj=0;j<4;j++){
if(map[rowIndex-3+i][j+startColumn]==State.STOPED){
return;
}
}
}
if(map[rowIndex][startColumn+1]==State.ACTIVE){//橫向條形,變換為豎立條形
for(inti=0;i<4;i++){
tmp[i][0]=State.ACTIVE;
for(intj=1;j<4;j++){
tmp[i][j]=State.EMPTY;
}
}
blockRows=4;
}else{//豎立條形,變換為橫向條形
for(intj=0;j<4;j++){
tmp[3][j]=State.ACTIVE;
for(inti=0;i<3;i++){
tmp[i][j]=State.EMPTY;
}
}
blockRows=1;
}
//將原地圖中圖形修改為變換後圖形
for(inti=0;i<4;i++){
for(intj=0;j<4;j++){
map[rowIndex-3+i][startColumn+j]=tmp[i][j];
}
}
}else{
//臨時數組,放置旋轉後圖形
State[][]tmp=newState[3][3];
intstartColumn=columns;
//找到圖形開始的第一個方塊位置
for(intj=0;j<3;j++){
for(inti=0;i<columns;i++){
if(map[rowIndex-j][i]==State.ACTIVE){
startColumn=i<startColumn?i:startColumn;
}
}
}
//判斷變換後是否會遇到阻礙
for(inti=0;i<3;i++){
for(intj=0;j<3;j++){
if(map[rowIndex-2+j][startColumn+2-i]==State.STOPED)
return;
}
}
//變換
for(inti=0;i<3;i++){
for(intj=0;j<3;j++){
tmp[2-j][i]=map[rowIndex-2+i][startColumn+j];
}
}
//將原地圖中圖形修改為變換後圖形
for(inti=0;i<3;i++){
for(intj=0;j<3;j++){
map[rowIndex-2+i][startColumn+j]=tmp[i][j];
}
}
//重繪
repaint();
//重新修改行指針
for(inti=0;i<3;i++){
for(intj=0;j<3;j++){
if(map[rowIndex-i][startColumn+j]!=null
||map[rowIndex-i][startColumn+j]!=State.EMPTY){
rowIndex=rowIndex-i;
blockRows=3;
return;
}
}
}
}
}catch(Exceptione){
//遇到數組下標越界,說明不能變換圖形形狀,不作任何處理
}
}3738394
當圖形下落遇到阻礙時停止,我們就需要判斷這時是否有某一行或幾行可以消除掉,這時可以先獲取每行中方塊的個數,然後再進行判斷:
int[]blocksCount=newint[rows];//記錄每行有方塊的列數
inteliminateRows=0;//消除的行數
/*計算每行方塊數量*/
for(inti=0;i<rows;i++){
blocksCount[i]=0;
for(intj=0;j<columns;j++){
if(map[i][j]==State.STOPED)
blocksCount[i]++;
}
}1234567891011
如果有滿行的方塊,則消除掉該行方塊:
/*實現有滿行的方塊消除操作*/
for(inti=0;i<rows;i++){
if(blocksCount[i]==columns){
//清除一行
for(intm=i;m>=0;m--){
for(intn=0;n<columns;n++){
map[m][n]=(m==0)?State.EMPTY:map[m-1][n];
}
}
eliminateRows++;//記錄消除行數
}
}12345678910111213
最後我們再重繪顯示積分就可以了。
重復以上的生成圖形、圖形下落、左右下移動、判斷消除行的操作,一個簡單的俄羅斯方塊就完成了。
❸ java編寫的俄羅斯方塊游戲
以下為一個渣鄭俄羅斯方塊的源代碼,以---------線分隔一個類。
郁悶太長了,不能全部粘貼上來,要的基梁並話搏跡在線M我吧。
import javax.microedition.midlet.*;
import javax.microedition.lci.*;
import java.io.IOException;
/**
* <p>Title: 俄羅斯方塊</p>
*
* <p>Description: 俄羅斯方塊游戲</p>
*
* <p>Copyright: Copyright (c) 2005</p>
*
* <p>Company: Star Group</p>
*
* @author: Part of this programe comes from a open-source project in the Web(www.hyweb.net).
* Our group makes some remakeble improvement to it.
* @version 1.0
*/
public class RussianGameMIDlet extends MIDlet {
static RussianGameMIDlet instance;
private UIController controller = new UIController(this);
private Splash splash;
private Image imgStart;
Display display = null;
public RussianGameMIDlet() {
instance = this;
display = Display.getDisplay(this);
}
public void startApp() {
try
{
imgStart = Image.createImage("/start.png");
} catch (IOException e) {
}
StringBuffer infoStart = new StringBuffer("俄羅斯方塊");
splash = new Splash(this.controller,infoStart, imgStart);
controller.setSplash(splash);
controller.handleEvent(UIController.EventID.EVENT_START_SPLASH);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public static void quitApp() {
instance.destroyApp(true);
instance.notifyDestroyed();
instance = null;
}
}
--------------------------------------------------------------------------------------------------------------------------------------------
❹ java的俄羅斯方塊代碼
俄羅斯方塊——java源代碼提供
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;i<rowNum;i++)
for (int j=0; j<columnNum;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;i<rowNum;i++){
boolean isfull = true;
L1:for(int j=0;j<columnNum;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 (temp<0||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=k>>1;
}
}
}
}
//定時線程
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);
}
}
❺ java 淇勭綏鏂鏂瑰潡
import java.awt.*;
import java.awt.event.*;
//淇勭綏鏂鏂瑰潡綾
public class Mytest 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){
Mytest ers = new Mytest("淇勭綏鏂鏂瑰潡娓告垙");
WindowListener win_listener = new WinListener();
ers.addWindowListener(win_listener);
}
// 淇勭綏鏂鏂瑰潡綾葷殑鏋勯犳柟娉
Mytest(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綾伙紝浣縋anel鐨勫洓鍛ㄧ暀絀洪棿
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; //姝f柟鏍肩殑琛屾暟
int columnNum; //姝f柟鏍肩殑鍒楁暟
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;i<rowNum;i++)
for (int j=0; j<columnNum;j++)
scrArr[i][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[i][j]);
}
// 鐢繪柟鍧楃殑鏂規硶
public void drawUnit(int row,int col,int type){
scrArr[row][col] = type;
Graphics g = getGraphics();
switch(type){ //琛ㄧず鐢繪柟蹇鐨勬柟娉
case 0: g.setColor(Color.black);break; //浠ヨ儗鏅涓洪滆壊鐢
case 1: g.setColor(Color.blue);break; //鐢繪e湪涓嬭惤鐨勬柟鍧
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;i<rowNum;i++){
boolean isfull = true;
L1:for(int j=0;j<columnNum;j++)
if(scrArr[i][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[i][j] == 0)
drawUnit(k-1,j,0);
else
drawUnit(k-1,j,2);
scrArr[k-1][j] = scrArr[i][j];
}
}
for(int i = k-1 ;i < rowNum; i++){
for(int j = 0; j < columnNum; j++){
drawUnit(i,j,0);
scrArr[i][j]=0;
}
}
Mytest.score += full_line_num;
Mytest.scoreField.setText(""+Mytest.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(!Mytest.isPlay)
return;
switch(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){
switch(curButton){
case button_play:if(!Mytest.isPlay){
scr.initScr();
Mytest.isPlay = true;
Mytest.score = 0;
Mytest.scoreField.setText("0");
Mytest.timer.resume();
}
scr.requestFocus();
break;
case button_levelup:if(Mytest.level < 10){
Mytest.level++;
Mytest.levelField.setText(""+Mytest.level);
Mytest.score = 0;
Mytest.scoreField.setText(""+Mytest.score);
}
scr.requestFocus();
break;
case button_leveldown:if(Mytest.level > 1){
Mytest.level--;
Mytest.levelField.setText(""+Mytest.level);
Mytest.score = 0;
Mytest.scoreField.setText(""+Mytest.score);
}
scr.requestFocus();
break;
case button_pause:if(pause_resume){
Mytest.timer.suspend();
pause_resume = false;
}else{
Mytest.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);
}
}
// 鍒ゆ柇鏄鍚︽g『鐨勬柟娉
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 (temp<0||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=k>>1;
}
}
}
}
//瀹氭椂綰跨▼
class MyTimer extends Thread{
GameCanvas scr;
public MyTimer(GameCanvas scr){
this.scr = scr;
}
public void run(){
while(true){
try{
sleep((10-Mytest.level + 1)*100);
}
catch(InterruptedException e){}
if(!scr.getBlock().fallDown()){
scr.deleteFullLine();
if(scr.isGameEnd()){
Mytest.isPlay = false;
suspend();
}else
scr.getBlock().reset();
}
}
}
}
class WinListener extends WindowAdapter{
public void windowClosing (WindowEvent l){
System.exit(0);
}
}