俄罗斯方块
程序代码:
package com.huawei.test; import java.awt.*; import java.awt.event.*; import java.util.Timer; import java.util.TimerTask; import javax.swing.*; public class Test0127 extends JPanel { /** * */ private static final long serialVersionUID = 1L; @Override public void paint(Graphics g) { g.setColor(Color.white); g.fillRect(0, 0, 400, 520); for(int i = 0; i < area.length; i++) { for(int j = 0; j < area[i].length; j++) { if(area[i][j] == 0) { g.setColor(Color.lightGray); for(int ii = 0; ii < moveObj.length; ii++) { if(moveObj[ii]/20==i && moveObj[ii]%20==j) { g.setColor(Color.pink); break; } } } else { g.setColor(Color.pink); } g.fill3DRect(i*size, (area[i].length-1-j)*size, size, size, true); g.setColor(Color.pink); g.setFont(new Font("gbk", Font.BOLD|Font.ITALIC, 24)); g.drawString("得分:"+score, 300, 40); } } } long moveIndex = 0; int size = 24; int[][] area = new int[12][20]; int[] moveObj = new int[4]; int score; public Test0127() { JFrame jframe = new JFrame("Test"); jframe.add(this); jframe.setSize(400, 520); jframe.setLocation(200, 40); jframe.setVisible(true); jframe.setResizable(false); jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); moveObj = new int[] {20-2, 20-1, 20*2-2, 20*2-1}; jframe.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_LEFT) { if(moveObj[0] > 20) { for(int i = 0; i < moveObj.length; i++) { moveObj[i] = moveObj[i] - 20; } } } if(e.getKeyCode() == KeyEvent.VK_RIGHT) { if(moveObj[3] < (12-1)*20) { for(int i = 0; i < moveObj.length; i++) { moveObj[i] = moveObj[i] + 20; } } } } }); new Timer().schedule(new TimerTask() { @Override public void run() { if(moveIndex % 4 == 0) { int[] tmpMoveObj = new int[4]; if(moveObj[0] % 20 > 0) { for(int i = 0; i < moveObj.length; i++) { tmpMoveObj[i] = moveObj[i] - 1; if(area[tmpMoveObj[i]/20][tmpMoveObj[i]%20] == 1) { tmpMoveObj = null; break; } } moveObj = tmpMoveObj == null ? moveObj : tmpMoveObj; } else { tmpMoveObj = null; } if(tmpMoveObj == null) { for(int i = 0; i < moveObj.length; i++) { area[moveObj[i]/20][moveObj[i]%20] = 1; } for(int j = 20 - 1; j >= 0; j--) { int k = 0; for(int i = 0; i < area.length; i++)k+=area[i][j]; if(k == area.length) { for(int jj = j; jj < 20-1; jj++) { for(int i = 0; i < area.length; i++)area[i][jj]=area[i][jj+1]; } score++; } } moveObj = new int[] {20-2, 20-1, 20*2-2, 20*2-1}; } } repaint(); moveIndex++ ; } }, 10, 100); } public static void main(String[] args) { new Test0127(); } }