俄罗斯方块——java源代码
经典俄罗斯方块代码(转javascript代码)
经典俄罗斯⽅块代码(转javascript代码)在⽹上发现⼀篇60⾏javascript超经典俄罗斯⽅块代码,值得学习,转为Delphi如下,有详细注释,不再另讲解:unit Block_Unit;interfaceusesWinapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Grids, Vcl.ExtCtrls;typeTBlockForm = class(TForm)Button1: TButton;procedure Button1Click(Sender: TObject);procedure FormCreate(Sender: TObject);procedure FormPaint(Sender: TObject);privateprocedure WMMyKey(var Msg: TWMKeyDown); message WM_KEYDOWN;publicend;typeTIntArr=array of TArray<Integer>;type TBlock=recordx,y,s:Integer;fk:array [0..3] of Integer;//fk记录⽅块,4X4⼆进制矩阵end;varBlockForm: TBlockForm;Map:array of Integer;Tetris: TIntArr= [[$6600],//⽅块,⼆进制数据显⽰⽅块[$2222, $0f00],//I型[$c600, $2640],//Z型[$6c00, $4620],//反Z型[$4460, $2e0, $6220, $740],//L型[$2260, $0e20, $6440, $4700], //反L型[$2620, $720, $2320, $2700]]; //T型;pos,bak:TBlock;//pos当前⽅块数据,bak备份当前⽅块数据dia:TArray<Integer>;rs:TResourceStream;procedure Rotate(r:Integer);procedure GameStart;procedure UpdateMap(b:Boolean);function HaveBlock:Boolean;procedure BlockMove(r:Integer);implementationuses Vcl.Imaging.jpeg;varGreen,Red:TJPEGImage;{$R *.dfm}{此游戏的核⼼思路是⽤⼆进制来记录整个界⾯的变化,每个⽅块设定为4X4的⼆进制矩阵,整个游戏界⾯设定为10列、22⾏。
俄罗斯方块代码
1./*2.*虚拟的单个方格类,控制方格的颜色3.*/4.class RussiaBox implements Cloneable5.{6. private boolean isColor;7.8. public RussiaBox(boolean isColor)9. {10. this.isColor = isColor;11. }12. /*13. *设置颜色14. */15. public void setColor(boolean isColor)16. {17. this.isColor=isColor;18. }19. /*20. *返回颜色21. */22. public boolean isColorBox()23. {24. return isColor;25. }26. /*27. * @see ng.Object#clone()28. */29. public Object clone()30. {31. Object o = null;32. try33. {34. o=super.clone();35. }catch(CloneNotSupportedException e)36. {37. e.printStackTrace();38. }39. return o;40. }41.}42./*43. * 游戏中方块显示的画布类44. */45.import java.awt.*;46.import java.awt.event.*;47.import javax.swing.*;48.import javax.swing.border.*;49.50.class GameCanvas extends JPanel51.{52. private RussiaBox [][]boxes;53. private int rows = 20 , cols = 12;54. private static GameCanvas canvas=null;55. private int boxWidth, boxHeight;//默认为零需要调用fanning函数设置56. private Color blockColor = Color.RED, bgColor = new Color(0,204,204);57. private EtchedBorder border=new EtchedBorder(EtchedBorder.RAISED,Color.WHITE, new Color(148, 145, 140)) ;58.59. /*60. *采用单件模式,构造函数私有61. */62. private GameCanvas()63. {64. boxes = new RussiaBox[rows][cols];65.66. for(int i = 0; i < boxes.length; i ++)67. for(int j = 0; j<boxes[i].length; j ++)68. boxes[i][j] = new RussiaBox(false);69.70. setBorder(border);71. }72. /*73. *获得GameCanvas实例74. */75. public static GameCanvas getCanvasInstance()76. {77. if(canvas == null)78. canvas = new GameCanvas();79.80. return canvas;81. }82. /*83. *设置画布的背景色84. */85. public void setBgColor(Color bgColor)86. {87. this.bgColor = bgColor;88. }89. /*90. * 获得画布的背景色91. */92. public Color getBgColor()93. {94. return bgColor;95. }96. /*97. *设置方块的颜色98. */99. public void setBlockColor(Color blockColor) 100. {101. this.blockColor = blockColor; 102. }103. /*104. *方块的颜色105. */106. public Color getBlockColor()107. {108. return blockColor;109. }110. /*111. *设置画布中方块的行数112. */113. public void setRows(int rows)114. {115. this.rows = rows;116. }117. /*118. *得到画布中方块的行数119. */120. public int getRows()121. {122. return rows;123. }124. /*125. *设置画布中方块的列数126. */127. public void setCols(int cols)128. {129. this.cols = cols;130. }131. /*132. *得到画布中方块的列数133. */134. public int getCols()135. {136. return cols;137. }138. /*139. *得到row行,col列的方格140. */141. public RussiaBox getBox(int row, int col)142. {143. if(row >= 0 && row < rows && col >= 0 && col < cols) 144. return boxes[row][col];145.146. else147. return null;148. }149. /*150. *在画布中绘制方块151. */152. public void paintComponent(Graphics g)153. {154. super.paintComponent(g);155.156. fanning();157. for(int i = 0; i < boxes.length; i ++)158. for(int j = 0; j < boxes[i].length; j ++)159. {160. Color color = boxes[i][j].isColorBox() ? blockCo lor : bgColor;161. g.setColor(color);162. g.fill3DRect(j * boxWidth, i * boxHeight , boxWi dth , boxHeight , true);163. }164. }165. /*166. *清除第row行167. */168. public void removeLine(int row)169. {170. for(int i = row; i > 0; i --)171. for(int j = 0; j < cols; j ++)172. {173. boxes[i][j] = (RussiaBox)boxes[i-1][j].clone();174. }175. }176. /*177. *重置为初始时的状态178. */179. public void reset()180. {181. for(int i = 0; i < boxes.length; i++)182. for(int j = 0 ;j < boxes[i].length; j++)183. {184. boxes[i][j].setColor(false);185. }186. repaint();187. }188. /*189. * 根据窗体的大小自动调整方格的大小190. */191. public void fanning()192. {193. boxWidth = getSize().width / cols;194. boxHeight = getSize().height / rows;195. }196.197.}198./*199. * 方块类200. */201.class RussiaBlock extends Thread202.{203. private int style,y,x,level;204. private boolean moving,pausing;205. private RussiaBox boxes[][];206. private GameCanvas canvas;207.208. public final static int ROWS = 4;209. public final static int COLS = 4;210. public final static int BLOCK_KIND_NUMBER = 7;211. public final static int BLOCK_STATUS_NUMBER = 4; 212. public final static int BETWEEN_LEVELS_TIME = 50; 213. public final static int LEVEL_FLATNESS_GENE = 3; 214.216. *方块的所有风格及其不同的状态217. */218. public final static int[][] STYLES = {// 共28种状态219. {0x0f00, 0x4444, 0x0f00, 0x4444}, // 长条型的四种状态220. {0x04e0, 0x0464, 0x00e4, 0x04c4}, // 'T'型的四种状态221. {0x4620, 0x6c00, 0x4620, 0x6c00}, // 反'Z'型的四种状态222. {0x2640, 0xc600, 0x2640, 0xc600}, // 'Z'型的四种状态223. {0x6220, 0x1700, 0x2230, 0x0740}, // '7'型的四种状态224. {0x6440, 0x0e20, 0x44c0, 0x8e00}, // 反'7'型的四种状态225. {0x0660, 0x0660, 0x0660, 0x0660}, // 方块的四种状态226. };227. /*228. *构造函数229. */230. public RussiaBlock(int y,int x,int level,int style) 231. {232.233. this.y = y;234. this.x = x;235. this.level = level;236. moving = true;237. pausing = false;238. this.style = style;239.240. canvas = GameCanvas.getCanvasInstance();241.242. boxes = new RussiaBox[ROWS][COLS];243. int key = 0x8000;244. for(int i = 0; i < boxes.length; i++)245. for(int j = 0; j < boxes[i].length; j++)246. {247. boolean isColor = ( (style & key) != 0 ); 248. boxes[i][j] = new RussiaBox(isColor);249. key >>= 1;250. }251. display();252. }253. /*254. *线程的 run方法控制放块的下落及下落速度255. */256. public void run()258. while(moving)259. {260. try261. {262. sleep( BETWEEN_LEVELS_TIME * (RussiaBlocksGame.MAX_LEV EL - level + LEVEL_FLATNESS_GENE) );263. if(!pausing)264. moving = ( moveTo(y + 1,x) && moving ); 265. }catch(InterruptedException e)266. {267. e.printStackTrace();268. }269. }270. }271. /*272. *暂停移动273. */274. public void pauseMove()275. {276. pausing = true;277. }278. /*279. *从暂停状态恢复280. */281. public void resumeMove()282. {283. pausing = false;284. }285.286. /*287. *停止移动288. */289. public void stopMove()290. {291. moving = false;292. }293./*294. *向左移一格295. */296. public void moveLeft()297. {298. moveTo(y , x - 1);299. }301. *向右移一格302. */303. public void moveRight()304. {305. moveTo(y , x + 1);306. }307. /*308. *向下移一格,返回与其他几个不同,为了一键到底309. */310. public boolean moveDown()311. {312. if(moveTo(y + 1, x))313. return true;314. else315. return false;316. }317. /*318. *移到newRow,newCol位置319. */320. public synchronized boolean moveTo(int newRow, int newCol )321. {322. //erase();//必须在判断前进行擦除,否则isMoveable将产生错误行为323.324. if(!moving || !isMoveable(newRow,newCol))325. {326. display();327. return false;328. }329. y = newRow;330. x = newCol;331. display();332. canvas.repaint();333. return true;334. }335. /*336. *判断能否移到newRow,newCol位置337. */338. private boolean isMoveable(int newRow, int newCol) 339. {340. erase();341. for(int i = 0; i < boxes.length; i ++)342. for(int j = 0; j< boxes[i].length; j ++ )343. {344. if( boxes[i][j].isColorBox() )345. {346. RussiaBox box = canvas.getBox(newRow + i, newC ol + j);347. if(box == null || box.isColorBox())348. return false;349. }350. }351. return true;352. }353. /*354. *通过旋转变为下一种状态355. */356. public void turnNext()357. {358. int newStyle = 0;359. for(int i = 0; i < STYLES.length; i ++)360. for(int j = 0 ;j < STYLES[i].length; j++)361. {362. if(style == STYLES[i][j])363. {364. newStyle = STYLES[i][(j + 1)%BLOCK_STATUS_NUMB ER];365. break;366. }367. }368. turnTo(newStyle);369. }370. /*371. *通过旋转变能否变为newStyle状态372. */373. private synchronized boolean turnTo(int newStyle) 374. {375. //erase();//擦除之后在判断isTurnNextAble376. if(!moving || !isTurnable(newStyle))377. {378. display();379. return false;380. }381.382. style=newStyle;383. int key = 0x8000;384.385. for(int i = 0; i < boxes.length; i ++)386. for(int j = 0 ;j < boxes[i].length; j++)387. {388. boolean isColor = ((key & style) != 0 );389. boxes[i][j].setColor(isColor);390. key >>=1;391. }392. display();393. canvas.repaint();394. return true;395. }396. /*397. *判断通过旋转能否变为下一种状态398. */399. private boolean isTurnable(int newStyle)400. {401. erase();402. int key = 0x8000;403. for(int i = 0; i< boxes.length; i++)404. for(int j=0; j<boxes[i].length; j++)405. {406. if((key & newStyle) != 0)407. {408. RussiaBox box = canvas.getBox(y + i, x + j);409. if(box == null || box.isColorBox())410. return false;411. }412. key >>= 1;413. }414. return true;415. }416. /*417. *擦除当前方块(只是设置isColor属性,颜色并没有清除,为了判断能否移动之用)418. */419. private void erase()420. {421. for(int i = 0; i < boxes.length; i ++)422. for(int j = 0; j< boxes[i].length; j ++ )423. {424. if( boxes[i][j].isColorBox() )425. {426. RussiaBox box = canvas.getBox( y + i, x + j);427. if(box != null)428. box.setColor(false);429. }430. }431. }432. /*433. *显示当前方块(其实只是设置Color属性,在调用repaint方法时才真正显示)434. */435. private void display()436. {437. for(int i = 0; i < boxes.length; i ++)438. for(int j = 0;j< boxes[i].length ; j ++)439. {440. if(boxes[i][j].isColorBox())441. {442. RussiaBox box = canvas.getBox( y + i, x + j); 443. if(box != null)444. box.setColor( true );445. }446. }447. }448.}449./*450. * 控制面板类451. */452.import java.awt.*;453.import java.awt.event.*;454.import javax.swing.*;455.import javax.swing.border.*;456.457.class ControlPanel extends JPanel458.{459. private TipBlockPanel tipBlockPanel;460. private JPanel tipPanel,InfoPanel,buttonPanel;461. private final JTextField levelField,scoreField;462. private JButton playButton,pauseButton,stopButton, 463. turnHarderButton,turnEasilyButton; 464. private EtchedBorder border=new EtchedBorder(EtchedBorde r.RAISED,Color.WHITE, new Color(148, 145, 140)) ;465.466. private RussiaBlocksGame game;467. private Timer timer;468.469. public ControlPanel(final RussiaBlocksGame game) 470. {471. this.game = game;472. /*473. *图形界面部分474. */475. setLayout(new GridLayout(3,1,0,4));476.477. tipBlockPanel = new TipBlockPanel();478. tipPanel = new JPanel( new BorderLayout() );479. tipPanel.add( new JLabel("Next Block:") , BorderLayout.N ORTH );480. tipPanel.add( tipBlockPanel , BorderLayout.CENTER ); 481. tipPanel.setBorder(border);482.483. InfoPanel = new JPanel( new GridLayout(4,1,0,0) ); 484. levelField = new JTextField(""+RussiaBlocksGame.DEFAULT_ LEVEL);485. levelField.setEditable(false);486. scoreField = new JTextField("0");487. scoreField.setEditable(false);488. InfoPanel.add(new JLabel("Level:"));489. InfoPanel.add(levelField);490. InfoPanel.add(new JLabel("Score:"));491. InfoPanel.add(scoreField);492. InfoPanel.setBorder(border);493.494. buttonPanel = new JPanel(new GridLayout(5,1,0,0)); 495. playButton = new JButton("Play");496. pauseButton = new JButton("Pause");497. stopButton = new JButton("Stop");498. turnHarderButton = new JButton("Turn harder");499. turnEasilyButton = new JButton("Turn easily");500.501. buttonPanel.add(playButton);502. buttonPanel.add(pauseButton);503. buttonPanel.add(stopButton);504. buttonPanel.add(turnHarderButton);505. buttonPanel.add(turnEasilyButton);506. buttonPanel.setBorder(border);507.508. addKeyListener(new ControlKeyListener());//添加510. add(tipPanel);511. add(InfoPanel);512. add(buttonPanel);513. /*514. *添加事件监听器515. */516. playButton.addActionListener(517. new ActionListener()518. {519. public void actionPerformed(ActionEvent event) 520. {521. game.playGame();522. requestFocus();//让ControlPanel重新获得焦点以响应键盘事件523. }524. });525.526. pauseButton.addActionListener(527. new ActionListener()528. {529. public void actionPerformed(ActionEvent event) 530. {531. if(pauseButton.getText().equals("Pause"))532. game.pauseGame();533. else534. game.resumeGame();535. requestFocus();//让ControlPanel重新获得焦点以响应键盘事件536. }537. }538. );539. stopButton.addActionListener(540. new ActionListener()541. {542. public void actionPerformed(ActionEvent event) 543. {544. game.stopGame();545. requestFocus();//让ControlPanel重新获得焦点以响应键盘事件546. }547. });548. turnHarderButton.addActionListener(549. new ActionListener()551. public void actionPerformed(ActionEvent event) 552. {553. int level = 0;554. try{555. level = Integer.parseInt(levelField.getText());556. setLevel(level + 1);557. }catch(NumberFormatException e)558. {559. e.printStackTrace();560. }561. requestFocus();//让ControlPanel重新获得焦点以响应键盘事件562. }563. });564. turnEasilyButton.addActionListener(565. new ActionListener()566. {567. public void actionPerformed(ActionEvent event) 568. {569. int level = 0;570. try{571. level = Integer.parseInt(levelField.getText());572. setLevel(level - 1);573. }catch(NumberFormatException e)574. {575. e.printStackTrace();576. }577. requestFocus();//让ControlPanel重新获得焦点以响应键盘事件578. }579. });580. /*581. * 时间驱动程序,每格500毫秒对level,score值进行更新582. */583. timer = new Timer(500,584. new ActionListener()585. {586. public void actionPerformed(ActionEvent event) 587. {588. scoreField.setText(""+game.getScore());589. game.levelUpdate();591. }592. );593. timer.start();594. }595. /*596. * 设置预显方块的样式597. */598. public void setBlockStyle(int style)599. {600. tipBlockPanel.setStyle(style);601. tipBlockPanel.repaint();602. }603. /*604. * 重置,将所有数据恢复到最初值605. */606. public void reset()607. {608. levelField.setText(""+RussiaBlocksGame.DEFAULT_LEVEL);609. scoreField.setText("0");610. setPlayButtonEnabled(true);611. setPauseButtonLabel(true);612. tipBlockPanel.setStyle(0);613. }614.615. /*616. *设置playButton是否可用617. */618. public void setPlayButtonEnabled(boolean enable) 619. {620. playButton.setEnabled(enable);621. }622.623. /*624. *设置pauseButton的文本625. */626. public void setPauseButtonLabel(boolean pause)627. {628. pauseButton.setText( pause ? "Pause" : "Rusume" ); 629. }630.631. /*632. *设置方块的大小,改变窗体大小时调用可自动调整方块到合适的尺寸633. */634. public void fanning()635. {636. tipBlockPanel.fanning();637. }638. /*639. *根据level文本域的值返回当前的级别640. */641. public int getLevel()642. {643. int level = 0;644. try645. {646. level=Integer.parseInt(levelField.getText()); 647. }catch(NumberFormatException e)648. {649. e.printStackTrace();650. }651. return level;652. }653. /*654. * 设置level文本域的值655. */656. public void setLevel(int level)657. {658. if(level > 0 && level <= RussiaBlocksGame.MAX_LEVEL)659. levelField.setText("" + level);660. }661. /*662. * 内部类为预显方块的显示区域663. */664. private class TipBlockPanel extends JPanel665. {666. private Color bgColor = Color.darkGray,667. blockColor = Color.lightGray;668. private RussiaBox [][]boxes = new RussiaBox[RussiaBloc k.ROWS][RussiaBlock.COLS];669. private int boxWidth, boxHeight,style;670. private boolean isTiled = false;671.672. /*673. * 构造函数674. */675. public TipBlockPanel()676. {677. for(int i = 0; i < boxes.length; i ++)678. for(int j = 0; j < boxes[i].length; j ++)679. {680. boxes[i][j]=new RussiaBox(false);681. }682. style = 0x0000;683. }684. /*685. * 构造函数686. */687. public TipBlockPanel(Color bgColor, Color blockColor)688. {689. this();690. this.bgColor = bgColor;691. this.blockColor = blockColor;692. }693. /*694. * 设置方块的风格695. */696. public void setStyle(int style)697. {698. this.style = style;699. repaint();700. }701.702. /*703. * 绘制预显方块704. */705. public void paintComponent(Graphics g)706. {707. super.paintComponent(g);708.709. int key = 0x8000;710.711. if(!isTiled)712. fanning();713. for(int i = 0; i < boxes.length; i ++)714. for(int j = 0; j<boxes[i].length ;j ++)715. {716. Color color = (style & key) != 0 ? blockColor : bgColor;717. g.setColor(color);718. g.fill3DRect(j * boxWidth, i * boxHeight, boxWidt h, boxHeight, true);719. key >>=1;720. }721. }722. /*723. *设置方块的大小,改变窗体大小时调用可自动调整方块到合适的尺寸724. */725.726. public void fanning()727. {728. boxWidth = getSize().width / RussiaBlock.COLS; 729. boxHeight = getSize().height /RussiaBlock.ROWS; 730. isTiled=true;731. }732. }733. /*734. *内部类键盘键听器,响应键盘事件735. */736. class ControlKeyListener extends KeyAdapter {737. public void keyPressed(KeyEvent ke)738. {739. if (!game.isPlaying()) return;740.741. RussiaBlock block = game.getCurBlock();742. switch (ke.getKeyCode()) {743. case KeyEvent.VK_DOWN:744. block.moveDown();745. break;746. case KeyEvent.VK_LEFT:747. block.moveLeft();748. break;749. case KeyEvent.VK_RIGHT:750. block.moveRight();751. break;752. case KeyEvent.VK_UP:753. block.turnNext();754. break;755. case KeyEvent.VK_SPACE://一键到底756. while(block.moveDown())757. {758. }759. break;760. default:761. break;762. }763. }764. }765.}766./*767. * 主游戏类768. */769.import java.awt.*;770.import java.awt.event.*;771.import javax.swing.*;772.773.public class RussiaBlocksGame extends JFrame774.{775. public final static int PER_LINE_SCORE = 100;//消去一行得分776. public final static int PER_LEVEL_SCORE = PER_LINE_SCORE* 20;//升一级需要的分数777. public final static int DEFAULT_LEVEL = 5;//默认级别778. public final static int MAX_LEVEL = 10;//最高级别779. private int score=0,curLevelScore = 0;//总分和本级得分780.781. private GameCanvas canvas;782. private ControlPanel controlPanel;783. private RussiaBlock block;784.785. private int style = 0;786. boolean playing = false;787.788. private JMenuBar bar;789. private JMenu gameMenu,controlMenu,windowStyleMenu,inform ationMenu;790. private JMenuItem newGameItem,setBlockColorItem,setBgColo rItem,791. turnHardItem,turnEasyItem,exitItem;792. private JMenuItem playItem,pauseItem,resumeItem,stopIte m;793. private JRadioButtonMenuItem windowsRadioItem,motifRadi oItem,metalRadioItem;794. private JMenuItem authorItem,helpItem;795. private ButtonGroup buttonGroup;796. /*797. * 构造函数798. */799. public RussiaBlocksGame(String title)800. {801. super(title);802.803. setSize(300,400);804. Dimension scrSize=Toolkit.getDefaultToolkit().getScreen Size();805. setLocation((scrSize.width-getSize().width)/2,(scrSize.height-getSize().height)/2);806.807. createMenu();808. Container container=getContentPane();809. container.setLayout(new BorderLayout());810.811. canvas = GameCanvas.getCanvasInstance();812. controlPanel = new ControlPanel(this);813.814. container.add(canvas,BorderLayout.CENTER);815. container.add(controlPanel,BorderLayout.EAST); 816.817. addWindowListener(818. new WindowAdapter()819. {820. public void windowClosing(WindowEvent event)821. {822. stopGame();823. System.exit(0);824. }825. }826. );827.828. addComponentListener(829. new ComponentAdapter()830. {831. public void componentResized(ComponentEvent event) 832. {833. canvas.fanning();834. }835. }837. canvas.fanning();838. setVisible(true);839. }840. /*841. * 判断游戏是否正在进行842. */843. public boolean isPlaying()844. {845. return playing;846. }847. /*848. * 开始游戏并设置按钮和菜单项的可用性849. */850. public void playGame()851. {852. play();853. controlPanel.setPlayButtonEnabled(false); 854. playItem.setEnabled(false);855. }856. /*857. * 暂停游戏858. */859. public void pauseGame()860. {861. if(block != null) block.pauseMove(); 862. controlPanel.setPauseButtonLabel(false); 863. pauseItem.setEnabled(false);864. resumeItem.setEnabled(true);865. }866. /*867. * 从暂停中恢复游戏868. */869. public void resumeGame()870. {871. if(block != null) block.resumeMove(); 872. controlPanel.setPauseButtonLabel(true); 873. pauseItem.setEnabled(true);874. resumeItem.setEnabled(false);875. }876. /*877. * 停止游戏878. */879. public void stopGame()881. if(block != null) block.stopMove(); 882. playing = false;883. controlPanel.setPlayButtonEnabled(true); 884. controlPanel.setPauseButtonLabel(true); 885. playItem.setEnabled(true); 886. }887. /*888. * 得到当前级别889. */890. public int getLevel()891. {892. return controlPanel.getLevel();893. }894. /*895. * 设置当前级别,并更新控制面板的显示896. */897. public void setLevel(int level)898. {899. if(level>0&&level<11)900. controlPanel.setLevel(level);901. }902. /*903. * 得到当前总分数904. */905. public int getScore()906. {907. if(canvas != null)908. return score;909. return 0;910. }911. /*912. * 得到本级得分913. */914. public int getCurLevelScore()915. {916. if(canvas != null)917. return curLevelScore;918. return 0;919. }920. /*921. * 更新等级922. */923. public void levelUpdate()925. int curLevel = getLevel();926. if(curLevel < MAX_LEVEL && curLevelScore >= PER_LEVEL_ SCORE)927. {928. setLevel(curLevel + 1);929. curLevelScore -= PER_LEVEL_SCORE;930. }931. }932. /*933. * 获得当前得方块934. */935. public RussiaBlock getCurBlock() {936. return block;937. }938. /*939. * 开始游戏940. */941. private void play()942. {943. playing=true;944. Thread thread = new Thread(new Game());945. thread.start();946. reset();947. }948. /*949. * 重置950. */951. private void reset()952. {953. controlPanel.reset();954. canvas.reset();955. score = 0;956. curLevelScore = 0;957. }958. /*959. * 宣告游戏结束960. */961. private void reportGameOver()962. {963. JOptionPane.showMessageDialog(this,"Game over!"); 964. }965. /*966. * 创建菜单968. private void createMenu()969. {970. gameMenu = new JMenu("Game");971. newGameItem = new JMenuItem("New Game");972. setBlockColorItem = new JMenuItem("Set Block Color...") ;973. setBgColorItem = new JMenuItem("Set BackGround Color...");974. turnHardItem = new JMenuItem("Turn Harder");975. turnEasyItem = new JMenuItem("Turn Easily");976. exitItem = new JMenuItem("Exit");977. gameMenu.add(newGameItem);978. gameMenu.add(setBlockColorItem);979. gameMenu.add(setBgColorItem);980. gameMenu.add(turnHardItem);981. gameMenu.add(turnEasyItem);982. gameMenu.add(exitItem);983.984. controlMenu = new JMenu("Control");985. playItem = new JMenuItem("Play");986. pauseItem = new JMenuItem("Pause");987. resumeItem = new JMenuItem("Resume");988. stopItem = new JMenuItem("Stop");989. controlMenu.add(playItem);990. controlMenu.add(pauseItem);991. controlMenu.add(resumeItem);992. controlMenu.add(stopItem);993.994. windowStyleMenu = new JMenu("WindowStyle");995. buttonGroup = new ButtonGroup();996. windowsRadioItem = new JRadioButtonMenuItem("Windows") ;997. motifRadioItem = new JRadioButtonMenuItem("Motif"); 998. metalRadioItem = new JRadioButtonMenuItem("Mentel",true);999. windowStyleMenu.add(windowsRadioItem);1000. buttonGroup.add(windowsRadioItem);1001. windowStyleMenu.add(motifRadioItem);1002. buttonGroup.add(motifRadioItem);1003. windowStyleMenu.add(metalRadioItem);1004. buttonGroup.add(metalRadioItem);1005.1006. informationMenu = new JMenu("Information");1007. authorItem = new JMenuItem("Author:Fuliang"); 1008. helpItem = new JMenuItem("Help");1009. informationMenu.add(authorItem);1010. informationMenu.add(helpItem);1011.1012. bar = new JMenuBar();1013. bar.add(gameMenu);1014. bar.add(controlMenu);1015. bar.add(windowStyleMenu);1016. bar.add(informationMenu);1017.1018. addActionListenerToMenu();1019. setJMenuBar(bar);1020. }1021. /*1022. * 添加菜单响应1023. */1024. private void addActionListenerToMenu()1025. {1026. newGameItem.addActionListener(new ActionListener() { 1027. public void actionPerformed(ActionEvent ae) { 1028. stopGame();1029. reset();1030. setLevel(DEFAULT_LEVEL);1031. }1032. });1033.1034. setBlockColorItem.addActionListener(new ActionListener() {1035. public void actionPerformed(ActionEvent ae) { 1036. Color newBlockColor =1037. JColorChooser.showDialog(RussiaBlocksGame.this ,1038. "Set color for block", canvas.getBlock Color());1039. if (newBlockColor != null)1040. canvas.setBlockColor(newBlockColor);1041. }1042. });1043.1044. setBgColorItem.addActionListener(new ActionListener() {1045. public void actionPerformed(ActionEvent ae) { 1046. Color newBgColor =1047. JColorChooser.showDialog(RussiaBlocksGame.this ,"Set color for block",1048. canvas.getBgColor()); 1049. if (newBgColor != null)1050. canvas.setBgColor(newBgColor);1051. }1052. });1053.1054. turnHardItem.addActionListener(new ActionListener() { 1055. public void actionPerformed(ActionEvent ae) { 1056. int curLevel = getLevel();1057. if (curLevel < MAX_LEVEL) setLevel(curLevel + 1); 1058. }1059. });1060.1061. turnEasyItem.addActionListener(new ActionListener() { 1062. public void actionPerformed(ActionEvent ae) { 1063. int curLevel = getLevel();1064. if (curLevel > 1) setLevel(curLevel - 1);1065. }1066. });1067.1068. exitItem.addActionListener(new ActionListener() { 1069. public void actionPerformed(ActionEvent ae) { 1070. System.exit(0);1071. }1072. });1073. playItem.addActionListener(new ActionListener() { 1074. public void actionPerformed(ActionEvent ae) { 1075. playGame();1076. }1077. });1078.1079. pauseItem.addActionListener(new ActionListener() { 1080. public void actionPerformed(ActionEvent ae) { 1081. pauseGame();1082. }1083. });1084.1085. resumeItem.addActionListener(new ActionListener() { 1086. public void actionPerformed(ActionEvent ae) { 1087. resumeGame();1088. }1089. });。
俄罗斯方块完整源代码
//不多说,直接可以拷贝下面的东西,就可以运行。
package day04;import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.applet.*;import ng.String.*;import ng.*;import java.io.*;public class ERSBlock extends JPanel implements ActionListener,KeyListener//应该是继承JPanel{static Button but[] = new Button[6];static Button noStop = new Button("取消暂停"); static Label scoreLab = new Label("分数:");static Label infoLab = new Label("提示:");static Label speedLab = new Label("级数:");static Label scoreTex = new Label("0");static Label infoTex = new Label(" ");static Label speedTex = new Label("1");static JFrame jf = new JFrame();static MyTimer timer;static ImageIcon icon=new ImageIcon("resource/Block.jpg");static JMenuBar mb = new JMenuBar();static JMenu menu0 = new JMenu("游戏 ");static JMenu menu1 = new JMenu("帮助 ");static JMenuItem mi0 = new JMenuItem("新游戏"); static JMenuItem mi1 = new JMenuItem("退出");static JMenuItem mi1_0 = new JMenuItem("关于"); static JDialog dlg_1;static JTextArea dlg_1_text = new JTextArea(); static int startSign= 0;//游戏开始标志 0 未开始 1 开始 2 暂停static String butLab[] = {"开始游戏","重新开始","降低级数","提高级数","游戏暂停","退出游戏"};static int game_body[][] = new int[19][10];static int game_sign_x[] = new int[4];//用于记录4个方格的水平位置static int game_sign_y[] = new int[4];//用于记录4个方格的垂直位置static boolean downSign = false;//是否落下static int blockNumber = 1;//砖块的编号static int gameScore = 0;//游戏分数static int speedMark = 1;public static void main(String args[]) {ERSBlock myBlock = new ERSBlock();mb.add(menu0);mb.add(menu1);menu0.add(mi0);menu0.add(mi1);menu1.add(mi1_0);jf.setJMenuBar(mb);myBlock.init();jf.add(myBlock);jf.setSize(565,501);jf.setResizable(false);jf.setTitle("俄罗斯方块");jf.setIconImage(icon.getImage());jf.setLocation(200,100);jf.show();timer = new MyTimer(myBlock); //启动线程timer.setDaemon(true);timer.start();timer.suspend();}public void init(){setLayout(null);for(int i = 0;i < 6;i++){but[i] = new Button(butLab[i]);add(but[i]);but[i].addActionListener(this);but[i].addKeyListener(this);but[i].setBounds(360,(240 + 30 * i),160,25); }add(scoreLab);add(scoreTex);add(speedLab);add(speedTex);add(infoLab);add(infoTex);add(scoreLab);scoreLab.setBounds(320,15,30,20); scoreTex.setBounds(360,15,160,20); scoreTex.setBackground(Color.white); speedLab.setBounds(320,45,30,20); speedTex.setBounds(360,45,160,20); speedTex.setBackground(Color.white);but[1].setEnabled(false);but[4].setEnabled(false);infoLab.setBounds(320,75,30,20); infoTex.setBounds(360,75,160,20); infoTex.setBackground(Color.white); noStop.setBounds(360,360,160,25); noStop.addActionListener(this); noStop.addKeyListener(this);mi0.addActionListener(this);mi1.addActionListener(this);mi1_0.addActionListener(this);num_csh_game();rand_block();}public void actionPerformed(ActionEvent e){if(e.getSource() == but[0])//开始游戏{startSign = 1;infoTex.setText("游戏已经开始!");but[0].setEnabled(false);but[1].setEnabled(true);but[4].setEnabled(true);timer.resume();}if(e.getSource() == but[1]||e.getSource() == mi0)//重新开始游戏{startSign = 0;gameScore = 0;timer.suspend();num_csh_restart();repaint();rand_block();scoreTex.setText("0");infoTex.setText("新游戏!");but[0].setEnabled(true);but[1].setEnabled(false);but[4].setEnabled(false);}if(e.getSource() == but[2])//降低级数 {infoTex.setText("降低级数!"); speedMark--;if(speedMark <= 1){speedMark = 1;infoTex.setText("已经是最低级数!"); }speedTex.setText(speedMark + ""); }if(e.getSource() == but[3])//提高级数 {infoTex.setText("提高级数!");speedMark++;if(speedMark >= 9){speedMark = 9;infoTex.setText("已经是最高级数!"); }speedTex.setText(speedMark + ""); }if(e.getSource() == but[4])//游戏暂停 {this.add(noStop);this.remove(but[4]);infoTex.setText("游戏暂停!"); timer.suspend();}if(e.getSource() == noStop)//取消暂停 {this.remove(noStop);this.add(but[4]);infoTex.setText("继续游戏!"); timer.resume();}if(e.getSource() == but[5]||e.getSource() == mi1)//退出游戏{jf.dispose();}if(e.getSource() == mi1_0)//退出游戏{dlg_1 = new JDialog(jf,"关于");try{FileInputStream io = new FileInputStream("resource/guanyu.txt");//得到路径byte a[] = new byte[io.available()];io.read(a);io.close();String str = new String(a);dlg_1_text.setText(str);}catch(Exception g){}dlg_1_text.setEditable(false);dlg_1.add(dlg_1_text);dlg_1.pack();dlg_1.setResizable(false);dlg_1.setSize(200, 120);dlg_1.setLocation(400, 240);dlg_1.show();}}public void rand_block()//随机产生砖块{int num;num = (int)(Math.random() * 6) + 1;//产生0~6之间的随机数blockNumber = num;switch(blockNumber){case 1: block1(); blockNumber = 1; break;case 2: block2(); blockNumber = 2; break;case 3: block3(); blockNumber = 3; break;case 4: block4(); blockNumber = 4; break;case 5: block5(); blockNumber = 5; break;case 6: block6(); blockNumber = 6; break;case 7: block7(); blockNumber = 7; break;}}public void change_body(int blockNumber)//改变砖块状态{dingwei();if(blockNumber == 1&&downSign == false)//变换长条2种情况{if(game_sign_y[0] == game_sign_y[1]&&game_sign_y[3] <= 16)//说明长条是横着的{if(game_body[game_sign_y[0] - 1][game_sign_x[0] + 1] != 2&&game_body[game_sign_y[3] + 2][game_sign_x[3] - 2] != 2){num_csh_game();game_body[game_sign_y[0] - 1][game_sign_x[0] + 1] = 1;game_body[game_sign_y[1]][game_sign_x[1]] = 1;game_body[game_sign_y[2] + 1][game_sign_x[2] - 1] = 1;game_body[game_sign_y[3] + 2][game_sign_x[3] - 2] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_x[0] == game_sign_x[1]&&game_sign_x[0] >= 1&&game_sign_x[3] <= 7)//说明长条是竖着的{if(game_body[game_sign_y[0] +1][game_sign_x[0]-1] != 2&&game_body[game_sign_y[3] -2][game_sign_x[3] + 2] != 2){num_csh_game();game_body[game_sign_y[0] + 1][game_sign_x[0] - 1] = 1;game_body[game_sign_y[1]][game_sign_x[1]]=1;game_body[game_sign_y[2] - 1][game_sign_x[2] + 1] = 1;game_body[game_sign_y[3] - 2][game_sign_x[3] + 2] = 1;infoTex.setText("游戏进行中!");repaint();}}}if(blockNumber == 3&&downSign == false)//变换转弯1有4种情况{if(game_sign_x[0] == game_sign_x[1]&&game_sign_x[0] == game_sign_x[2]&&game_sign_y[2] == game_sign_y[3]&&game_sign_x[0] >= 1){if(game_body[game_sign_y[0] + 1][game_sign_x[0] - 1] != 2&&game_body[game_sign_y[2] - 1][game_sign_x[2] + 1] != 2&&game_body[game_sign_y[3] - 2][game_sign_x[3]] != 2){num_csh_game();game_body[game_sign_y[0] + 1][game_sign_x[0] - 1] = 1;game_body[game_sign_y[1]][game_sign_x[1]] = 1;= 1;game_body[game_sign_y[3] - 2][game_sign_x[3]] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[1] == game_sign_y[2]&&game_sign_y[2] == game_sign_y[3]&&game_sign_x[0] == game_sign_x[3]&&game_sign_y[1] <= 17){if(game_body[game_sign_y[0]][game_sign_x[0] - 2] != 2&&game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] != 2&&game_body[game_sign_y[3] - 1][game_sign_x[3] - 1] != 2){num_csh_game();game_body[game_sign_y[0]][game_sign_x[0] - 2] = 1;game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] = 1;game_body[game_sign_y[2]][game_sign_x[2]] = 1;= 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_x[1] == game_sign_x[2]&&game_sign_x[1] == game_sign_x[3]&&game_sign_y[0] == game_sign_y[1]&&game_sign_x[3] <= 8){if(game_body[game_sign_y[0] + 2][game_sign_x[0]] != 2&&game_body[game_sign_y[1] + 1][game_sign_x[1] - 1] != 2&&game_body[game_sign_y[3] - 1][game_sign_x[3] + 1] != 2){num_csh_game();game_body[game_sign_y[0] + 2][game_sign_x[0]] = 1;game_body[game_sign_y[1] + 1][game_sign_x[1] - 1] = 1;game_body[game_sign_y[2]][game_sign_x[2]] = 1;game_body[game_sign_y[3] - 1][game_sign_x[3] + 1]= 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[0] == game_sign_y[1]&&game_sign_y[1] == game_sign_y[2]&&game_sign_x[0] == game_sign_x[3]) {if(game_body[game_sign_y[0] + 1][game_sign_x[0] + 1] != 2&&game_body[game_sign_y[2] - 1][game_sign_x[2] - 1] != 2&&game_body[game_sign_y[3]][game_sign_x[3] + 2] != 2){num_csh_game();game_body[game_sign_y[0] + 1][game_sign_x[0] + 1] = 1;game_body[game_sign_y[1]][game_sign_x[1]] = 1;game_body[game_sign_y[2] - 1][game_sign_x[2] - 1] = 1;game_body[game_sign_y[3]][game_sign_x[3] + 2] = 1;infoTex.setText("游戏进行中!");repaint();}}}if(blockNumber == 4&&downSign == false)//变换转弯2有4种情况{if(game_sign_x[0] == game_sign_x[1]&&game_sign_x[0] == game_sign_x[3]&&game_sign_y[1] == game_sign_y[2]&&game_sign_x[3] <= 7){if(game_body[game_sign_y[0] + 2][game_sign_x[0]] != 2&&game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] != 2&&game_body[game_sign_y[3]][game_sign_x[3] + 2] != 2){num_csh_game();game_body[game_sign_y[0] + 2][game_sign_x[0]] = 1;game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] = 1;game_body[game_sign_y[2]][game_sign_x[2]] = 1;game_body[game_sign_y[3]][game_sign_x[3] + 2] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[1] == game_sign_y[2]&&game_sign_y[1] == game_sign_y[3]&&game_sign_x[0] == game_sign_x[2]) {if(game_body[game_sign_y[1]][game_sign_x[1] + 2] != 2&&game_body[game_sign_y[2] - 1][game_sign_x[2] + 1] != 2&&game_body[game_sign_y[3] - 2][game_sign_x[3]] != 2){num_csh_game();game_body[game_sign_y[0]][game_sign_x[0]] = 1;game_body[game_sign_y[1]][game_sign_x[1] + 2] = 1;game_body[game_sign_y[2] - 1][game_sign_x[2] + 1] = 1;game_body[game_sign_y[3] - 2][game_sign_x[3]] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_x[0] == game_sign_x[2]&&game_sign_x[0] == game_sign_x[3]&&game_sign_y[1] == game_sign_y[2]&&game_sign_x[0] >= 2){if(game_body[game_sign_y[0]][game_sign_x[0] - 2] != 2&&game_body[game_sign_y[2] - 1][game_sign_x[2] - 1] != 2&&game_body[game_sign_y[3] - 2][game_sign_x[3]] != 2){num_csh_game();game_body[game_sign_y[0]][game_sign_x[0] - 2] = 1;game_body[game_sign_y[1]][game_sign_x[1]] = 1;game_body[game_sign_y[2] - 1][game_sign_x[2] - 1] = 1;game_body[game_sign_y[3] - 2][game_sign_x[3]] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[0] == game_sign_y[1]&&game_sign_y[0] == game_sign_y[2]&&game_sign_x[1] == game_sign_x[3]&&game_sign_y[0] <= 16){if(game_body[game_sign_y[0] + 2][game_sign_x[0]] != 2&&game_body[game_sign_y[1] + 1][game_sign_x[1] - 1] != 2&&game_body[game_sign_y[2]][game_sign_x[2] - 2] != 2){num_csh_game();game_body[game_sign_y[0] + 2][game_sign_x[0]] = 1;game_body[game_sign_y[1] + 1][game_sign_x[1] - 1] = 1;game_body[game_sign_y[2]][game_sign_x[2] - 2] = 1;game_body[game_sign_y[3]][game_sign_x[3]] = 1;infoTex.setText("游戏进行中!");repaint();}}}if(blockNumber == 5&&downSign == false)//变换转弯3有4种情况{if(game_sign_x[0] == game_sign_x[2]&&game_sign_x[2] == game_sign_x[3]&&game_sign_y[0] == game_sign_y[1]&&game_sign_x[1] >= 2){if(game_body[game_sign_y[0] + 1][game_sign_x[0] -1] != 2&&game_body[game_sign_y[1]][game_sign_x[1] -2] != 2&&game_body[game_sign_y[3] - 1][game_sign_x[3] + 1] != 2){num_csh_game();game_body[game_sign_y[0] + 1][game_sign_x[0] - 1] = 1;game_body[game_sign_y[1]][game_sign_x[1] - 2] = 1;game_body[game_sign_y[2]][game_sign_x[2]] = 1;game_body[game_sign_y[3] - 1][game_sign_x[3] + 1] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[1] == game_sign_y[2]&&game_sign_y[2] == game_sign_y[3]&&game_sign_x[0] == game_sign_x[1]&&game_sign_y[0] <= 16){if(game_body[game_sign_y[0] + 2][game_sign_x[0]] != 2&&game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] != 2&&game_body[game_sign_y[3] - 1][game_sign_x[3] - 1] != 2){num_csh_game();game_body[game_sign_y[0] + 2][game_sign_x[0]] = 1;game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] = 1;game_body[game_sign_y[2]][game_sign_x[2]] = 1;game_body[game_sign_y[3] - 1][game_sign_x[3] - 1] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_x[0] == game_sign_x[1]&&game_sign_x[1] == game_sign_x[3]&&game_sign_y[2] == game_sign_y[3]) {if(game_body[game_sign_y[0] + 1][game_sign_x[0] -1] != 2&&game_body[game_sign_y[2]][game_sign_x[2] +2] != 2&&game_body[game_sign_y[3] - 1][game_sign_x[3] + 1] != 2){num_csh_game();game_body[game_sign_y[0] + 1][game_sign_x[0] - 1] = 1;game_body[game_sign_y[1]][game_sign_x[1]] = 1;game_body[game_sign_y[2]][game_sign_x[2] + 2] = 1;game_body[game_sign_y[3] - 1][game_sign_x[3] + 1] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[0] == game_sign_y[1]&&game_sign_y[1] == game_sign_y[2]&&game_sign_x[2] == game_sign_x[3]){if(game_body[game_sign_y[0] + 1][game_sign_x[0] + 1] != 2&&game_body[game_sign_y[2] - 1][game_sign_x[2] - 1] != 2&&game_body[game_sign_y[3] - 2][game_sign_x[3]] != 2){num_csh_game();game_body[game_sign_y[0] + 1][game_sign_x[0] + 1] = 1;game_body[game_sign_y[1]][game_sign_x[1]] = 1;game_body[game_sign_y[2] - 1][game_sign_x[2] - 1] = 1;game_body[game_sign_y[3] - 2][game_sign_x[3]] = 1;infoTex.setText("游戏进行中!");repaint();}}}if(blockNumber == 6&&downSign == false)//变换两层砖块1的2种情况{if(game_sign_x[0] == game_sign_x[2]&&game_sign_x[0] >= 2){if(game_body[game_sign_y[0]][game_sign_x[0] - 2] != 2&&game_body[game_sign_y[2] - 1][game_sign_x[2] -1 ] != 2&&game_body[game_sign_y[3] - 1][game_sign_x[3] + 1] != 2){num_csh_game();game_body[game_sign_y[0]][game_sign_x[0] - 2] = 1;game_body[game_sign_y[1]][game_sign_x[1]] = 1;game_body[game_sign_y[2] - 1][game_sign_x[2] - 1] = 1;game_body[game_sign_y[3] - 1][game_sign_x[3] + 1] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[0] == game_sign_y[1]&&game_sign_y[3] <= 17){if(game_body[game_sign_y[0]][game_sign_x[0] + 2] != 2&&game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] != 2&&game_body[game_sign_y[3] + 1][game_sign_x[3] - 1] != 2){num_csh_game();game_body[game_sign_y[0]][game_sign_x[0] + 2] = 1;game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] = 1;game_body[game_sign_y[2]][game_sign_x[2]] = 1;game_body[game_sign_y[3] + 1][game_sign_x[3] - 1] = 1;infoTex.setText("游戏进行中!");repaint();}}}if(blockNumber == 7&&downSign == false)//变换两层砖块2的2种情况{if(game_sign_x[0] == game_sign_x[1]&&game_sign_x[0] <= 16){if(game_body[game_sign_y[0]][game_sign_x[0] + 2] != 2&&game_body[game_sign_y[1] - 1][game_sign_x[1] + 1] != 2&&game_body[game_sign_y[3] - 1][game_sign_x[3] - 1] != 2){num_csh_game();game_body[game_sign_y[0]][game_sign_x[0] + 2] = 1;game_body[game_sign_y[1] - 1][game_sign_x[1] + 1] = 1;game_body[game_sign_y[2]][game_sign_x[2]] = 1;game_body[game_sign_y[3] - 1][game_sign_x[3] - 1] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[0] == game_sign_y[1]&&game_sign_y[2] <= 17)if(game_body[game_sign_y[0] + 1][game_sign_x[0] -1] != 2&&game_body[game_sign_y[1]][game_sign_x[1] -2] != 2&&game_body[game_sign_y[2] + 1][game_sign_x[2] + 1] != 2){num_csh_game();game_body[game_sign_y[0] + 1][game_sign_x[0] - 1] = 1;game_body[game_sign_y[1]][game_sign_x[1] - 2] = 1;game_body[game_sign_y[2] + 1][game_sign_x[2] + 1] = 1;game_body[game_sign_y[3]][game_sign_x[3]] = 1;infoTex.setText("游戏进行中!");repaint();}}}}public void num_csh_game()//数组清零for(int i = 0;i < 19;i++){for(int j = 0;j < 10;j++){if(game_body[i][j] == 2){game_body[i][j] = 2;}else{game_body[i][j] = 0;}}}}public void num_csh_restart()//重新开始时数组清零 {for(int i = 0;i < 19;i++){for(int j = 0;j < 10;j++)game_body[i][j] = 0;}}}public void keyTyped(KeyEvent e){}public void keyPressed(KeyEvent e){if(e.getKeyCode() == KeyEvent.VK_DOWN&&startSign == 1)//处理下键{this.down();}if(e.getKeyCode() == KeyEvent.VK_LEFT&&startSign == 1)//处理左键{this.left();}if(e.getKeyCode() == KeyEvent.VK_RIGHT&&startSign== 1)//处理右键{this.right();}if(e.getKeyCode() == KeyEvent.VK_UP&&startSign== 1)//处理上键转换{this.change_body(blockNumber);}if(startSign == 0){infoTex.setText("游戏未开始或已结束!");}}public void keyReleased(KeyEvent e){}public void paint(Graphics g){g.setColor(Color.black);g.fill3DRect(0,0,300,450,true);for(int i = 0;i < 19;i++){for(int j = 0;j < 10;j++){if(game_body[i][j] == 1){g.setColor(Color.blue);g.fill3DRect(30*j,30*(i-4),30,30,true); }if(game_body[i][j] == 2){g.setColor(Color.magenta);g.fill3DRect(30*j,30*(i-4),30,30,true); }}}}public void left()//向左移动{int sign = 0;dingwei();for(int k = 0;k < 4;k++){if(game_sign_x[k] == 0||game_body[game_sign_y[k]][game_sign_x[k] - 1] == 2){sign = 1;}}if(sign == 0&&downSign == false){num_csh_game();for(int k = 0;k < 4;k++){game_body[game_sign_y[k]][game_sign_x[k] - 1] = 1; }infoTex.setText("向左移动!");repaint();}}public void right()//向右移动{int sign = 0;dingwei();for(int k = 0;k < 4;k++){if(game_sign_x[k] == 9||game_body[game_sign_y[k]][game_sign_x[k] + 1] == 2){sign = 1;}}if(sign == 0&&downSign == false){num_csh_game();for(int k = 0;k < 4;k++){game_body[game_sign_y[k]][game_sign_x[k] + 1] = 1; }infoTex.setText("向右移动!");repaint();}}public void down()//下落{int sign = 0;dingwei();for(int k = 0;k < 4;k++){if(game_sign_y[k] == 18||game_body[game_sign_y[k] + 1][game_sign_x[k]] == 2){sign = 1;downSign = true;changeColor();cancelDW();getScore();if(game_over() == false){rand_block();repaint();}}}if(sign == 0){num_csh_game();for(int k = 0;k < 4;k++){game_body[game_sign_y[k] + 1][game_sign_x[k]] = 1;}infoTex.setText("游戏进行中!");repaint();}}public boolean game_over()//判断游戏是否结束{int sign=0;for(int i = 0;i < 10;i++){if(game_body[4][i] == 2){sign = 1;}}if(sign == 1){infoTex.setText("游戏结束!");changeColor();repaint();startSign = 0;timer.suspend();return true;}elsereturn false;}public void getScore()//满行消除方法{for(int i = 0;i < 19;i++){int sign = 0;for(int j = 0;j < 10;j++){if(game_body[i][j] == 2){sign++;}}if(sign == 10){gameScore += 100;scoreTex.setText(gameScore+"");infoTex.setText("恭喜得分!");for(int j = i;j >= 1;j--){for(int k = 0;k < 10;k++){game_body[j][k] = game_body[j - 1][k];}}}}}public void changeColor()//给已经落下的块换色{downSign = false;for(int k = 0;k < 4;k++){game_body[game_sign_y[k]][game_sign_x[k]] = 2; }}public void dingwei()//确定其位置{int k = 0;cancelDW();for(int i = 0;i < 19;i++){for(int j = 0;j < 10;j++){if(game_body[i][j] == 1){game_sign_x[k] = j;game_sign_y[k] = i;k++;}}}}public void cancelDW()//将定位数组初始化{for(int k = 0;k < 4;k++){game_sign_x[k] = 0;game_sign_y[k] = 0;}}public void block1()//长条{game_body[0][4] = 1;game_body[1][4] = 1;game_body[2][4] = 1;game_body[3][4] = 1;}public void block2()//正方形{game_body[3][4] = 1;game_body[3][5] = 1;game_body[2][5] = 1;}public void block3()//3加1(下) {game_body[1][4] = 1;game_body[2][4] = 1;game_body[3][4] = 1;game_body[3][5] = 1;}public void block4()//3加1(中) {game_body[1][4] = 1;game_body[2][4] = 1;game_body[3][4] = 1;game_body[2][5] = 1;}public void block5()//3加1(上) {game_body[1][4] = 1;game_body[2][4] = 1;game_body[1][5] = 1;}public void block6()//转折1 {game_body[1][5] = 1;game_body[2][5] = 1;game_body[2][4] = 1;game_body[3][4] = 1;}public void block7()//转折2 {game_body[1][4] = 1;game_body[2][4] = 1;game_body[2][5] = 1;game_body[3][5] = 1;}}//定时线程class MyTimer extends Thread {ERSBlock myBlock;public MyTimer(ERSBlock myBlock){this.myBlock = myBlock;}public void run(){while(myBlock.startSign == 1){try{sleep((10-myBlock.speedMark + 1)*100);myBlock.down();}catch(InterruptedException e){}}}}。
基于Java的俄罗斯方块的设计和实现(含源文件)
姓 名
学号
专 业
指导教师
摘 要
俄罗斯方块作为一款风靡全球的多样化终端游戏,经久不衰。俄罗斯方块简单的基本游戏规则是旋转、移动,游戏自动随机输出7种形状的方块,经旋转后可形成28种形状,方块堆叠在一起,排列成完整的一行或多行消除得分,积分达到一定程度会自动提升级别。该游戏上手简单、老少皆宜、家喻户晓。
2 系统的
对系统的需求分析就是用户和开发人员在“系统必须做什么”这个问题上实现相互理解,达到共识,从而形成双方认可的软件产品的需求规格。这样有利于提高软件开发过程中的能见度,便于对软件开发过程的控制与管理,便于采用工程化的模式开发软件,从而达到提高软件的质量,为开发人员、维护人员、管理人员之间的交流、协作提供便捷。作为工作成果的原始依据,系统的需求分析可以向潜在用户传递软件功能、性能的需求,使其能够判断该软件是否符合自己的需求。
游戏形状需求:用数组作为存储方块28种状态的数据结构,即长条形、Z字形、反Z形、田字形、7字形、反7形、T字型一共7种形状的向4个方向的旋转变形,各个方块要能实现它的任意变形,可设为顺时针变形或逆时针变形,一般为逆时针变形。方块的可否翻转需要加以判断,以防止其翻转越界。
键盘处理事件需求:方块下落时,可通过键盘方向键(上键、下键、左键、右键)或字母键I、K、J、L对下落方块进行向上(旋转变形)、向下(加速下落)、向左移动、向右移动。
鼠标处理事件需求:通过点击菜单栏中相应的菜单项或控制面板内的按钮,可以实现游戏的开始、结束、暂停、继续、提高等级、降低等级,预显方块形状的显示,分数、等级的显示,以及游戏帮助、颜色变换等功能。
显示需求:当方块填满一行时可以消行,剩余未填满的行逐次向下移动并统计分数。当达到一定分数的时候,会增加相应的等级。当方块充满主界面的每一行,方块不能再下落时,提示“Game Over”的字样。
俄罗斯方块源代码
C语言俄罗斯方块源代码Vc6.0编译通过#include<windows.h>#include<stdio.h>#include<time.h>#include<stdlib.h>#include<malloc.h>#include<conio.h>#define MAP_WIDTH10#define MAP_HEIGHT20#define BLOCKM"■"#define BKBLOCK"□"#define OUTSTD GetStdHandle(STD_OUTPUT_HANDLE)typedef int(*PFUN)(void *pData);void ShowMapArray(int map[MAP_HEIGHT][MAP_WIDTH]);//生成方块int xyIsInarrBlock(int arrBlock[4][2], int x, int y) //有返回1 没有返回0 {int i;for (i = 0;i<4;i++)if (arrBlock[i][0] == x && arrBlock[i][1] == y)return 1;return 0;}void GetTransBlocks(int arrBlock[4][2])//坐标模式4*4方块{int nTmp, x, y;int nCount = 1;int i;int nMinx = 0, nMiny = 0;memset(arrBlock, 0, 8 * sizeof(int));while (nCount < 4){nTmp = rand() % nCount;x = arrBlock[nTmp][0];y = arrBlock[nTmp][1];nTmp = rand() % 4;switch (nTmp){case 0:x--;break;case 1:y--;break;case 2:x++;break;case 3:y++;break;}if (xyIsInarrBlock(arrBlock, x, y))continue;arrBlock[nCount][0] = x;arrBlock[nCount][1] = y;if (nMinx > x)nMinx = x;if (nMiny > y)nMiny = y;nCount++;}for (i = 0;i<4;i++){if (nMinx < 0)arrBlock[i][0] -= nMinx;if (nMiny < 0)arrBlock[i][1] -= nMiny;}}//旋转void Ratat(int arrBlock[4][2], int Direct) // driect 1 顺时针方向旋转,-1 逆时针方向旋转{int i;int nMinx, nMiny;int nTmp;for (i = 0;i<4;i++){nTmp = arrBlock[i][0];arrBlock[i][0] = arrBlock[i][1] * (-1)*Direct;arrBlock[i][1] = nTmp*Direct;if (i == 0){nMinx = arrBlock[i][0];nMiny = arrBlock[i][1];}else{if (nMinx > arrBlock[i][0])nMinx = arrBlock[i][0];if (nMiny > arrBlock[i][1])nMiny = arrBlock[i][1];}}for (i = 0;i<4;i++){if (nMinx < 0)arrBlock[i][0] -= nMinx;if (nMiny < 0)arrBlock[i][1] -= nMiny;}}void gotoxy(int x, int y){COORD pos = { x,y };SetConsoleCursorPosition(OUTSTD, pos);}void showxy(int x, int y, int bShow){COORD pos = { x * 2 + 2,y + 2 };SetConsoleCursorPosition(OUTSTD, pos);if (bShow)printf(BLOCKM);elseprintf(BKBLOCK);}void DisShowCursor(){CONSOLE_CURSOR_INFO cci;GetConsoleCursorInfo(OUTSTD, &cci);cci.bVisible = FALSE;SetConsoleCursorInfo(OUTSTD, &cci);}int CheckBlockPlace(int map[MAP_HEIGHT][MAP_WIDTH], int x, int y, int block[4][2], int bShow) //判断位置是否可用{int i;if (x < 0 || y < 0 || x >= MAP_WIDTH || y >= MAP_HEIGHT)return 0;for (i = 0;i<4;i++){if (map[y + block[i][1]][x + block[i][0]] == 1 && bShow)return 0;if (y + block[i][1] >= MAP_HEIGHT || x + block[i][0] >= MAP_WIDTH)return 0;}return 1;}int ShowBlock(int x, int y, int block[4][2], int bShow){int i;for (i = 0;i<4;i++)showxy(block[i][0] + x, block[i][1] + y, bShow);return 1;}void LoadMap(int map[MAP_HEIGHT][MAP_WIDTH]){int i, j;DisShowCursor();system("cls");printf("----------------俄罗斯方块v0.1--------------");printf("\n\n");for (i = 0;i<MAP_HEIGHT;i++){printf(" ");for (j = 0;j<MAP_WIDTH;j++){if (map[i][j])printf(BLOCKM);elseprintf(BKBLOCK);}printf("\n");}gotoxy(MAP_WIDTH * 2 + 6, 4);printf("按s开始\n");gotoxy(MAP_WIDTH * 2 + 6, 5);printf("Next:");gotoxy(MAP_WIDTH * 2 + 6, 12);printf("分数:");}int gameDown(int map[MAP_HEIGHT][MAP_WIDTH], int blockxy[4][2], int nSec, PFUN OnFun, void *pOnData){int i, j, k;int nSelect;int x = 3, y = 0;static int maxy = 20;int missrow = 0;int xsum = 0;while (1){nSelect = OnFun(pOnData);if (nSelect){switch (nSelect){case 75:{if (CheckBlockPlace(map, x - 1, y, blockxy, 1))x--;}break;case 72:{Ratat(blockxy, 1);if (!CheckBlockPlace(map, x, y, blockxy, 1)){Ratat(blockxy, -1);}}break;case 77:{if (CheckBlockPlace(map, x + 1, y, blockxy, 1))x++;}break;}}else{if (CheckBlockPlace(map, x, y, blockxy, 1)){ShowBlock(x, y, blockxy, 1);Sleep(nSec);if (CheckBlockPlace(map, x, y + 1, blockxy, 1)){ShowBlock(x, y, blockxy, 0);y++;}else{for (i = 0;i<4;i++){map[y + blockxy[i][1]][x + blockxy[i][0]] = 1;}if (y < maxy)maxy = y;break;}}elsereturn -1;}}for (i = maxy;i<MAP_HEIGHT;i++){xsum = 0;for (j = 0;j<MAP_WIDTH;j++){xsum += map[i][j];}if (xsum == MAP_WIDTH){for (k = i;k >= maxy;k--)for (j = 0;j<MAP_WIDTH;j++)map[k][j] = map[k - 1][j];missrow++;LoadMap(map);}}return missrow;}// help functionvoid ShowMapArray(int map[MAP_HEIGHT][MAP_WIDTH]){int i, j;for (i = 0;i<MAP_HEIGHT;i++){COORD pos = { MAP_WIDTH * 2,i };SetConsoleCursorPosition(OUTSTD, pos);for (j = 0;j<MAP_WIDTH;j++){printf("%d", map[i][j]);}}}int GetInfo(void *pData){while (kbhit()){char ch1 = getch();if (ch1 < 0){ch1 = getch();}return ch1;}while (kbhit())getch();return 0;}int main(){int map[MAP_HEIGHT][MAP_WIDTH] = { 0 };int blockarrnow[4][2] = { 0 }, blockarrnext[4][2] = { 0 };int ch, nRe, i, j, nScro = 0, nSpeed = 300;BOOL bRun = TRUE;LoadMap(map);srand((unsigned)time(NULL));while (bRun){if (kbhit()){ch = getch();}if (ch == 's' || ch == 'S'){GetTransBlocks(blockarrnow);while (bRun){GetTransBlocks(blockarrnext);ShowBlock(MAP_WIDTH + 2, 5, blockarrnext, 1);nRe = gameDown(map, blockarrnow, nSpeed, GetInfo, NULL);for (i = 0;i<4;i++){blockarrnow[i][0] = blockarrnext[i][0];blockarrnow[i][1] = blockarrnext[i][1];}for (i = 0;i <= 4;i++)for (j = 0;j <= 4;j++){gotoxy(MAP_WIDTH * 2 + 4 + j * 2, 7 + i);printf(" ");}if (nRe < 0){bRun = FALSE;break;}else{nScro += (nRe * 100);gotoxy(MAP_WIDTH * 2 + 11, 12);printf("%d", nScro);}}}}return 0;}Vs2015 编译运行配图。
俄罗斯方块代码
俄罗斯⽅块代码1 #include<iostream>2 #include<string>3 #include<ctime>4 #include<cstdlib>5 #include<windows.h>6 #include<conio.h>78using namespace std;910int block00[4][4] = { { 10,0,0,0 },{ 1,1,1,1 },{ 0,0,0,0 },{ 0,0,0,0 } };11int block01[4][4] = { { 11,0,1,0 },{ 0,0,1,0 },{ 0,0,1,0 },{ 0,0,1,0 } };12int block02[4][4] = { { 12,0,0,0 },{ 0,0,0,0 },{ 1,1,1,0 },{ 0,1,0,0 } };13int block03[4][4] = { { 13,0,0,0 },{ 0,1,0,0 },{ 1,1,0,0 },{ 0,1,0,0 } };14int block04[4][4] = { { 14,0,0,0 },{ 0,0,0,0 },{ 0,1,0,0 },{ 1,1,1,0 } };15int block05[4][4] = { { 15,0,0,0 },{ 0,1,0,0 },{ 0,1,1,0 },{ 0,1,0,0 } };16int block06[4][4] = { { 16,0,0,0 },{ 0,0,0,0 },{ 1,1,1,0 },{ 1,0,0,0 } };17int block07[4][4] = { { 17,0,0,0 },{ 1,1,0,0 },{ 0,1,0,0 },{ 0,1,0,0 } };18int block08[4][4] = { { 18,0,0,0 },{ 0,0,0,0 },{ 0,0,1,0 },{ 1,1,1,0 } };19int block09[4][4] = { { 19,0,0,0 },{ 0,1,0,0 },{ 0,1,0,0 },{ 0,1,1,0 } };20int block10[4][4] = { { 20,0,0,0 },{ 0,0,0,0 },{ 1,1,1,0 },{ 0,0,1,0 } };21int block11[4][4] = { { 21,0,0,0 },{ 0,1,0,0 },{ 0,1,0,0 },{ 1,1,0,0 } };22int block12[4][4] = { { 22,0,0,0 },{ 0,0,0,0 },{ 1,0,0,0 },{ 1,1,1,0 } };23int block13[4][4] = { { 23,0,0,0 },{ 0,1,1,0 },{ 0,1,0,0 },{ 0,1,0,0 } };24int block14[4][4] = { { 24,0,0,0 },{ 0,0,0,0 },{ 0,1,1,0 },{ 1,1,0,0 } };25int block15[4][4] = { { 25,0,0,0 },{ 1,0,0,0 },{ 1,1,0,0 },{ 0,1,0,0 } };26int block16[4][4] = { { 26,0,0,0 },{ 0,0,0,0 },{ 1,1,0,0 },{ 0,1,1,0 } };27int block17[4][4] = { { 27,0,0,0 },{ 0,0,1,0 },{ 0,1,1,0 },{ 0,1,0,0 } };28int block18[4][4] = { { 28,0,0,0 },{ 0,0,0,0 },{ 1,1,0,0 },{ 1,1,0,0 } };2930void initialWindow(HANDLE hOut);//初始化窗⼝31void initialPrint(HANDLE hOut);//初始化界⾯32void gotoXY(HANDLE hOut, int x, int y);//移动光标33void roundBlock(HANDLE hOut, int block[4][4]);//随机⽣成⽅块并打印到下⼀个⽅块位置34bool collisionDetection(int block[4][4], int map[21][12], int x, int y);//检测碰撞35void printBlock(HANDLE hOut, int block[4][4], int x, int y);//打印⽅块36void clearBlock(HANDLE hOut, int block[4][4], int x, int y);//消除⽅块37void myLeft(HANDLE hOut, int block[4][4], int map[21][12], int x, int &y);//左移38void myRight(HANDLE hOut, int block[4][4], int map[21][12], int x, int &y);//右移39void myUp(HANDLE hOut, int block[4][4], int map[21][12], int x, int &y);//顺时针旋转90度40int myDown(HANDLE hOut, int block[4][4], int map[21][12], int &x, int y);//加速下落41void myStop(HANDLE hOut, int block[4][4]);//游戏暂停42void gameOver(HANDLE hOut, int block[4][4], int map[21][12]);//游戏结束43void eliminateRow(HANDLE hOut, int map[21][12], int &val, int &fraction, int &checkpoint);//判断是否能消⾏并更新分值 44int main()45 {46int map[21][12];47int blockA[4][4];//候选区的⽅块48int blockB[4][4];//下落中的⽅块49int positionX, positionY;//⽅块左上⾓的坐标50bool check;//检查⽅块还能不能下落51char key;//⽤来存储按键52int val;//⽤来控制下落速度53int fraction;//⽤来存储得分54int checkpoint;//⽤来存储关卡55int times;56 HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);//获取标准输出设备句柄57 initialWindow(hOut);58 initial:59 gotoXY(hOut, 0, 0);60 initialPrint(hOut);61 check = true;62 val = 50;63 fraction = 0;64 checkpoint = 1;65 times = val;66for (int i = 0; i < 20; ++i)67 {68for (int j = 1; j < 11; ++j)69 {70 map[i][j] = 0;71 }72 }73for (int i = 0; i < 20; ++i)74 {75 map[i][0] = map[i][11] = 1;76 }77for (int i = 0; i < 12; ++i)78 {8182 srand((unsigned)time(NULL));83 roundBlock(hOut, blockA);84while (true)85 {86if (check)87 {88 eliminateRow(hOut, map, val, fraction, checkpoint);89 check = false;90 positionX = -3;91 positionY = 4;92if (collisionDetection(blockA, map, positionX, positionY))93 {94for (int i = 0; i < 4; ++i)95 {96for (int j = 0; j < 4; ++j)97 {98 blockB[i][j] = blockA[i][j];99 }100 }101 roundBlock(hOut, blockA);102 }103else104 {105 gameOver(hOut, blockA, map);106goto initial;107 }108 }109 printBlock(hOut, blockB, positionX, positionY);110if (_kbhit())111 {112 key = _getch();113switch (key)114 {115case72:116 myUp(hOut, blockB, map, positionX, positionY);117break;118case75:119 myLeft(hOut, blockB, map, positionX, positionY);120break;121case77:122 myRight(hOut, blockB, map, positionX, positionY);123break;124case80:125switch (myDown(hOut, blockB, map, positionX, positionY)) 126 {127case0:128 check = false;129break;130case1:131 check = true;132break;133case2:134 gameOver(hOut, blockB, map);135goto initial;136default:137break;138 }139break;140case32:141 myStop(hOut, blockA);142break;143case27:144 exit(0);145default:146break;147 }148 }149 Sleep(20);150if (0 == --times)151 {152switch (myDown(hOut, blockB, map, positionX, positionY)) 153 {154case0:155 check = false;156break;157case1:158 check = true;159break;160case2:161 gameOver(hOut, blockB, map);162goto initial;166 times = val;167 }168 }169 cin.get();170return0;171 }172173void initialWindow(HANDLE hOut)174 {175 SetConsoleTitle("俄罗斯⽅块");176 COORD size = { 80, 25 };177 SetConsoleScreenBufferSize(hOut, size);178 SMALL_RECT rc = { 0, 0, 79, 24 };179 SetConsoleWindowInfo(hOut, true, &rc);180 CONSOLE_CURSOR_INFO cursor_info = { 1, 0 };181 SetConsoleCursorInfo(hOut, &cursor_info);182 }183184void initialPrint(HANDLE hOut)185 {186 SetConsoleTextAttribute(hOut, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE); 187for (int i = 0; i < 20; ++i)188 {189 cout << "■■☆☆" << endl;190 }191 gotoXY(hOut, 26, 0);192 cout << "☆☆☆☆☆☆☆☆☆☆☆";193 gotoXY(hOut, 0, 20);194 cout << "■■■■■■■■■■■■☆☆☆☆☆☆☆☆☆☆☆☆☆";195 gotoXY(hOut, 26, 1);196 cout << "分数: ";197 gotoXY(hOut, 26, 2);198 cout << "关卡: ";199 gotoXY(hOut, 26, 4);200 cout << "下⼀⽅块:";201 gotoXY(hOut, 26, 9);202 cout << "操作⽅法:";203 gotoXY(hOut, 30, 11);204 cout << "↑:旋转↓:速降";205 gotoXY(hOut, 30, 12);206 cout << "→:右移←:左移";207 gotoXY(hOut, 30, 13);208 cout << "空格键:开始/暂停";209 gotoXY(hOut, 30, 14);210 cout << "Esc 键:退出";211 gotoXY(hOut, 26, 16);212 cout << "关于:";213 gotoXY(hOut, 30, 18);214 cout << "俄罗斯⽅块V1.0";215 gotoXY(hOut, 35, 19);216 cout << "作者:潘约尔";217 }218219void gotoXY(HANDLE hOut, int x, int y)220 {221 COORD pos;222 pos.X = x;223 pos.Y = y;224 SetConsoleCursorPosition(hOut, pos);225 }226227void roundBlock(HANDLE hOut, int block[4][4])228 {229 clearBlock(hOut, block, 5, 15);230switch (rand() % 19)231 {232case0:233for (int i = 0; i < 4; ++i)234 {235for (int j = 0; j < 4; ++j)236 {237 block[i][j] = block00[i][j];238 }239 }240break;241case1:242for (int i = 0; i < 4; ++i)243 {244for (int j = 0; j < 4; ++j)245 {246 block[i][j] = block01[i][j];250case2:251for (int i = 0; i < 4; ++i)252 {253for (int j = 0; j < 4; ++j)254 {255 block[i][j] = block02[i][j]; 256 }257 }258break;259case3:260for (int i = 0; i < 4; ++i)261 {262for (int j = 0; j < 4; ++j)263 {264 block[i][j] = block03[i][j]; 265 }266 }267break;268case4:269for (int i = 0; i < 4; ++i)270 {271for (int j = 0; j < 4; ++j)272 {273 block[i][j] = block04[i][j]; 274 }275 }276break;277case5:278for (int i = 0; i < 4; ++i)279 {280for (int j = 0; j < 4; ++j)281 {282 block[i][j] = block05[i][j]; 283 }284 }285break;286case6:287for (int i = 0; i < 4; ++i)288 {289for (int j = 0; j < 4; ++j)290 {291 block[i][j] = block06[i][j]; 292 }293 }294break;295case7:296for (int i = 0; i < 4; ++i)297 {298for (int j = 0; j < 4; ++j)299 {300 block[i][j] = block07[i][j]; 301 }302 }303break;304case8:305for (int i = 0; i < 4; ++i)306 {307for (int j = 0; j < 4; ++j)308 {309 block[i][j] = block08[i][j]; 310 }311 }312break;313case9:314for (int i = 0; i < 4; ++i)315 {316for (int j = 0; j < 4; ++j)317 {318 block[i][j] = block09[i][j]; 319 }320 }321break;322case10:323for (int i = 0; i < 4; ++i)324 {325for (int j = 0; j < 4; ++j)326 {327 block[i][j] = block10[i][j]; 328 }329 }330break;333 {334for (int j = 0; j < 4; ++j)335 {336 block[i][j] = block11[i][j];337 }338 }339break;340case12:341for (int i = 0; i < 4; ++i)342 {343for (int j = 0; j < 4; ++j)344 {345 block[i][j] = block12[i][j];346 }347 }348break;349case13:350for (int i = 0; i < 4; ++i)351 {352for (int j = 0; j < 4; ++j)353 {354 block[i][j] = block13[i][j];355 }356 }357break;358case14:359for (int i = 0; i < 4; ++i)360 {361for (int j = 0; j < 4; ++j)362 {363 block[i][j] = block14[i][j];364 }365 }366break;367case15:368for (int i = 0; i < 4; ++i)369 {370for (int j = 0; j < 4; ++j)371 {372 block[i][j] = block15[i][j];373 }374 }375break;376case16:377for (int i = 0; i < 4; ++i)378 {379for (int j = 0; j < 4; ++j)380 {381 block[i][j] = block16[i][j];382 }383 }384break;385case17:386for (int i = 0; i < 4; ++i)387 {388for (int j = 0; j < 4; ++j)389 {390 block[i][j] = block17[i][j];391 }392 }393break;394case18:395for (int i = 0; i < 4; ++i)396 {397for (int j = 0; j < 4; ++j)398 {399 block[i][j] = block18[i][j];400 }401 }402break;403default:404break;405 }406 printBlock(hOut, block, 5, 15);407 }408409bool collisionDetection(int block[4][4], int map[21][12], int x, int y) 410 {411for (int i = 0; i < 4; ++i)412 {413for (int j = 0; j < 4; ++j)414 {417return false;418 }419 }420 }421return true;422 }423424void printBlock(HANDLE hOut, int block[4][4], int x, int y)425 {426switch (block[0][0])427 {428case10:429case11:430 SetConsoleTextAttribute(hOut, FOREGROUND_GREEN);431break;432case12:433case13:434case14:435case15:436 SetConsoleTextAttribute(hOut, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY); 437break;438case16:439case17:440case18:441case19:442 SetConsoleTextAttribute(hOut, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY); 443break;444case20:445case21:446case22:447case23:448 SetConsoleTextAttribute(hOut, FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY);449break;450case24:451case25:452 SetConsoleTextAttribute(hOut, FOREGROUND_GREEN | FOREGROUND_INTENSITY);453break;454case26:455case27:456 SetConsoleTextAttribute(hOut, FOREGROUND_BLUE | FOREGROUND_INTENSITY);457break;458case28:459 SetConsoleTextAttribute(hOut, FOREGROUND_RED | FOREGROUND_INTENSITY);460break;461default:462break;463 }464for (int i = 0; i < 4; ++i)465 {466if (i + x >= 0)467 {468for (int j = 0; j < 4; ++j)469 {470if (block[i][j] == 1)471 {472473 gotoXY(hOut, 2 * (y + j), x + i);474 cout << "■";475 }476 }477 }478 }479 }480481void clearBlock(HANDLE hOut, int block[4][4], int x, int y)482 {483for (int i = 0; i < 4; ++i)484 {485if (i + x >= 0)486 {487for (int j = 0; j < 4; ++j)488 {489if (block[i][j] == 1)490 {491 gotoXY(hOut, 2 * (y + j), x + i);492 cout << "";493 }494 }495 }496 }497 }498501 SetConsoleTextAttribute(hOut, FOREGROUND_RED | FOREGROUND_INTENSITY);502 gotoXY(hOut, 9, 8);503 cout << "GAME OVER";504 gotoXY(hOut, 8, 9);505 cout << "空格键:重来";506 gotoXY(hOut, 8, 10);507 cout << "ESC键:退出";508char key;509while (true)510 {511 key = _getch();512if (key == 32)513 {514return;515 }516if (key == 27)517 {518 exit(0);519 }520 }521 }522523int myDown(HANDLE hOut, int block[4][4], int map[21][12], int &x, int y)524 {525if (collisionDetection(block, map, x + 1, y))526 {527 clearBlock(hOut, block, x, y);528 ++x;529return0;530 }531if (x < 0)532 {533return2;534 }535for (int i = 0; i < 4; ++i)536 {537for (int j = 0; j < 4; ++j)538 {539if (block[i][j] == 1)540 {541 map[x + i][y + j] = 1;542 SetConsoleTextAttribute(hOut, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY); 543 gotoXY(hOut, 2 * (y + j), x + i);544 cout << "■";545 }546 }547 }548return1;549 }550551void myLeft(HANDLE hOut, int block[4][4], int map[21][12], int x, int &y)552 {553if (collisionDetection(block, map, x, y - 1))554 {555 clearBlock(hOut, block, x, y);556 --y;557 }558 }559560void myRight(HANDLE hOut, int block[4][4], int map[21][12], int x, int &y)561 {562if (collisionDetection(block, map, x, y + 1))563 {564 clearBlock(hOut, block, x, y);565 ++y;566 }567 }568569void myUp(HANDLE hOut, int block[4][4], int map[21][12], int x, int &y)570 {571switch (block[0][0])572 {573case10:574if (collisionDetection(block01, map, x, y))575 {576 clearBlock(hOut, block, x, y);577for (int i = 0; i < 4; ++i)578 {579for (int j = 0; j < 4; ++j)580 {581 block[i][j] = block01[i][j];582 }586case11:587if (collisionDetection(block00, map, x, y))588 {589 clearBlock(hOut, block, x, y);590for (int i = 0; i < 4; ++i)591 {592for (int j = 0; j < 4; ++j)593 {594 block[i][j] = block00[i][j];595 }596 }597 }598else if (collisionDetection(block00, map, x, y - 1)) 599 {600 clearBlock(hOut, block, x, y);601for (int i = 0; i < 4; ++i)602 {603for (int j = 0; j < 4; ++j)604 {605 block[i][j] = block00[i][j];606 }607 }608 --y;609 }610else if (collisionDetection(block00, map, x, y + 1)) 611 {612 clearBlock(hOut, block, x, y);613for (int i = 0; i < 4; ++i)614 {615for (int j = 0; j < 4; ++j)616 {617 block[i][j] = block00[i][j];618 }619 }620 ++y;621 }622else if (collisionDetection(block00, map, x, y - 2)) 623 {624 clearBlock(hOut, block, x, y);625for (int i = 0; i < 4; ++i)626 {627for (int j = 0; j < 4; ++j)628 {629 block[i][j] = block00[i][j];630 }631 }632 y = y - 2;633 }634else if (collisionDetection(block00, map, x, y + 2)) 635 {636 clearBlock(hOut, block, x, y);637for (int i = 0; i < 4; ++i)638 {639for (int j = 0; j < 4; ++j)640 {641 block[i][j] = block00[i][j];642 }643 }644 y = y + 2;645 }646break;647case12:648if (collisionDetection(block03, map, x, y))649 {650 clearBlock(hOut, block, x, y);651for (int i = 0; i < 4; ++i)652 {653for (int j = 0; j < 4; ++j)654 {655 block[i][j] = block03[i][j];656 }657 }658 }659else if (collisionDetection(block03, map, x, y - 1)) 660 {661 clearBlock(hOut, block, x, y);662for (int i = 0; i < 4; ++i)663 {664for (int j = 0; j < 4; ++j)665 {666 block[i][j] = block03[i][j];671else if (collisionDetection(block03, map, x, y + 1)) 672 {673 clearBlock(hOut, block, x, y);674for (int i = 0; i < 4; ++i)675 {676for (int j = 0; j < 4; ++j)677 {678 block[i][j] = block03[i][j];679 }680 }681 ++y;682 }683break;684case13:685if (collisionDetection(block04, map, x, y))686 {687 clearBlock(hOut, block, x, y);688for (int i = 0; i < 4; ++i)689 {690for (int j = 0; j < 4; ++j)691 {692 block[i][j] = block04[i][j];693 }694 }695 }696else if (collisionDetection(block04, map, x, y - 1)) 697 {698 clearBlock(hOut, block, x, y);699for (int i = 0; i < 4; ++i)700 {701for (int j = 0; j < 4; ++j)702 {703 block[i][j] = block04[i][j];704 }705 }706 --y;707 }708else if (collisionDetection(block04, map, x, y + 1)) 709 {710 clearBlock(hOut, block, x, y);711for (int i = 0; i < 4; ++i)712 {713for (int j = 0; j < 4; ++j)714 {715 block[i][j] = block04[i][j];716 }717 }718 ++y;719 }720break;721case14:722if (collisionDetection(block05, map, x, y))723 {724 clearBlock(hOut, block, x, y);725for (int i = 0; i < 4; ++i)726 {727for (int j = 0; j < 4; ++j)728 {729 block[i][j] = block05[i][j];730 }731 }732 }733else if (collisionDetection(block05, map, x, y - 1)) 734 {735 clearBlock(hOut, block, x, y);736for (int i = 0; i < 4; ++i)737 {738for (int j = 0; j < 4; ++j)739 {740 block[i][j] = block05[i][j];741 }742 }743 --y;744 }745else if (collisionDetection(block05, map, x, y + 1)) 746 {747 clearBlock(hOut, block, x, y);748for (int i = 0; i < 4; ++i)749 {750for (int j = 0; j < 4; ++j)755 ++y;756 }757break;758case15:759if (collisionDetection(block02, map, x, y))760 {761 clearBlock(hOut, block, x, y);762for (int i = 0; i < 4; ++i)763 {764for (int j = 0; j < 4; ++j)765 {766 block[i][j] = block02[i][j];767 }768 }769 }770else if (collisionDetection(block02, map, x, y - 1)) 771 {772 clearBlock(hOut, block, x, y);773for (int i = 0; i < 4; ++i)774 {775for (int j = 0; j < 4; ++j)776 {777 block[i][j] = block02[i][j];778 }779 }780 --y;781 }782else if (collisionDetection(block02, map, x, y + 1)) 783 {784 clearBlock(hOut, block, x, y);785for (int i = 0; i < 4; ++i)786 {787for (int j = 0; j < 4; ++j)788 {789 block[i][j] = block02[i][j];790 }791 }792 ++y;793 }794break;795796case16:797if (collisionDetection(block07, map, x, y))798 {799 clearBlock(hOut, block, x, y);800for (int i = 0; i < 4; ++i)801 {802for (int j = 0; j < 4; ++j)803 {804 block[i][j] = block07[i][j];805 }806 }807 }808else if (collisionDetection(block07, map, x, y - 1)) 809 {810 clearBlock(hOut, block, x, y);811for (int i = 0; i < 4; ++i)812 {813for (int j = 0; j < 4; ++j)814 {815 block[i][j] = block07[i][j];816 }817 }818 --y;819 }820else if (collisionDetection(block07, map, x, y + 1)) 821 {822 clearBlock(hOut, block, x, y);823for (int i = 0; i < 4; ++i)824 {825for (int j = 0; j < 4; ++j)826 {827 block[i][j] = block07[i][j];828 }829 }830 ++y;831 }832break;833case17:834if (collisionDetection(block08, map, x, y))837for (int i = 0; i < 4; ++i)838 {839for (int j = 0; j < 4; ++j)840 {841 block[i][j] = block08[i][j];842 }843 }844 }845else if (collisionDetection(block08, map, x, y - 1)) 846 {847 clearBlock(hOut, block, x, y);848for (int i = 0; i < 4; ++i)849 {850for (int j = 0; j < 4; ++j)851 {852 block[i][j] = block08[i][j];853 }854 }855 --y;856 }857else if (collisionDetection(block08, map, x, y + 1)) 858 {859 clearBlock(hOut, block, x, y);860for (int i = 0; i < 4; ++i)861 {862for (int j = 0; j < 4; ++j)863 {864 block[i][j] = block08[i][j];865 }866 }867 ++y;868 }869break;870case18:871if (collisionDetection(block09, map, x, y))872 {873 clearBlock(hOut, block, x, y);874for (int i = 0; i < 4; ++i)875 {876for (int j = 0; j < 4; ++j)877 {878 block[i][j] = block09[i][j];879 }880 }881 }882else if (collisionDetection(block09, map, x, y - 1)) 883 {884 clearBlock(hOut, block, x, y);885for (int i = 0; i < 4; ++i)886 {887for (int j = 0; j < 4; ++j)888 {889 block[i][j] = block09[i][j];890 }891 }892 --y;893 }894else if (collisionDetection(block09, map, x, y + 1)) 895 {896 clearBlock(hOut, block, x, y);897for (int i = 0; i < 4; ++i)898 {899for (int j = 0; j < 4; ++j)900 {901 block[i][j] = block09[i][j];902 }903 }904 ++y;905 }906break;907case19:908if (collisionDetection(block06, map, x, y))909 {910 clearBlock(hOut, block, x, y);911for (int i = 0; i < 4; ++i)912 {913for (int j = 0; j < 4; ++j)914 {915 block[i][j] = block06[i][j];916 }921 clearBlock(hOut, block, x, y);922for (int i = 0; i < 4; ++i)923 {924for (int j = 0; j < 4; ++j)925 {926 block[i][j] = block06[i][j];927 }928 }929 --y;930 }931else if (collisionDetection(block06, map, x, y + 1)) 932 {933 clearBlock(hOut, block, x, y);934for (int i = 0; i < 4; ++i)935 {936for (int j = 0; j < 4; ++j)937 {938 block[i][j] = block06[i][j];939 }940 }941 ++y;942 }943break;944case20:945if (collisionDetection(block11, map, x, y))946 {947 clearBlock(hOut, block, x, y);948for (int i = 0; i < 4; ++i)949 {950for (int j = 0; j < 4; ++j)951 {952 block[i][j] = block11[i][j];953 }954 }955 }956else if (collisionDetection(block11, map, x, y - 1)) 957 {958 clearBlock(hOut, block, x, y);959for (int i = 0; i < 4; ++i)960 {961for (int j = 0; j < 4; ++j)962 {963 block[i][j] = block11[i][j];964 }965 }966 --y;967 }968else if (collisionDetection(block11, map, x, y + 1)) 969 {970 clearBlock(hOut, block, x, y);971for (int i = 0; i < 4; ++i)972 {973for (int j = 0; j < 4; ++j)974 {975 block[i][j] = block11[i][j];976 }977 }978 ++y;979 }980break;981case21:982if (collisionDetection(block12, map, x, y))983 {984 clearBlock(hOut, block, x, y);985for (int i = 0; i < 4; ++i)986 {987for (int j = 0; j < 4; ++j)988 {989 block[i][j] = block12[i][j];990 }991 }992 }993else if (collisionDetection(block12, map, x, y - 1)) 994 {995 clearBlock(hOut, block, x, y);996for (int i = 0; i < 4; ++i)997 {998for (int j = 0; j < 4; ++j)999 {1000 block[i][j] = block12[i][j];1005else if (collisionDetection(block12, map, x, y + 1)) 1006 {1007 clearBlock(hOut, block, x, y);1008for (int i = 0; i < 4; ++i)1009 {1010for (int j = 0; j < 4; ++j)1011 {1012 block[i][j] = block12[i][j];1013 }1014 }1015 ++y;1016 }1017break;1018case22:1019if (collisionDetection(block13, map, x, y))1020 {1021 clearBlock(hOut, block, x, y);1022for (int i = 0; i < 4; ++i)1023 {1024for (int j = 0; j < 4; ++j)1025 {1026 block[i][j] = block13[i][j];1027 }1028 }1029 }1030else if (collisionDetection(block13, map, x, y - 1)) 1031 {1032 clearBlock(hOut, block, x, y);1033for (int i = 0; i < 4; ++i)1034 {1035for (int j = 0; j < 4; ++j)1036 {1037 block[i][j] = block13[i][j];1038 }1039 }1040 --y;1041 }1042else if (collisionDetection(block13, map, x, y + 1)) 1043 {1044 clearBlock(hOut, block, x, y);1045for (int i = 0; i < 4; ++i)1046 {1047for (int j = 0; j < 4; ++j)1048 {1049 block[i][j] = block13[i][j];1050 }1051 }1052 ++y;1053 }1054break;1055case23:1056if (collisionDetection(block10, map, x, y))1057 {1058 clearBlock(hOut, block, x, y);1059for (int i = 0; i < 4; ++i)1060 {1061for (int j = 0; j < 4; ++j)1062 {1063 block[i][j] = block10[i][j];1064 }1065 }1066 }1067else if (collisionDetection(block10, map, x, y - 1)) 1068 {1069 clearBlock(hOut, block, x, y);1070for (int i = 0; i < 4; ++i)1071 {1072for (int j = 0; j < 4; ++j)1073 {1074 block[i][j] = block10[i][j];1075 }1076 }1077 --y;1078 }1079else if (collisionDetection(block10, map, x, y + 1)) 1080 {1081 clearBlock(hOut, block, x, y);1082for (int i = 0; i < 4; ++i)1083 {1084for (int j = 0; j < 4; ++j)1090 }1091break;1092case24:1093if (collisionDetection(block15, map, x, y))1094 {1095 clearBlock(hOut, block, x, y);1096for (int i = 0; i < 4; ++i)1097 {1098for (int j = 0; j < 4; ++j)1099 {1100 block[i][j] = block15[i][j];1101 }1102 }1103 }1104else if (collisionDetection(block15, map, x, y - 1)) 1105 {1106 clearBlock(hOut, block, x, y);1107for (int i = 0; i < 4; ++i)1108 {1109for (int j = 0; j < 4; ++j)1110 {1111 block[i][j] = block15[i][j];1112 }1113 }1114 --y;1115 }1116else if (collisionDetection(block15, map, x, y + 1)) 1117 {1118 clearBlock(hOut, block, x, y);1119for (int i = 0; i < 4; ++i)1120 {1121for (int j = 0; j < 4; ++j)1122 {1123 block[i][j] = block15[i][j];1124 }1125 }1126 ++y;1127 }1128break;1129case25:1130if (collisionDetection(block14, map, x, y))1131 {1132 clearBlock(hOut, block, x, y);1133for (int i = 0; i < 4; ++i)1134 {1135for (int j = 0; j < 4; ++j)1136 {1137 block[i][j] = block14[i][j];1138 }1139 }1140 }1141else if (collisionDetection(block14, map, x, y - 1)) 1142 {1143 clearBlock(hOut, block, x, y);1144for (int i = 0; i < 4; ++i)1145 {1146for (int j = 0; j < 4; ++j)1147 {1148 block[i][j] = block14[i][j];1149 }1150 }1151 --y;1152 }1153else if (collisionDetection(block14, map, x, y + 1)) 1154 {1155 clearBlock(hOut, block, x, y);1156for (int i = 0; i < 4; ++i)1157 {1158for (int j = 0; j < 4; ++j)1159 {1160 block[i][j] = block14[i][j];1161 }1162 }1163 ++y;1164 }1165break;1166case26:1167if (collisionDetection(block17, map, x, y))1168 {1174 block[i][j] = block17[i][j];1175 }1176 }1177 }1178else if (collisionDetection(block17, map, x, y - 1))1179 {1180 clearBlock(hOut, block, x, y);1181for (int i = 0; i < 4; ++i)1182 {1183for (int j = 0; j < 4; ++j)1184 {1185 block[i][j] = block17[i][j];1186 }1187 }1188 --y;1189 }1190else if (collisionDetection(block17, map, x, y + 1))1191 {1192 clearBlock(hOut, block, x, y);1193for (int i = 0; i < 4; ++i)1194 {1195for (int j = 0; j < 4; ++j)1196 {1197 block[i][j] = block17[i][j];1198 }1199 }1200 ++y;1201 }1202break;1203case27:1204if (collisionDetection(block16, map, x, y))1205 {1206 clearBlock(hOut, block, x, y);1207for (int i = 0; i < 4; ++i)1208 {1209for (int j = 0; j < 4; ++j)1210 {1211 block[i][j] = block16[i][j];1212 }1213 }1214 }1215else if (collisionDetection(block16, map, x, y - 1))1216 {1217 clearBlock(hOut, block, x, y);1218for (int i = 0; i < 4; ++i)1219 {1220for (int j = 0; j < 4; ++j)1221 {1222 block[i][j] = block16[i][j];1223 }1224 }1225 --y;1226 }1227else if (collisionDetection(block16, map, x, y + 1))1228 {1229 clearBlock(hOut, block, x, y);1230for (int i = 0; i < 4; ++i)1231 {1232for (int j = 0; j < 4; ++j)1233 {1234 block[i][j] = block16[i][j];1235 }1236 }1237 ++y;1238 }1239break;1240default:1241break;1242 }1243 }12441245void myStop(HANDLE hOut, int block[4][4])1246 {1247 clearBlock(hOut, block, 5, 15);1248 SetConsoleTextAttribute(hOut, FOREGROUND_RED | FOREGROUND_INTENSITY); 1249 gotoXY(hOut, 30, 7);1250 cout << "游戏暂停";1251char key;1252while (true)。
Java编写的俄罗斯方块(小游戏)
for (i=0; i<xblocks; i++)
{
for (j=0; j<yblocks; j++)
{
screendata[i][j]=0;
}
ห้องสมุดไป่ตู้ }
score=0;
emptyline=-1;
int objectdx;
short objecttype;
short objectcolor;
int objectrotation;
int objectrotationd=0;
short objectptr;
short checkptr;
final short itemcount=7;
fmsmall = g.getFontMetrics();
g.setFont(largefont);
fmlarge = g.getFontMetrics();
gameInit();
}
//初始化游戏
public void gameInit()
{
0,0, 1,0, 0,1, -1,1, // 被旋转180度
0,0, 0,-1, 1,0, 1,1, // 被旋转270度
0,0, 1,0, -1,0, 0,-1, // L形1,正常状态
0,0, 0,1, 0,-1, -1,0, // 被旋转90度
short screencount=40;
boolean showtitle=true;
int items[]={
0,0, -1,0, 0,-1, -1,-1, // 四方形, 正常状态
俄罗斯方块java代码
俄罗斯方块java代码俄罗斯方块是最经典的休闲益智游戏之一,现在很多人都不玩了,这里就来写一篇俄罗斯方块的Java代码。
首先,需要说明的是,Java代码中有两个类,一个是主类(Tetris.java),一个是方块类(Block.java)。
主类包含的功能是:显示游戏画面、游戏的主逻辑、处理键盘事件、以及控制游戏暂停、游戏结束等;方块类包含的功能是:初始化方块颜色、坐标、方向等,旋转方块。
那么我们来分析一下主类(Tetris.java)的代码。
首先是一些变量的定义:游戏区域的宽度和高度static final int Width = 10;static final int Height = 22;方块的颜色static Color blocksColor[] = {new Color(255, 255, 255), new Color(204, 102, 102),new Color(102, 204, 102), new Color(102, 102, 204),new Color(204, 204, 102), new Color(204, 102, 204),new Color(102, 204, 204), new Color(218, 170, 0) };游戏区域static int[][] wall = new int[Width][Height];当前方块static Block curBlock;下一个方块static Block nextBlock;游戏是否结束static boolean isOver;线程static MyThread t;接下来是一些初始化操作:初始化主窗体public Tetris() {initFrame();initUI();initGame();}初始化游戏界面private void initUI() {设置游戏面板和游戏区域pnlGame = new JPanel();pnlGame.setPreferredSize(new Dimension(blockSize * Width, blockSize * Height));pnlGame.setBorder(BorderFactory.createLineBorder(Color.gray));gameArea = new GameArea();pnlGame.add(gameArea);设置下一个方块显示面板和下一个方块区域pnlNextBlock = new JPanel();pnlNextBlock.setPreferredSize(new Dimension(blockSize * 4, blockSize * 4));pnlNextBlock.setBorder(BorderFactory.createTitledBorder("Next Block"));nextBlockArea = new BlockArea();pnlNextBlock.add(nextBlockArea);将游戏界面和下一个方块界面加入主窗体frmMain.getContentPane().add(pnlGame, BorderLayout.WEST);frmMain.getContentPane().add(pnlNextBlock, BorderLayout.EAST);显示窗体frmMain.pack();frmMain.setVisible(true);}初始化游戏private void initGame() {初始化积分、速度score = 0;speed = 1;初始化游戏区域for (int i = 0; i < Width; i++) {for (int j = 0; j < Height; j++) {wall[i][j] = 0;}}旋转T型方块,初始朝向为横向curBlock = new Block(1, 0);生成下一块方块nextBlock = new Block(0, 0);}我们可以看到,主类(Tetris.java)包含以下方法:1. initFrame()方法,用来初始化主窗体。
java程序积木源代码
旋转流程控制
加速下降流程控制
开始流程控制(Timer)
暂停流程控制
继续流程控制
结束流程控制
修改键盘事件
修改paintScore方法
Person I;
Person you;
I.love(you);
4 严格测试结果! TestCase
1) 如果"能够下落", 就下落一步
2) 否则就"着陆到墙里面"
3) 着落以后, "销毁充满的行", 并且记分
4) "检查游戏结束"了吗?
左右移动流程控制
分数计算
界面的绘制
键盘事件控制
就会固定在该处,而新的方块出现在区域上方开始落下。
(3)当区域中某一列横向格子全部由方块填满,则该行会消失
并成为玩家的得分。同时删除的行数越多,得分指数上升。
(4)当固定的方块堆到区域最上方而无法消除层数时,
则游戏结束。
(6)一般来说,游戏还会提示下一个要落下的方块,
熟练的玩家会计算到下一个方块,评估要如何进行。
由于游戏能不断进行下去对商业用游戏不太理想,
所以一般还会随着游戏的进行而加速提高难度。
(7)预先设置的随机发生器不断地输出单个方块到场地顶部
2 业务分析
找到有哪些业务对象根据图片的分析
tetris(俄罗斯方块)
|-- score 累计分数
|-- lines 销毁的行数
|-- 4 cell
3 数据模型, 一切业务对象转换为数字表示
场地按照行列划分为 20×10格子
格子有属性row, col, color
俄罗斯方块
1import java.awt.*;2import java.awt.event.*;3import javax.swing.*;4import javax.swing.event.*;56class Block implements Runnable// 方块类7{8 static final int type = 7, state = 4;910 static final int[][] patten = { // 16进制代表每种方块11 { 0x0f00, 0x4444, 0x0f00, 0x4444 },// 长条12 { 0x6600, 0x6600, 0x6600, 0x6600 },// 正方块13 { 0x04e0, 0x0464, 0x00e4, 0x04c4 },// 三角14 { 0x08e0, 0x0644, 0x00e2, 0x044c },// 弯折一下,1、3,1左15 { 0x02e0, 0x0446, 0x00e8, 0x0c44 },// 弯折一下,1、3,1右16 { 0x0462, 0x006c, 0x0462, 0x006c },// 弯折两下,1、2、1,1左上;1右下17 { 0x0264, 0x00c6, 0x0264, 0x00c6 } // 弯折两下,1、2、1,1右上;1左下18 };1920 private intblockType = -1; // 方块类型,7种,大小范围0-62122 private intblockState;// 方块状态,4种,大小范围0-32324 private int row, col; // 方块所在的行数,列数2526 private intoldRow, oldCol; // 记录方块变化前所在的行数,列数2728 private intoldType = -1, oldState; // 记录方块变化前的类型和状态2930 private intisfall = 1; // 标记若画,画成什么颜色的,3132 // 1表示可以下落,画为红色;0表示不可下落,画为蓝色3334 private boolean end = false;// 结束标记,为true时表示结束3536 LeftShowCanvaslsc;3738 public Block(LeftShowCanvaslsc)39 {40 this.lsc = lsc;41 row = 0;42 col = 3;43 oldRow = row;44 oldCol = col;45 }4647 public void reInit() // 一个方块无法下落后,重新初始化48 {49 blockType = -1;50 isfall = 1;51 }5253 public void reInitRowCol() // 初始化方块起始点54 {55 row = 0;56 col = 3;57 }5859 public void run() // 下落线程60 {61 lsc.requestFocusInWindow(); // 获得焦点62 while (!end)63 {64 intblocktype = (int) (Math.random() * 100) % 7;65 drawBlock(blocktype);66 do67 {68 try69 {70 Thread.sleep(500); // 控制下落速度71 } catch (InterruptedException e)72 {7374 }75 } while (fallMove()); // 下落76 for (int j = 0; j <lsc.maxcols; j++)77 // 判断是否结束78 if (lsc.unitState[3][j] == 2)79 end = true;80 }81 }8283 public synchronized void drawBlock(intblockType) // 画方块84 {85 if (this.blockType != blockType)86 blockState = (int) (Math.random() * 100) % 4; // 状态87 this.blockType = blockType; // 样式88 if (!isMove(3)) // 判断是否能画89 {90 this.blockType = oldType;91 this.blockState = oldState;92 return;93 }94 intcomIndex = 0x8000;95 if (this.oldType != -1)96 {97 for (int i = oldRow; i <oldRow + 4; i++)98 for (int j = oldCol; j <oldCol + 4; j++)99 {100 if ((patten[oldType][oldState] &comIndex) != 0101 &&lsc.unitState[i][j] == 1)102 //lsc.drawUnit(i, j, 0); // 先还原103 lsc.unitState[i][j]=0;//将状态记录改变,用于画下张图104 comIndex = comIndex>> 1;105 }106 }107 comIndex = 0x8000;108 for (int i = row; i < row + 4; i++)109 for (int j = col; j < col + 4; j++)110 {111 if ((patten[blockType][blockState] &comIndex) != 0)112 {113 if (isfall == 1)114 //lsc.drawUnit(i, j, 1); // 再画,画为RED115 lsc.unitState[i][j]=1; //将状态记录改变116 else if (isfall == 0)117 {118 //lsc.drawUnit(i, j, 2); // 无法下落,画为BLUE119 lsc.unitState[i][j]=2;//将状态记录改变,用于画下张图120 lsc.deleteFullLine(i); // 判断此行是否可以消121 }122 }123 comIndex = comIndex>> 1;124 }125126 Image image; //创建缓冲图片,利用双缓冲消除闪烁,画的下个状态图127 image=lsc.createImage(lsc.getWidth(),lsc.getHeight());128 Graphics g=image.getGraphics();129 lsc.paint(g);130 g.drawImage(image, 0, 0, lsc);131132 if (isfall == 0) // 无法下落,先判断是否能消行,再重新初始化133 {134 // lsc.deleteFullLine(row,col);135 reInit();136 reInitRowCol();137 }138 oldRow = row;139 oldCol = col;140 oldType = blockType;141 oldState = blockState;142 }143144 public void leftTurn() // 旋转,左转145 {146 if (this.blockType != -1)147 {148 blockState = (blockState + 1) % 4;149 if (isMove(3))150 drawBlock(blockType);151 else152 blockState = (blockState + 3) % 4;153 }154 }155156 public void leftMove() // 左移157 {158 if (this.blockType != -1 &&isMove(0))159 {160 col -= 1;161 drawBlock(blockType);162 }163 }164165 public void rightMove() // 右移166 {167 if (this.blockType != -1 &&isMove(1))168 {169 col += 1;170 drawBlock(blockType);171 }172 }173174 public booleanfallMove() // 下移175 {176 if (this.blockType != -1)177 {178 if (isMove(2))179 {180 row += 1;181 drawBlock(blockType);182 return true;183 } else184 {185 isfall = 0;186 drawBlock(blockType);187 return false;188 }189 }190 return false;191 }192193 public synchronized booleanisMove(int tag) // 左0 ,右1 ,下2 ,旋转3194 {195 intcomIndex = 0x8000;196 for (int i = row; i < row + 4; i++)197 for (int j = col; j < col + 4; j++)198 {199 if ((patten[blockType][blockState] &comIndex) != 0)200 {201 if (tag == 0 && (j == 0 || lsc.unitState[i][j - 1] == 2))// 是否能左移202 return false;203 else if (tag == 1 && // 是否能右移204 (j == lsc.maxcols - 1 || lsc.unitState[i][j + 1] == 2))205 return false;206 else if (tag == 2 && // 是否能下移207 (i == lsc.maxrows - 1 || lsc.unitState[i + 1][j] == 2))208 return false;209 else if (tag == 3 && // 是否能旋转210 (i >lsc.maxrows - 1 || j < 0211 || j >lsc.maxcols - 1 || lsc.unitState[i][j] == 2)) 212 return false;213 }214 comIndex = comIndex>> 1;215 }216 return true;217 }218}219220class LeftShowCanvas extends Canvas221{222 intmaxrows, maxcols; // 画布最大行数,列数223224 intunitSize; // 单元格的大小,小正方格225226 int[][] unitState; // 每个小方格的状态0、1、2表示227228 RightPanelrp;229230 int score;231232 public LeftShowCanvas(RightPanelrp)233 {234 this.rp = rp;235 score = Integer.valueOf(rp.jtf.getText());236 maxrows = 20;237 maxcols = 10;238 unitSize = 20;239 unitState = new int[maxrows][maxcols];240 initCanvas();241 }242243 public void initCanvas() // 初始化,画布方格244 {245 for (int i = 0; i <maxrows; i++)246 for (int j = 0; j <maxcols; j++)247 unitState[i][j] = 0;248 }249250 public void paint(Graphics g)251 {252 for (int i = 0; i <maxrows; i++)253 {254 for (int j = 0; j <maxcols; j++)255 drawUnit(i, j, unitState[i][j]); // 画方格256 if (i == 3)257 {258 g.setColor(Color.RED);259 g.drawLine(0, (i + 1) * (unitSize + 1) - 1, maxcols* (unitSize + 1) - 1, (i + 1) * (unitSize + 1) - 1);}}}public void drawUnit(int row, int col, int tag) // 画方格{unitState[row][col] = tag; // 记录状态Graphics g = getGraphics();switch (tag){case 0: // 初始黑色g.setColor(Color.BLACK);break;case 1: // 方格黑色g.setColor(Color.RED);break;case 2:g.setColor(Color.BLUE);break;}g.fillRect(col * (unitSize + 1), row * (unitSize + 1), unitSize,unitSize);}public void deleteFullLine(int row) // 判断此行是否可以消,同时可消就消行{for (int j = 0; j <maxcols; j++)if (unitState[row][j] != 2)return;for (int i = row; i > 3; i--)// 到此即为可消,将上面的移下消此行for (int j = 0; j <maxcols; j++)//drawUnit(i, j, unitState[i - 1][j]);unitState[i][j]=unitState[i-1][j];//将状态记录改变,用于画下张图score++;rp.jtf.setText(String.valueOf(score));}lassRightPanel extends JPanelJButton[] jbt = new JButton[7];JButton[] jbt2 = new JButton[4];JButton jbt3;JTextFieldjtf;JLabeljlb;MyJPanel jp1, jp2;public RightPanel(){jbt[0] = new JButton("长条");jbt[1] = new JButton("方块");jbt[2] = new JButton("三角");jbt[3] = new JButton("左三");jbt[4] = new JButton("右三");jbt[5] = new JButton("左二");jbt[6] = new JButton("右二");jbt2[0] = new JButton("左移");jbt2[1] = new JButton("右移");jbt2[2] = new JButton("下移");jbt2[3] = new JButton("翻转");jbt3 = new JButton("开始");jtf = new JTextField("0", 5);jlb = new JLabel("得分", JLabel.CENTER);jp1 = new MyJPanel(); // 左边的上面板jp2 = new MyJPanel(); // 左边的下面板jp1.setLayout(new GridLayout(4, 2, 20, 10)); // 网格布局jp2.setLayout(new GridLayout(4, 2, 20, 10)); // 网格布局this.setLayout(new BorderLayout()); // 边界布局for (int i = 0; i < 7; i++)jp1.add(jbt[i]);jp1.add(jbt3);for (int i = 0; i < 4; i++)jp2.add(jbt2[i]);jp2.add(jlb);jp2.add(jtf);this.add(jp1, "North");this.add(jp2, "Center");}/ 重写MyPanel类,使Panel的四周留空间lassMyJPanel extends JPanelpublic Insets getInsets(){return new Insets(10, 30, 30, 30);}lassMyActionListener implements ActionListenerRightPanelrp;Block bl;LeftShowCanvaslsc;public MyActionListener(RightPanelrp, Block bl, LeftShowCanvaslsc){this.rp = rp;this.bl = bl;this.lsc = lsc;}public void actionPerformed(ActionEvent e){if (e.getSource().equals(rp.jbt3)){// 这样子则按几次开始按钮就创建几个相同的线程,控制着相同的数据Thread th = new Thread(bl);th.start();}for (int i = 0; i <Block.type; i++)if (e.getSource().equals(rp.jbt[i])) // 看是画哪个{bl.reInitRowCol();bl.drawBlock(i);lsc.requestFocusInWindow(); // 获得焦点return;}if (e.getSource().equals(rp.jbt2[0]))bl.leftMove();else if (e.getSource().equals(rp.jbt2[1]))bl.rightMove();else if (e.getSource().equals(rp.jbt2[2]))bl.fallMove();else if (e.getSource().equals(rp.jbt2[3]))bl.leftTurn();lsc.requestFocusInWindow(); // 获得焦点}MyKeyAdapter extends KeyAdapterBlock bl;publicMyKeyAdapter(Block bl){this.bl = bl;}public void keyPressed(KeyEvent e){if (e.getKeyCode() == KeyEvent.VK_LEFT)bl.leftMove();else if (e.getKeyCode() == KeyEvent.VK_RIGHT) bl.rightMove();else if (e.getKeyCode() == KeyEvent.VK_DOWN) bl.fallMove();else if (e.getKeyCode() == KeyEvent.VK_SPACE) bl.leftTurn();}ic class FinalElsBlock extends JFrameBlock bl;LeftShowCanvaslsc;RightPanelrp;publicFinalElsBlock(){super("ELSBlock Study");setBounds(130, 130, 500, 450);setLayout(new GridLayout(1, 2, 50, 30));rp = new RightPanel();lsc = new LeftShowCanvas(rp);bl = new Block(lsc);rp.setSize(80, 400);for (int i = 0; i < 7; i++)// 为每个按钮添加消息监听rp.jbt[i].addActionListener(new MyActionListener(rp, bl, lsc)); rp.jbt3.addActionListener(new MyActionListener(rp, bl, lsc)); for (int i = 0; i < 4; i++)rp.jbt2[i].addActionListener(new MyActionListener(rp, bl, lsc)); lsc.addKeyListener(new MyKeyAdapter(bl));this.add(lsc);this.add(rp);this.addWindowListener(new WindowAdapter(){public void windowClosing(WindowEvent e){dispose();System.exit(0);}});setVisible(true);}public static void main(String[] args){newFinalElsBlock();}。
本科毕业论文-基于Java的游戏“俄罗斯方块”的设计与实现
西南交通大学本科毕业设计基于Java的游戏“俄罗斯方块”的设计与实现年级: 2002级学号: 20027102姓名: 赵凌专业: 电气工程及其自动化指导老师: 黄进2006年6月院系电气工程学院专业电气工程及其自动化年级2002级姓名赵凌题目基于Java的游戏“俄罗斯方块”的设计与实现指导教师评语指导教师 (签章)评阅人评语评阅人 (签章)成绩答辩委员会主任 (签章)年月日毕业设计(论文)任务书班级电气2002级2班学生姓名赵凌学号20027102 发题日期:2006年3月6日完成日期:6月20日题目基于Java的游戏“俄罗斯方块”的设计和实现1、本论文的目的、意义本次毕业设计的目的在于学习Java程序设计基本技术,学习用JBuilder开发Java程序的相关技术,熟悉游戏“俄罗斯方块”的需求,熟悉项目开发的完整过程。
通过本次毕业设计,学生应该学会怎样进行一个项目的需求分析、概要设计、详细设计等软件开发过程,熟练地掌握Java程序设计的基本技术和方法,熟练地掌握JBuilder环境的使用方法,培养起初步的项目分析能力和程序设计能力,把理论与实践相结合,为今后工作打下坚实的基础。
2、学生应完成的任务学生应完成项目的需求分析、概要设计、详细设计等前期工作,在此基础上,采用基于Java的程序设计技术完成游戏“俄罗斯方块”的基本功能,包括:游戏控制功能(游戏的开始、暂停和恢复),游戏设置功能(设置方块下移速度),游戏排行榜功能(存储成绩)等,最终完成毕业设计说明书的攥写。
3、设计各部分内容及时间分配:(共 12 周)第一部分收集相关资料及熟悉开发语言和环境(2周)第二部分系统主界面模块(1周)第三部分游戏控制模块(3周)第四部分游戏设置模块(1周)第五部分游戏排行榜模块(1周)第六部分毕业设计说明书的撰写、初评、修改及定稿(3周)评阅及答辩(1周)备注指导教师:黄进2006年3月6日审批人:年月日摘要近年来,Java作为一种新的编程语言,以其简单性、可移植性和平台无关性等优点,得到了广泛地应用,特别是Java与WWW的完美结合,使其成为网络编程和嵌入式编程领域的首选编程语言。
俄罗斯方块游戏原代码
#include<stdio.h>#include<stdlib.h>#include<dos.h>#include<graphics.h> /*系统提供的头文件*/#define TIMER 0x1c /*定义时钟中断的中断号*/#define VK_LEFT 0x4b00/*左移键*/#define VK_RIGHT 0x4d00/*右移键*/#define VK_DOWN 0x5000 /*加速键*/#define VK_UP 0x4800 /*变形键*/#define VK_SPACE 0x3920 /*变形键*/#define VK_END 0x4f00 /*暂停键*/#define VK_ESC 0x011b#define VK_ENTER 0x1c0d#define BSIZE 16 /*方块的边长是16个象素*/#define MAX_SHAPE 19 /*总共有19种各形态的方块*/#define BOARD_WIDTH 10 /*游戏面板的宽度,以方块的宽度为单位*/#define BOARD_HEIGHT 20/*游戏面板的高度,以方块的宽度为单位*/#define BGCOLOR BLACK /*背景色*/#define FORECOLOR WHITE /*前景色*/#define FALSE 0#define TRUE 1#define EMPTY 0#define FILLED 1#define BOARD_LEFT_X 10 /*游戏面板左上角的横坐标*/#define BOARD_LEFT_Y 5 /*游戏面板左上角的纵坐标*//*定义全局变量*/extern int Gameboard[BOARD_WIDTH+2][BOARD_HEIGHT+2];extern int nCurrent_block_index ; /*当前下落的方块的索引号*/ extern int nNext_block_index ; /*下一个方块的索引号*/extern int nSpeed, nScore; /*速度和得分*/extern int nSpeedUpScore; /*第一次要加速需达到的分数*/extern int bAccel, bOver;extern int nOriginX, nOriginY;/*某一形状的原点的绝对坐标*/ extern unsigned int TimerCounter; /* 计时变量,每秒钟增加18 */struct block{int arrXY[8];int nColor;int nNext;}; /*保存某一形状信息的结构体*/typedef struct block BLOCK;extern BLOCK arrayBlock[19];void interrupt newtimer(void);void SetTimer(void interrupt(*IntProc)(void));void KillTimer();void InitializeGraph();void InitializeGameboard() ;void DrawSquare(int x, int y);void DrawBlock(int BlockIndex, int sx, int sy,int color); int IsConflict(int BlockIndex, int x, int y);void HandleLeft(int BlockIndex,int *x, int *y);void HandleRight(int BlockIndex,int *x, int *y);void HandleUp(int *BlockIndex,int *x, int *y);int HandleDown(int BlockIndex,int *x, int *y);int IsLineFull(int y);void KillLine(int y);int KillLines(int y);int IsGameOver();int GameOver();void StartGame();void ProcessInGame();void game();void win();void help();void design();void show_win();void main(){win();menu();}void help(){clrscr();help();textcolor(WHITE);gotoxy(20,4);cprintf("\xDB\xDB\xDB\xDB\xB2 HELP ABOUT THE Game \xB2\xDB\xDB\xDB\xDB"); gotoxy(4,6);cprintf(" [ 1 ] - Metamorphose : Press the left key square moves left "); gotoxy(30,8);cprintf("Press the left key square move to the right");gotoxy(30,10);cprintf("Press down key square accelerate whereabouts");gotoxy(4,12);cprintf(" [ 2 ] - Speed up : Press the button oblong rotating ");gotoxy(4,14);cprintf(" [ 3 ] - Game Start : Press Enter to button to start the game"); gotoxy(4,16);cprintf(" [ 4 ] - Game Over : Press the ESC key to quit the game");gotoxy(30,18);cprintf("YOU WANT TO BE HELPFUL");gotoxy(6,23);printf("Press any key to go to the MAIN MENU ........");getche();}menu(){int x;do{{clrscr();design();textcolor(WHITE);cprintf("\xDB\xDB\xDB\xDB\xB2 Tetris Game \xB2\xDB\xDB\xDB\xDB");gotoxy(3,4);cprintf("--------------------------------------------------------------------------");gotoxy(35,5);cprintf("MAIN MENU");gotoxy(26,8);cprintf(" 1 - New Game ");gotoxy(26,9);cprintf(" 2 - Rank ");gotoxy(26,10);cprintf(" 3 - HELP ");gotoxy(26,11);cprintf(" 4 - The Game Explain ");gotoxy(26,12);cprintf(" 5 - EXIT ");x=toupper(getch());switch(x){case '1':game();break;case '2':cprintf("At present there is no ranking");break;case '3':help();break;case '4':cprintf("This game by LuWenJun,ChenLong,QiWei jointly compiled,Deficiencies still please forgive me");break;case '5':exit(0);break;default:clrscr();design();gotoxy(17,12);printf("\a\xDB\xB2 WRONG ENTRY : PRESS ANY KEY AND TRY AGAIN"); getche();}}}while(x!='5');return x;}void win(){int i,graphdriver,graphmode,size,page;char s1[30],s2[30];graphdriver=DETECT;initgraph(&graphdriver,&graphmode,"c:\\turboc2");cleardevice();setbkcolor(BLUE);setviewport(40,40,600,440,1);setfillstyle(1,2);setcolor(YELLOW);rectangle(0,0,560,400);floodfill(50,50,14);rectangle(20,20,540,380);setfillstyle(1,13);floodfill(21,300,14);setcolor(BLACK);settextstyle(1,0,6);outtextxy(100,60,"Welcom You");setviewport(100,200,540,380,0);setcolor(14);setfillstyle(1,12);rectangle(20,20,420,120);settextstyle(2,0,9);floodfill(21,100,14);sprintf(s1,"Let's our play Tetris Game!");setcolor(YELLOW);outtextxy(60,40,s1);sprintf(s2,"Press any key to play....");setcolor(1);settextstyle(4,0,3);outtextxy(110,80,s2);getch();closegraph();}void design(){int i;clrscr();textcolor(14);gotoxy(2,2);cprintf("\xC9");gotoxy(3,2);for(i=1;i<=74;i++)cprintf("\xCD");gotoxy(77,2);cprintf("\xBB");gotoxy(2,3);cprintf("\xBA");gotoxy(2,4);cprintf("\xBA");gotoxy(2,5);cprintf("\xBA");gotoxy(2,6);cprintf("\xBA");gotoxy(2,7);cprintf("\xBA");gotoxy(2,8);cprintf("\xB A");gotoxy(2,9);cprintf("\xBA");gotoxy(2,10);cprintf("\xBA");gotoxy(2,11);cprintf("\ xBA");gotoxy(2,12);cprintf("\xBA");gotoxy(2,13);cprintf("\xBA");gotoxy(2,14);cprintf("\xBA");gotoxy(2,15);cprintf(" \xBA");gotoxy(2,16);cprintf("\xBA");gotoxy(2,17);cprintf("\xBA");gotoxy(2,18);cprintf("\xBA");gotoxy(2,22);cprintf(" \xCC");gotoxy(2,19);cprintf("\xBA");gotoxy(2,20);cprintf("\xBA");gotoxy(2,21);cprintf(" \xBA");gotoxy(2,24);cprintf("\xC8");gotoxy(2,23);cprintf("\xBA");gotoxy(3,24);for(i=1;i<=74;i++)cprintf("\xCD");gotoxy(77,18);cprintf("\xBA");gotoxy(77,19);cprintf("\xBA");gotoxy(77,20);cprint f("\xBA");gotoxy(77,21);cprintf("\xBA");gotoxy(77,24);cprintf("\xBC");gotoxy(77,23);cprintf("\xBA");gotoxy(3,22);for(i=1;i<=74;i++)cprintf("\xCD");gotoxy(77,22);cprintf("\xB9");gotoxy(77,3);cprintf("\xBA");gotoxy(77,4);cprintf("\xBA");gotoxy(77,5);cprintf("\xBA");gotoxy(77,6);cprintf("\xBA");gotoxy(77,7);cprintf("\xBA");gotoxy(77,8);cprintf(" \xBA");gotoxy(77,9);cprintf("\xBA");gotoxy(77,10);cprintf("\xBA");gotoxy(77,11);cprintf ("\xBA");gotoxy(77,12);cprintf("\xBA");gotoxy(77,13);cprintf("\xBA");gotoxy(77,14);cprintf("\xBA");gotoxy(77,15);cprint f("\xBA");gotoxy(77,16);cprintf("\xBA");gotoxy(77,17);cprintf("\xBA");textcolor(RED);}void show_win(void){union REGS in, out;in.x.ax = 0x1;int86(0x33, &in, &out);}/*********************************************************** 函数原型:void InitializeGraph() * * 传入参数:无 ** 返回值:无 ** 函数功能:初始化进入图形模式***********************************************************/void InitializeGraph(){int gdriver = VGA, gmode=VGAHI, errorcode;/* 初始化图形模式*/initgraph(&gdriver, &gmode, "c:\\turboc2");/* 读取初始化结果 */errorcode = graphresult();if (errorcode != grOk) /* 错误发生 */{printf("Graphics error: %s\n", grapherrormsg(errorcode));printf("Press any key to halt:");getch();exit(1); /* 返回错误码 */}}/*********************************************************** 函数原型:void InitializeGameboard() ** 传入参数:无** 返回值:无** 函数功能:初始化游戏面板以及下一形状提示框、计分框和难度框 ***********************************************************/void InitializeGameboard(){/* 绘制游戏面板(即游戏区域)*/setfillstyle(SOLID_FILL,BGCOLOR);bar(BSIZE*BOARD_LEFT_X,BSIZE*BOARD_LEFT_Y,BSIZE*(BOARD_LEFT_X+BOARD_WIDTH),BSIZE*(BOARD_LEFT_Y+BOARD_HEIGHT));setcolor(WHITE);rectangle(BSIZE*BOARD_LEFT_X,BSIZE*BOARD_LEFT_Y,BSIZE*(BOARD_LEFT_X+BOARD_WIDTH),BSIZE*(BOARD_LEFT_Y+BOARD_HEIGHT));/*绘制下一形状提示框*/setcolor(BLUE);settextjustify(CENTER_TEXT, BOTTOM_TEXT);outtextxy(BSIZE*(25+4), BSIZE*(5+1), "next");setfillstyle(SOLID_FILL, BGCOLOR);bar(BSIZE*(24.5+2), BSIZE*6, BSIZE*(24.5+2+5), BSIZE*(6+5));setcolor(YELLOW);rectangle(BSIZE*(24.5+2), BSIZE*6, BSIZE*(24.5+2+5), BSIZE*(6+5));/*绘制速度框*/setcolor(BLUE);settextjustify(CENTER_TEXT, BOTTOM_TEXT);outtextxy(BSIZE*(25+4), BSIZE*(12+1), "level");setfillstyle(SOLID_FILL, BGCOLOR);bar(BSIZE*25,BSIZE*13, BSIZE*(25+8), BSIZE*(13+1));setcolor(YELLOW);rectangle(BSIZE*25,BSIZE*13, BSIZE*(25+8), BSIZE*(13+1)); setcolor(RED);settextjustify(CENTER_TEXT, BOTTOM_TEXT);outtextxy(BSIZE*(25+4), BSIZE*(13+1), "0");/*绘制计分框*/setcolor(BLUE);settextjustify(CENTER_TEXT, BOTTOM_TEXT);outtextxy(BSIZE*(25+4), BSIZE*(19+1), "score");setfillstyle(SOLID_FILL, BGCOLOR);bar(BSIZE*25,BSIZE*20, BSIZE*(25+8), BSIZE*(20+1));setcolor(YELLOW);rectangle(BSIZE*25,BSIZE*20, BSIZE*(25+8), BSIZE*(20+1)); setcolor(RED);settextjustify(CENTER_TEXT, BOTTOM_TEXT);outtextxy(BSIZE*(25+4), BSIZE*(20+1), "0");}int Gameboard[BOARD_WIDTH+2][BOARD_HEIGHT+2];int nCurrent_block_index;/* 当前下落的方块的索引号*/int nNext_block_index ; /*下一个方块的索引号*/int nSpeed, nScore; /*速度和得分*/int nSpeedUpScore = 1000; /*第一次要加速需达到的分数*/int bAccel, bOver;int nOriginX=5, nOriginY=1;/*某一形状的原点的绝对坐标*/ BLOCK arrayBlock[19]={/*x1,y1,x2,y2,x3,y3,x4,y4, color, next*/{ 0,-2, 0,-1, 0, 0, 1, 0, CYAN, 1}, /* */{-1, 0, 0, 0, 1,-1, 1, 0, CYAN, 2}, /* # */{ 0,-2, 1,-2, 1,-1, 1, 0, CYAN, 3}, /* # */{-1,-1,-1, 0, 0,-1, 1,-1, CYAN, 0}, /* ## */{ 0,-2, 0,-1, 0, 0, 1,-2,MAGENTA, 5}, /* */{-1,-1,-1, 0, 0, 0, 1, 0,MAGENTA, 6}, /* ## */{ 0, 0, 1,-2, 1,-1, 1, 0,MAGENTA, 7}, /* # */{-1,-1, 0,-1, 1,-1, 1, 0,MAGENTA, 4}, /* # */{-1, 0, 0,-1, 0, 0, 1, 0,YELLOW, 9}, /* */{-1,-1, 0,-2, 0,-1, 0, 0,YELLOW, 10}, /* */{-1,-1, 0,-1, 0, 0, 1,-1,YELLOW, 11}, /* # */{ 0,-2, 0,-1, 0, 0, 1,-1,YELLOW, 8}, /* ### */{-1, 0, 0,-1, 0, 0, 1,-1, BROWN, 13}, /* ## */{ 0,-2, 0,-1, 1,-1, 1, 0, BROWN, 12}, /* ## */{-1,-1, 0,-1, 0, 0, 1, 0, WHITE, 15}, /* ## */{ 0,-1, 0, 0, 1,-2, 1,-1, WHITE, 14}, /* ## */{ 0,-3, 0,-2, 0,-1, 0, 0, RED, 17},/* # */{-1, 0, 0, 0, 1, 0, 2, 0, RED, 16},/* # *//* # *//* # */{ 0,-1, 0, 0, 1,-1, 1, 0, BLUE, 18},/* ## *//* ## */};/*********************************************************** 函数原型:void StartGame () ** 传入参数:无** 返回值:无 ** 函数功能:游戏开始时调用的函数,其中绘制界面需调用函数 ** InitializeGameboard(), 接下来需初始化游戏面板的 ** 各个方块和一些全局变量的初值 ***********************************************************/void StartGame(){int i,j;/*设置游戏面板中每个方块的初始值*/for(j=0;j<=BOARD_HEIGHT;j++)for(i=0;i<BOARD_WIDTH+2;i++){if(i==0 || i==BOARD_WIDTH+1)Gameboard[i][j] = FILLED;elseGameboard[i][j] = EMPTY;}for(i=0;i<BOARD_WIDTH+2;i++)Gameboard[i][BOARD_HEIGHT+1] = FILLED;InitializeGameboard();/*设置游戏变量的初值*/nNext_block_index = -1; /*游戏初始,没有下一个形状的索引号*/nSpeed = 0;nScore = 0;}/*********************************************************** 函数原型:void ProcessInGame() ** 传入参数:无** 返回值:无** 函数功能:核心函数,主要用于处理在游戏中的各种事件(如按下各种按键) ***********************************************************/void ProcessInGame(){int key;bioskey(0);randomize();while(1){if(nNext_block_index==-1){nCurrent_block_index = rand()%19;nNext_block_index = rand()%19;/*绘制下一个提示形状*/DrawBlock(nNext_block_index,19,6,arrayBlock[nNext_block_index].nColor );}else{nCurrent_block_index = nNext_block_index;DrawBlock(nNext_block_index, 19,6,BGCOLOR ); /* 消除原来的提示形状 */nNext_block_index = rand()%19;DrawBlock(nNext_block_index,19,6,arrayBlock[nNext_block_index].nColor ); /*绘制下一个提示形状 */}nOriginX=5, nOriginY=1;TimerCounter = 0;DrawBlock(nCurrent_block_index, nOriginX,nOriginY, arrayBlock[nCurrent_block_index].nColor );/*在面板内绘制当前形状*/while(1){if (bioskey(1))key=bioskey(0);else key=0;bAccel = FALSE;switch(key){case VK_LEFT: /* 左移 */HandleLeft(nCurrent_block_index,&nOriginX,&nOriginY );break;case VK_RIGHT: /* 右移 */HandleRight(nCurrent_block_index,&nOriginX,&nOriginY );break;case VK_UP: /* 旋转 */case VK_SPACE:HandleUp(&nCurrent_block_index, &nOriginX,&nOriginY);break;case VK_DOWN: /* 下落加速键 */bAccel=TRUE;break;case VK_END: /* 暂停*/bioskey(0);break;case VK_ESC: /* 退出游戏 */bOver=TRUE;return;}if(bAccel || TimerCounter>(20-nSpeed*2))if(HandleDown(nCurrent_block_index,&nOriginX,&nOriginY))break;if(bOver)return;}}}/*********************************************************** 函数原型:void main() ** 传入参数:无 ** 返回值:无 ** 函数功能:入口函数,包含俄罗斯方块程序的主流程 ***********************************************************/void game(){InitializeGraph();SetTimer(newtimer); /*设置新的时钟中断*/while(1){StartGame();ProcessInGame();if(GameOver())break;bOver = FALSE;}KillTimer();closegraph();}unsigned int TimerCounter=0; /* 计时变量,每秒钟增加18 *//*********************************************************** 函数原型:void interrupt (*oldtimer)(void) ** 传入参数:无** 返回值:无** 函数功能:指向原来时钟中断处理过程入口的中断处理函数指针(句柄) ***********************************************************/void interrupt (*oldtimer)(void);/*********************************************************** 函数原型:void interrupt newtimer(void) ** 传入参数:无 ** 返回值:无 ** 函数功能:新的时钟中断处理函数 ***********************************************************/void interrupt newtimer(void){(*oldtimer)();TimerCounter++;}/*********************************************************** 函数原型:void SetTimer(void interrupt(*)(void)) ** 传入参数:无 ** 返回值:无 ** 函数功能:设置新的时钟中断处理函数 ***********************************************************/void SetTimer(void interrupt(*IntProc)(void)){oldtimer=getvect(TIMER);disable();setvect(TIMER,IntProc);enable();}/*********************************************************** 函数原型:void KillTimer() ** 传入参数:无 ** 返回值:无 ** 函数功能:恢复原先的时钟中断处理函数 ***********************************************************/void KillTimer(){disable();setvect(TIMER,oldtimer);enable();}/*********************************************************** 函数原型:void DrawSquare(int x, int y) ** 传入参数:游戏面板中的横坐标x,纵坐标y ** 返回值:无 ** 函数功能:在坐标(x, y)处绘制方块 ***********************************************************/void DrawSquare(int x, int y){if(y<1)return;bar(BSIZE*(x+9)+1,BSIZE*(y+4)+1,BSIZE*(x+10)-1,BSIZE*(y+5)-1);}/*********************************************************** 函数原型:void DrawBlock(int BlockIndex, int sx, int sy,int color) ** 传入参数:形状的索引BlockIndex,绝对横坐标x,绝对纵坐标y,颜色color ** 返回值:无** 函数功能:在坐标(sx, sy)处绘制颜色为color的形状***********************************************************/void DrawBlock(int BlockIndex, int sx, int sy,int color){int i,c;setfillstyle(SOLID_FILL, color);for(i=0;i<7;i+=2)DrawSquare(arrayBlock[BlockIndex].arrXY[i]+sx,arrayBlock[BlockIndex].arrXY[i+1]+sy);}/*********************************************************** 函数原型:int IsConflict(int BlockIndex, int x, int y) ** 传入参数:形状的索引BlockIndex,绝对横坐标x,绝对纵坐标y ** 返回值:无冲突返回0,有冲突返回1 ** 函数功能:判断形状是否能存在于坐标(x, y)处 * **********************************************************/int IsConflict(int BlockIndex, int x, int y){int i;for (i=0;i<=7;i++,i++){if (arrayBlock[BlockIndex].arrXY[i]+x<1 || arrayBlock[BlockIndex].arrXY[i]+x>10)return TRUE;if (arrayBlock[BlockIndex].arrXY[i+1]+y<1)continue;if(Gameboard[arrayBlock[BlockIndex].arrXY[i]+x][arrayBlock[BlockIndex].arrXY[i+1]+ y])return TRUE;}return FALSE;}/*********************************************************** 函数原型:int HandleLeft(int BlockIndex,int *x, int *y) * * 传入参数:形状的索引BlockIndex,绝对横坐标的指针*x,绝对纵坐标的 ** 指针*y ** 返回值:无** 函数功能:按下左方向键时的处理函数***********************************************************/void HandleLeft(int BlockIndex,int *x, int *y) /*按下左方向键时的处理函数*/{if(!IsConflict(BlockIndex,*x-1,*y)){DrawBlock(BlockIndex,*x,*y,BGCOLOR); /*擦除原先的形状*/(*x)--;DrawBlock(BlockIndex, *x, *y, arrayBlock[BlockIndex].nColor); /*绘制当前形状*/}}/*********************************************************** 函数原型:int HandleRight(int BlockIndex,int *x, int *y) ** 传入参数:形状的索引BlockIndex,绝对横坐标的指针*x,绝对纵坐标的 ** 指针*y ** 返回值:无** 函数功能:按下右方向键时的处理函数***********************************************************/void HandleRight(int BlockIndex,int *x, int *y)/*按下右方向键时的处理函数*/{if(!IsConflict(BlockIndex,*x+1,*y)){DrawBlock(BlockIndex,*x,*y,BGCOLOR); /*擦除原先的形状*/(*x)++;DrawBlock(BlockIndex, *x, *y, arrayBlock[BlockIndex].nColor); /*绘制当前形状*/}}/*********************************************************** 函数原型:int HandleUp(int BlockIndex,int *x, int *y) ** 传入参数:形状的索引BlockIndex,绝对横坐标的指针*x,绝对纵坐标的 ** 指针*y ** 返回值:无** 函数功能:按下上方向键(旋转键)时的处理函数***********************************************************/void HandleUp(int *BlockIndex,int *x, int *y) /*按下旋转键时的处理函数*/{int NextBlockIndex, i;static int arrayOffset[5]={0,-1,1,-2,2};NextBlockIndex = arrayBlock[*BlockIndex].nNext;for(i=0;i<5;i++)if(!IsConflict(NextBlockIndex, *x+arrayOffset[i],*y)){DrawBlock(*BlockIndex, *x, *y, BGCOLOR); /*擦除原先的形状*/*BlockIndex = arrayBlock[*BlockIndex].nNext;(*x) += arrayOffset[i];DrawBlock(*BlockIndex, *x, *y, arrayBlock[*BlockIndex].nColor); /*绘制当前形状*/}}/*********************************************************** 函数原型:int HandleDown(int BlockIndex,int *x, int *y) * * 传入参数:形状的索引BlockIndex,绝对横坐标的指针*x,绝对纵坐标的 ** 指针*y ** 返回值:仍在自由下落返回0,无法下落了返回1 ** 函数功能:按下向下方向键或自由下落时的处理函数***********************************************************/int HandleDown(int BlockIndex,int *x, int *y)/*按下下方向键或自由下落时的处理函数*/{char ScoreBuffer[10]={0},SpeedBuffer[10]={0};int i;int NumLinesKilled=0;/*if(TimerCounter>(20-nSpeed*2))*/{TimerCounter = 0; /*重置时钟中断*/if(!IsConflict(BlockIndex,*x,*y+1)) /*仍在下落*/{DrawBlock(BlockIndex,*x,*y,BGCOLOR); /*擦除原先的形状*/(*y)++;DrawBlock(BlockIndex, *x, *y, arrayBlock[BlockIndex].nColor); /*绘制当前形状*/return FALSE;/*仍在下落返回FALSE*/}else /*无法再下落了*/{DrawBlock(BlockIndex,*x,*y,FORECOLOR);for (i=0;i<=7;i++,i++){if ((*y)+arrayBlock[BlockIndex].arrXY[i+1]<1)continue;Gameboard[(*x)+arrayBlock[BlockIndex].arrXY[i]][(*y)+arrayBlock[BlockIndex].arrX Y[i+1]]=1;}NumLinesKilled = KillLines(*y);if(NumLinesKilled>0){switch(NumLinesKilled){case 1:nScore+=100;case 2:nScore+=300;case 3:nScore+=500;case 4:nScore+=800;}/*重绘计分框*/setfillstyle(SOLID_FILL,BLACK);bar(BSIZE*25,BSIZE*20, BSIZE*(25+8), BSIZE*(20+1));setcolor(YELLOW);rectangle(BSIZE*25,BSIZE*20, BSIZE*(25+8), BSIZE*(20+1));itoa(nScore,ScoreBuffer, 10);setcolor(RED);settextjustify(CENTER_TEXT, BOTTOM_TEXT);outtextxy(BSIZE*(25+4), BSIZE*(20+1), ScoreBuffer);if(nScore > nSpeedUpScore){nSpeed++;nSpeedUpScore+= nSpeed*1000;/*重绘速度框*/setfillstyle(SOLID_FILL,BLACK);bar(BSIZE*25,BSIZE*13, BSIZE*(25+8), BSIZE*(13+1));setcolor(YELLOW);rectangle(BSIZE*25,BSIZE*13, BSIZE*(25+8), BSIZE*(13+1)); itoa(nSpeed,SpeedBuffer,10);setcolor(YELLOW);settextjustify(CENTER_TEXT, BOTTOM_TEXT);outtextxy(BSIZE*(25+4), BSIZE*(13+1), SpeedBuffer);}if(IsGameOver())bOver = TRUE;return TRUE; /*下落到底返回TRUE*/}}}/*********************************************************** 函数原型:int IsLineFull(int y) ** 传入参数:纵坐标y ** 返回值:填满返回1,否则返回0 ** 函数功能:判断第y行是否已被填满***********************************************************/int IsLineFull(int y){int i;for(i=1;i<=10;i++)if(!Gameboard[i][y])return FALSE;return TRUE;}/*********************************************************** void KillLine(int y) ** 传入参数:纵坐标y ** 返回值:无 ** 函数功能:消去第y行***********************************************************/void KillLine(int y){int i,j;for(j=y;j>=2;j--)for(i=1;i<=10;i++){if(Gameboard[i][j]==Gameboard[i][j-1])continue;if(Gameboard[i][j-1]==FILLED){Gameboard[i][j]=FILLED;setfillstyle(SOLID_FILL,FORECOLOR);}else /*Gameboard[i][j-1]==EMPTY*/Gameboard[i][j] = EMPTY;setfillstyle(SOLID_FILL,BGCOLOR);}DrawSquare(i,j);}}/*********************************************************** 函数原型:int KillLines(int y) ** 传入参数:纵坐标y ** 返回值:消去的行数 ** 函数功能:消去第y行以及与第y行连续的上面被填满的行 ***********************************************************/int KillLines(int y){int i, j, LinesKilled=0;for(i=0;i<4;i++){while(IsLineFull(y)){KillLine(y);LinesKilled++;i++;}y--;if(y<1)break;}return LinesKilled;}/*********************************************************** 函数原型:int IsGameOver() ** 传入参数:无 ** 返回值:游戏结束返回1,否则返回0 ** 函数功能:判断游戏是否结束***********************************************************/int IsGameOver(){int i;for(i=1;i<=10;i++)if(Gameboard[i][1])return TRUE;return FALSE;}/*********************************************************** 函数原型:int GameOver() ** 传入参数:无** 返回值:退出游戏返回1,否则返回0 ** 函数功能:在界面上输出游戏结束信息,并根据用户按键选择决定是否退出游戏***********************************************************/int GameOver(){int key;settextjustify(CENTER_TEXT,TOP_TEXT);/* 输出游戏结束信息 */setcolor(RED);outtextxy(BSIZE*15,BSIZE*12,"Game Over");setcolor(GREEN);outtextxy(BSIZE*15,BSIZE*14,"Enter : New Game");outtextxy(BSIZE*15,BSIZE*15,"Esc : Exit");for(;;){while(!bioskey(1));key=bioskey(0);if (key==VK_ENTER)return FALSE; /* 按下回车键,重新开始游戏 */if (key==VK_ESC)return TRUE; /* 按下ESC键,退出游戏 */}}。
俄罗斯方块java代码
g2.drawString("NEXT", 196, 45);
g2.drawString("SCORE",193, 110);
g2.drawString(""+SCORE,205, 130);
g2.drawString("Xiong", 205, 160);
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Els extends JFrame implements KeyListener,Runnable
{
public Els()
{
g2.drawLine(0, m, 180, m);
}
//将值不非0的格子涂黑
for(int i=1;i<13;i++)
{
for(int j=0;j<20;j++)
{
g2.setColor(Color.DARK_GRAY);
if (o[i][j]!=0) g2.fillRect(15*i-13, 15*j+2, 13, 13);
}
for(int m=52;m<=92;m+=10)
{
g2.drawLine(192, m, 232, m);
}
//绘制大框格
for(int m=0;m<=180;m+=15)
{
俄罗斯方块java代码
import javax.swing.*;import javax.swing.Timer;import java.awt.*;import java.awt.event.*;import java.util.*;/**Title: 俄罗斯方块*Description: 俄罗斯方块*Copyright: 俄罗斯方块*Company:俄罗斯方块**@author Zhu Yong*@version 1.0*/public class SquaresGame{public static void main(String[]args){ new SquaresFrame().play();}}class SquaresFrame extends JFrame { public final static int WIDTH= 500;public final static int HEIGHT= 600;/***游戏区*/private BoxPanel boxPanel;/***暂停标记*/private boolean isPause= true;/***默认构造函数*/public SquaresFrame(){/***记分面板boxPanel =new BoxPanel(infoPanel);JMenuBar bar = new JMenuBar();JMenu menu = new JMenu("菜单");JMenuItem begin = new JMenuItem("新游戏");final JMenuItem pause = new JMenuItem("暂停"); JMenuItem stop = new JMenuItem("结束");setJMenuBar(bar);bar.add(menu);menu.add(begin);menu.add(pause);menu.add(stop);stop.addActionListener(newActionListener(){ public voidactionPerformed(ActionEvent e){System.exit(0);}});pause.addActionListener(newActionListener(){ public voidactionPerformed(ActionEvent e){if (isPause){boxPanel.supend(false);isPause = ! isPause;pause.setText("恢复");}else {boxPanel.supend(true);isPause = ! isPause;pause.setText("暂停");}}});boxPanel.newGame(); }});boxPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.cre ateEtchedBorder(),"Box"));infoPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.cr eateEtchedBorder(),"Info"));add(boxPanel,BorderLayout.CENTER);add(infoPanel,BorderLayout.EAST);setTitle("Squares Game");setSize(WIDTH,HEIGHT);//不可改变框架大小setResizable(false);//定位显示到屏幕中间setLocation(((int)Toolkit.getDefaultToolkit().getScreenSize().getWidt h()-WIDTH)/2,((int)Toolkit.getDefaultToolkit().getScreenSize().getHeight()-HEIGHT) /2);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setVisible(true);}public void play() {boxPanel.newGame();}}/****@author Zhu Yong*游戏区面板*/class BoxPanel extends JPanel {/***定义行*/public final static int ROWS= 20;/**public final static int COLS= 10;public final static Color DISPLAY= new Color(128,128,255);/***没有方块时显示的颜色*/public final static Color HIDE= new Color(238,238,238);/***记分面板上显示的下一个方块的颜色*/public final static Color NEXTDISPLAY= Color.ORANGE;/***是否显示网络*/public final static boolean PAINTGRID= false;/***用4个按钮表示一个方块*/private JButton[][]squares= new JButton[ROWS][COLS];/***定义对前位置是否有方块.用颜色区别.*/private int[][]stateTable= new int[ROWS][COLS];private InfoPanel scorePanel;private ABox currentBox;private ABox nextBox;/***各方块颜色数组.其中0号颜色为无方块时颜色.共7种方块 .最后一个消行时颜色 */private static Color[]boxColor= new Color[]{newColor(238,238,238),new Color(128,128,255),new Color(189,73,23), new Color(154,105,22),new Color(101,124,52),newColor(49,100,128),new Color(84,57,119),new Color(111,54,102), new Color(126,50,57),Color.RED};/***定时器,负责方块自动下移*/private Timer timer;/**private int level;/***初时化时的延时*/private final static int INITDELAY= 940;/***每一级别延时减少的步进值*/private final static int INC= 90;public BoxPanel(InfoPanel panel){setLayout(new GridLayout(ROWS,COLS,1,1));//可能获取焦点,才能接受键盘事件setFocusable(true);//setCursor(new Cursor(1));/***初时化,生成JButton,设置颜色.JButton数组按照先第一行再第二行的顺序添加.下标为[行][列]和[x][y]正好相反.*/for(int i=0;i<ROWS;i++)for(int j=0;j<COLS;j++) {JButton square= new JButton("");square.setEnabled(false);square.setBorderPainted(PAINTGRID);squares[i][j] = square;stateTable[i][j] = 0;add(square);}scorePanel = panel;timer =new Timer(INITDELAY,new autoDownHandler());//注册键盘事件addKeyListener(new KeyAdapter(){ publicvoid keyPressed(KeyEvent e) {int key = e.getKeyCode();//System.out.println(bt.getX()+":"+bt.getY());if (key == KeyEvent.VK_DOWN) dropdown();else if (key == KeyEvent.VK_UP) rotate();else if (key == KeyEvent.VK_RIGHT) right();else if (key == KeyEvent.VK_LEFT) left();/***重新所有方块. 即重新改变所有JButton背景色*/private void showBox(){for(int i=0;i<ROWS;i++)for(int j=0;j<COLS;j++)squares[i][j].setBackground(boxColor[stateTable[i][j]]);}/***只重新显示当前方块*/private void showCurrentBox(){point[] location = currentBox.getLocation();for(int i=0;i<4;i++){int row = location[i].getY();int col =location[i].getX();squares[row][col].setBackground(boxColor[stateTable[row][col]]);}}/***消行记分*/private void clearBox(){int clearLines=0;for(int i=ROWS-1;i>=0;i--)for(int j=0;j<COLS;j++) {if (stateTable[i][j]==0) break;if (j==(COLS-1)) {removeLine(i);clearLines++;i++; }}if (clearLines>0) {scorePanel.winScore(clearLines);upgrade();}}/***消行,重置属性表.下移*@param line*/for(int j=0;j<COLS;j++){stateTable[line][j] = 8;//System.out.println(squares[line][j].getBackground());squares[line][j].setBackground(Color.RED);//System.out.println(squares[line][j].getBackground());//validate();}showBox();for (int i=line;i>=0;i--)for(int j=0;j<COLS;j++)if (i!=0)stateTable[i][j] = stateTable[i-1][j];elsestateTable[i][j] = 0;showBox();timer.start();}/***检查把方块移动到(x,y)时是否合法 .*@param x*@param y*@return*/public boolean checkAction(int x,int y) {//先移除当前方块,再判断.当前方块和下一位置的方块有共用的位置.removeCurrentBox();boolean ret = true;point[] list = currentBox.getShape().getList();int xx = 0;int yy = 0;for (int i=0;i<4;i++) {if (i!=0) {xx = list[i].getX()+x;yy = list[i].getY()+y; }else {xx = x; yy = y; }//System.out.println("check"+i+"->"+xx+":"+yy);if ( xx>=COLS|| xx<0) {ret = false;break; } if ( yy>=ROWS|| yy<0 ) {ret = false; break;}//System.out.println("after break check"+i+"->"+xx+":"+yy); if (stateTable[yy][xx]!=0){ret = false; break;}}addCurrentBox();return ret;}*左移*/public void left(){if(checkAction(currentBox.getHead().getX()-1,currentBox.getHead().getY())) {removeCurrentBox();showCurrentBox();currentBox.setHead(currentBox.getHead().getX()-1,currentBox.getHead() .getY());addCurrentBox();//showBox();showCurrentBox();}}/***右移*/public void right(){if(checkAction(currentBox.getHead().getX()+1,currentBox.getHead().getY())) {removeCurrentBox();showCurrentBox();currentBox.setHead(currentBox.getHead().getX()+1,currentBox.getHead() .getY());addCurrentBox();//showBox();showCurrentBox();}}/***下移*@return*/public boolean down(){int choose=0;if(checkAction(currentBox.getHead().getX(),currentBox.getHead().getY()+1)) {removeCurrentBox();showCurrentBox();etY()+1);addCurrentBox();showCurrentBox();//showBox();return true;}else {clearBox();currentBox = nextBox.setDefault();nextBox = BoxFactory.getBox().setDefault();scorePanel.setNext(nextBox);//showBox();//检查是否游戏结束if (checkGameOver()){supend(false);choose = JOptionPane.showConfirmDialog(this, "游戏结束\n你的积分为"+scorePanel.getScore()+"\n要开始新游戏吗?","GameOver",JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE);if (choose == JOptionPane.YES_OPTION) newGame();}addCurrentBox();showCurrentBox();//showBox();return false;}}/***丢下.*/public void dropdown() {while (down()) {};}/***判断是否结束*@returnpoint[] location = currentBox.getLocation();for(int i=0;i<4;i++){int row = location[i].getY();int col = location[i].getX();if (stateTable[row][col]!=0) return true;}return false;}/***变形*/public void rotate(){if (checkRotate()){removeCurrentBox();showCurrentBox();currentBox.rotate();addCurrentBox();showCurrentBox();//showBox();}}/***检查变形是否合法*@return*/private boolean checkRotate(){removeCurrentBox();int oldheadx =currentBox.getHead().getX(); intoldheady =currentBox.getHead().getY();//System.out.println("oldhead:"+oldheadx+","+oldheady);boolean ret = true;point[] shape = currentBox.getNextShape().getList();int x=0,y=0,newheadx = 0,newheady=0; for(inti=0;i<4;i++) {if (i!=0){x = newheadx + shape[i].getX();y = newheady + shape[i].getY();}else {newheadx = oldheadx + shape[i].getX();newheady = oldheady + shape[i].getY();x = newheadx;y = newheady;//System.out.println("newhead:"+newheadx+":"+newheady);if ( x>=COLS|| x<0) {ret = false;break; } if ( y>=ROWS|| y<0 ){ret = false;break;}//System.out.println("after break checkrotate "+i+"->"+x+":"+y); if (stateTable[y][x]!=0) {ret = false;break;}}addCurrentBox();return ret;}/***移除当前方块.设置颜色为无色.主要用于移动,变形时.清除当前位置方块.显示下一位置方块.*/private void removeCurrentBox(){//System.out.println("removeCurrentBox:"+Thread.currentThread().getNa me());for(int i=0;i<4;i++){int x=currentBox.getLocation()[i].getX();int y=currentBox.getLocation()[i].getY();stateTable[y][x] = 0;}}/***添加当前方块到属性表.*/private void addCurrentBox(){for(int i=0;i<4;i++){int x=currentBox.getLocation()[i].getX();int y=currentBox.getLocation()[i].getY();stateTable[y][x] = currentBox.getId();}}/***暂停游戏*false时暂停*@param resume*/public void supend(boolean resume){if (! resume) {timer.stop();else {timer.start();setFocusable(true);this.requestFocus();}}/***设置游戏级别.即改变定时器延时.*@param level*/public void setLevel(int level) {this.level= level;scorePanel.setLevel(level);timer.setDelay(INITDELAY-INC*level);}/***自动下移监听器*@author Administrator**/private class autoDownHandler implements ActionListener { public void actionPerformed(ActionEvent e){ down();}}/***根据积分自动设置级别*/public void upgrade(){int score =scorePanel.getScore();if (score > 3000 &&level<2) setLevel(2); else if (score > 6000 &&level<3) setLevel(3); else if(score > 10000 &&level<4) setLevel(4); else if(score > 15000 &&level<5) setLevel(5); else if(score > 21000 &&level<6) setLevel(6); else if(score > 28000 &&level<7) setLevel(7); else if(score > 35000 &&level<8) setLevel(8); else if(score > 43000 &&level<9) setLevel(9); else if(score > 51000 &&level<10) setLevel(10);}/***重置,开始新游戏.for(int i=0;i<ROWS;i++)for(int j=0;j<COLS;j++)stateTable[i][j] = 0;showBox();setLevel(1);scorePanel.clean();currentBox = BoxFactory.getBox();nextBox = BoxFactory.getBox();scorePanel.setNext(nextBox);setFocusable(true);requestFocus();addCurrentBox();showBox();timer.start();}}/***记分面板*@author Administrator**/class InfoPanel extends JPanel{private JLabel scoreLabel;private JLabel lineLabel;private JLabel levelLabel;private JPanel nextPanel;/***下一个方块*/private JButton[][]nextBox;public InfoPanel(){setLayout(new BorderLayout());Box vbox = Box.createVerticalBox();add(vbox,BorderLayout.CENTER);vbox.add(Box.createRigidArea(new Dimension(12,50)));Box vbox1 = Box.createVerticalBox();vbox.add(vbox1);scoreLabel =new JLabel("0");lineLabel =new JLabel("0");levelLabel =new JLabel("0");nextPanel.setLayout(new GridLayout(4,4,1,1));for(int i=0;i<4;i++)for(int j=0;j<4;j++){JButton bt = new JButton("");bt.setEnabled(false);bt.setBorderPainted(BoxPanel.PAINTGRID);nextPanel.add(bt);nextBox[j][i] = bt;}vbox1.add(new JLabel("Next :"));vbox1.add(nextPanel);vbox1.add(Box.createVerticalStrut(90));vbox1.add(new JLabel("得分:"));vbox1.add(Box.createVerticalStrut(10));vbox1.add(scoreLabel);vbox1.add(Box.createVerticalStrut(10));vbox1.add(new JLabel("行数:"));vbox1.add(Box.createVerticalStrut(10));vbox1.add(lineLabel);vbox1.add(Box.createVerticalStrut(10));vbox1.add(new JLabel(" Level :"));vbox1.add(Box.createVerticalStrut(10));vbox1.add(levelLabel);vbox1.add(Box.createVerticalStrut(80));}/***记分.显示在面板上*@param lines*/public void winScore(int lines){int score = 0;lineLabel.setText(""+(Integer.parseInt(lineLabel.getText())+lines));if (lines==1) score = 100;else if (lines ==2) score = 300;else if (lines ==3) score = 500;else if (lines ==4) score = 1000;scoreLabel.setText(""+(Integer.parseInt(scoreLabel.getText())+score)) ;}/***@param next*/public void setNext(ABox next) {for(int i=0;i<4;i++)for(int j=0;j<4;j++)nextBox[i][j].setBackground(BoxPanel.HIDE);int headx = 2; int heady = 0;//设置方块位置if (next.getId() == 1) {headx = 2;heady=0;}else if (next.getId() == 2) {headx = 1;heady = 1;}else if (next.getId() == 3) {headx = 2;heady = 1;}else if (next.getId() == 4) {headx = 1;heady = 1;}else if (next.getId() == 5) {headx = 2;heady = 1;}else if (next.getId() == 6) {headx = 1;heady = 1;}else if (next.getId() == 7) {headx = 1;heady = 1;}point[] shape = next.getShape(0).getList();nextBox[headx][heady].setBackground(BoxPanel.NEXTDISPLAY);nextBox[headx+shape[1].getX()][heady+shape[1].getY()].setBackground(B oxPanel.NEXTDISPLAY);nextBox[headx+shape[2].getX()][heady+shape[2].getY()].setBackground(B oxPanel.NEXTDISPLAY);nextBox[headx+shape[3].getX()][heady+shape[3].getY()].setBackground(B oxPanel.NEXTDISPLAY);}/***设置显示级别*@param level*/public void setLevel(int level) {levelLabel.setText(""+level);}/***获取当前积分*@return*/public int getScore(){return Integer.parseInt(scoreLabel.getText());}*重置*/public void clean(){scoreLabel.setText(""+0);setLevel(1);for(int i=0;i<4;i++)for(int j=0;j<4;j++)nextBox[i][j].setBackground(BoxPanel.HIDE);}}/***方块类*@author Administrator**/class ABox {public final static int ROWS= 20;public final static int COLS= 10;private int id;/***用于存放方块所有样子坐标.*/private ArrayList<BoxShape>shapeTable;private String name;private int currentShapeId;/***当前方块位置.注意这里是坐标(x,y)和squares,stateTable数组的行列顺序正好相反.**/private point[]location;/***方块起始位置.*/private point head= new point(0,COLS/2);public ABox(String name,int id) {= name;this.id= id;shapeTable =new ArrayList<BoxShape>();location =new point[4];}/**public void rotate(){currentShapeId=(currentShapeId+1)>=shapeTable.size()?0:(currentShapeI d+1);point shapehead = shapeTable.get(currentShapeId).getList()[0];setHead(getHead().getX()+shapehead.getX(),getHead().getY()+shapehead. getY());}/***添加方块坐标集*@param shape*/public void addShape(BoxShape shape){shapeTable.add(shape);}/***重设方块位置.定义新的头结点.根据坐标集计算下其它子方块位置.*@param x新位置头结点坐标x*@param y*/public void setHead(int x,int y) {head.setxy(x, y);point[] shapePoint = getShape().getList();location[0] = head;location[1] = head.add(shapePoint[1]);location[2] = head.add(shapePoint[2]);location[3] = head.add(shapePoint[3]);}/***获取位置数组*@return*/public point[] getLocation(){return location;}/***获取头结点*@return*/public point getHead(){/***获取当前坐标集*@return*/public BoxShape getShape(){// get current shapereturn shapeTable.get(currentShapeId);}/***获取下一个坐标集*/public BoxShape getNextShape() {//int index = currentShapeId+1;//if (index>=shapeTable.size()) index = 0;returnshapeTable.get(currentShapeId+1>=shapeTable.size()?0:currentShapeId+1);}/***重置当前方块 .因为游戏中一直在重用方块对象.*@return*/public ABox setDefault(){setHead(4,0);currentShapeId = 0;return this;}/***获取对应坐标集*@param index*@return*/public BoxShape getShape(int index){ return shapeTable.get(index);}/***用于调试*/public String toString(){return ""+name+" "+getHead();}public int getId(){}/***产生方块*@author Administrator**/class BoxFactory {/***ArrayLIst中存放每个方块的一个对象.随机获取.*/private static ArrayList<ABox>aboxes= new ArrayList<ABox>();/***产生方块对象.*/static {/**其中包含4个点.都是相对坐标.第一个坐标是相对变形前根结点坐标的变化量,其它3坐标是相对当前根结点的变化量.对任一方块,可让其处一个3*3或4*4的方阵中,变化时不应脱离此方块,然后以此来计算根结点相对变化值.*****/ABox abox = new ABox("changtiao",1);abox.addShape(new BoxShape(2,-2,0,1,0,2,0,3));abox.addShape(new BoxShape(-2,2,1,0,2,0,3,0));aboxes.add(abox);/** ** **/abox = new ABox("fangkuai",2);abox.addShape(new BoxShape(0,0,1,0,0,1,1,1));aboxes.add(abox);** ***/abox = new ABox("3A",3);abox.addShape(new BoxShape(1,-1,-1,1,0,1,-1,2)); abox.addShape(new BoxShape(-1,1,1,0,1,1,2,1)); aboxes.add(abox);/*** ***/abox = new ABox("3B",4);abox.addShape(new BoxShape(0,0,0,1,1,1,1,2)); abox.addShape(new BoxShape(0,0,1,0,-1,1,0,1)); aboxes.add(abox);/**** **/abox = new ABox("4A",5);abox.addShape(new BoxShape(1,-1,0,1,-1,2,0,2)); abox.addShape(new BoxShape(-1,1,1,0,2,0,2,1)); abox.addShape(new BoxShape(1,-1,1,0,0,1,0,2)); abox.addShape(new BoxShape(-1,1,0,1,1,1,2,1)); aboxes.add(abox);/******/abox = new ABox("4b",6);abox.addShape(new BoxShape(1,-1,0,1,0,2,1,2)); abox.addShape(new BoxShape(1,1,-2,1,-1,1,0,1)); abox.addShape(new BoxShape(-1,-1,1,0,1,1,1,2)); abox.addShape(new BoxShape(-1,1,1,0,2,0,0,1)); aboxes.add(abox);/**/abox = new ABox("5",7);abox.addShape(new BoxShape(0,0,-1,1,0,1,1,1));abox.addShape(new BoxShape(0,0,-1,1,0,1,0,2));abox.addShape(new BoxShape(-1,1,1,0,2,0,1,1));abox.addShape(new BoxShape(1,-1,0,1,1,1,0,2));aboxes.add(abox);}/***随机获取方块*@return*/public static ABox getBox() {//return aboxes.get(new Random().nextInt(aboxes.size()));return aboxes.get(newRandom().nextInt(aboxes.size())).setDefault();}}/***方块坐标集的一个类,用于简化初始化方块时输入坐标*@author Administrator**/class BoxShape{public int dx1,dx2,dx3,dx4;public int dy1,dy2,dy3,dy4;public BoxShape(int dx1,int dy1,int dx2,int dy2,int dx3,int dy3,int dx4,int dy4){this.dx1= dx1; this.dy2= dy2;this.dx3= dx3; this.dy4= dy4;}/** this.dy1= dy1;this.dy3= dy3;this.dx2= dx2;this.dx4= dx4;*返回坐标点数组*@return*/public point[] getList(){return new point[]{new point(dx1,dy1),new point(dx2,dy2),new point(dx3,dy3),new point(dx4,dy4)};}*一个坐标的类 .可用Point,Dimension代替*@author Administrator**/class point {private int x;private int y;public point (int x,int y) {this.x= x;this.y= y;}public int getX(){return x;}public int getY(){return y;}public point add(point other){return new point(x+other.getX(),y+other.getY());}public void setxy(int x,int y){this.x= x;this.y= y;}public String toString() {return ""+x+":"+y;}}THE UNIVERSITY OF AUCKLANDFIRST SEMESTER, 2011Campus: CityCOMPUTER SCIENCEPrinciples of Programming(Time Allowed: TWO hours)Note:*The use of calculators is NOT permitted.*You should separate the Section A Question Booklet from the Section B Question/Answer Booklet. You may keep the Section A Question Booklet. You must hand in the Section BQuestion/Answer booklet and the Teleform sheet.*Compare the exam version number on the Teleform sheet supplied with the version number above. If they do not match, ask the supervisor for a new sheet.*Enter your name and student ID on the Teleform sheet. Your name should be entered left aligned. If your name is longer than the number of boxes provided, truncate it.*Answer Section A on the Teleform answer sheet provided. Each question in this section is worth 2 marks.*For Section A, use a dark pencil to mark your answers in the answer boxes on the Teleform sheet.Check that the question number on the sheet corresponds to the question number in thisquestion/answer book. Do not cross out answers on the Teleform sheet if you change your mind.You must completely erase one answer before you choose another one. If you spoil your sheet,ask the supervisor for a replacement. There is one correct answer per question.*Answer Section B in the space provided in the Section B Question/Answer Booklet.*Attempt all questions. Write as clearly as possible. The space provided will generally be sufficient but is not necessarily an indication of the expected length. Extra space is providedat the end of this exam book.CONTINUEDVERSION 00000001- 2 -COMPSCI 101PLEASE CHECK BEFORE YOU START:Have you entered your name and student ID on the Teleform sheet (letters written in the boxesand corresponding circles filled in) and on the front of the Section B question/answer booklet?*What output is produced when the following code is executed?System.out.println("[" + 4 + 4 + 3 * 5 / 2 + "," + 2 + 2 + "]");[447.5,22][15.5,22][447,22][15.5,4][15,22]*Which of the following outputs could NOT have been produced by the following code?int a = (int) (Math.random() * (4 - 1));int b = (int) (Math.random() * 4) - 1;System.out.println("a: " + a + " b: " + b);*a: 0 b: 2*a: 2 b: -1*a: 0 b: 0*a: -1 b: 2*None of the above3) What output is produced when the following code is executed?int a = 9;int b = 1;int c = a % (a - 1);int d = b % (b + 1);int sum = c + d;System.out.println("sum: " + sum);*sum: 10*sum: 2*sum: 9*sum: 1*None of the above*What output is produced when the following code is executed?String word = "SPLENDID";int pos1 = word.indexOf("S");int pos2 = word.indexOf("word");int sum = pos1 + pos2;System.out.println(sum);*-2*1*0*-1*None of the above*What output is produced when the following is executed?String word = "JOYFUL";char c = word.charAt(word.length() - 2);word = word.substring(0, 1) + word.substring(3) + c;System.out.println(word);JOFULFJFULUJOFULUJFULFNone of the above*Consider the following variable declarations:Point p1, p2;Rectangle r1, r2;p1 = new Point(10, 20);p2 = new Point(30, 40);r1 = new Rectangle(10, 20, 30, 40);r2 = new Rectangle(50, 60, 70, 80);Given these variable declarations, only ONE of the following statements will COMPILE. Which one?*boolean result = p1.intersects(p2);*boolean result = p1.contains(r1);*boolean result = p2.contains(p2);*boolean result = r2.contains(p1);*boolean result = r1.intersects(p2);7) What is the output of the following code?boolean a = true;boolean b = true;boolean c = false;if (c) {System.out.println("first");} else if (a && c){ if (a || b) {System.out.println("second"); } else {System.out.println("third");}} else if (a || c){ System.out.println("fourth");} else {System.out.println("fifth");}*fifth*third*second*first*fourth*Given the isPerfect() method defined below, which of the following sections of code prints “yes”?private boolean isPerfect(int n1, int n2, int n3) {int sum = n1 + n2 + n3;int product = n1 * n2 * n3;if (sum == product) {return true;}return false;}*if (isPerfect(0, 3, 3)){ System.out.println("yes");}*if (isPerfect(-1, 6, 1)) {System.out.println("yes");}*if (isPerfect(1, 2, 3)){ System.out.println("yes");}*if (isPerfect(2, 2, 2)){ System.out.println("yes");}(e) None of the above*What is the output of the following code?public void start(){ int a, b;a = 1;b = 2;exam(a, b);System.out.print("a: " + a + ", ");System.out.print("b: " + b);}private void exam(int a, int other) {a = a + 1;other = other + 1;}*a: 1, b: 2*a: 2, b: 3*a: 2, b: 2*a: 1, b: 3*The code would not compile because the names of the parameters in the method definition do not match the names of the variables in the statement that calls the method.10) What output is produced by the following code segment?int counter = 1;int sum = 0;while (counter <= 3) {sum += counter;}System.out.println(sum);//6//2//Nothing, because the loop never stops.//Nothing, because the variable sum is out of scope.//311) What output is produced by the following code segment?int i = 7;int counter = 0;while (i >= 0) {counter++;i = i - 3;}System.out.println(counter);*3*4*2*Nothing, because the variable counter is out of scope.*Nothing, because the loop never stops.12) A for loop has the following basic structure:for (initialisation; condition; increment) {...}Which of the following is the correct order in which the three component parts of the loop would be encountered if the loop executed exactly twice?(a) initialisation condition condition increment increment increment(c) initialisation increment increment condition condition condition(d) initialisation condition increment condition increment(e) initialisation increment condition increment condition increment13) What output is produced by the following code?String[] words = {"one", "two", "buckle", "my", "shoe"};for (int i = 0; i < words.length; i++) {if (words[i].length() <= 3){ System.out.print(words[i].charAt(0));}}*tbms*otm*bms*otbms*Nothing would be printed*What output is produced by the following code segment?int sum = 0;for (int i = 1; i < 5; i++) {sum += i;}System.out.println(sum);*15*4*6*10*Nothing, because the variable sum is out of scope.15) Consider the following while loop:int i = 10;while (i > 0) {System.out.println(i * i);i -= 2;}Which of the following for loops is equivalent to this while loop?*for (int i = 0; i < 10; i++) {System.out.println(i * i);}*for (int i = 10; i > 0; i--){ System.out.println(i * i);}*for (int i = 0; i <= 10; i=i+2) {System.out.println(i * i);}*for (int i = 10; i >= 0; i=i-2){ System.out.println(i * i);}*for (int i = 10; i > 0; i=i-2) {System.out.println(i * i);}。
java俄罗斯方块完整代码
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key==KeyEvent.VK_Q) {//如果按Q
System.exit(0);//结束Java进程
}
if(gameOver) {//如果游戏结束
T = ImageIO.read(Tetris.class.getResource("tT.png"));
I = ImageIO.read(Tetris.class.getResource("II.png"));
S = ImageIO.read(Tetris.class.getResource("SS.png"));
}else {
g.drawImage(cell.getImage(),x-1,y-1,null);//有格子贴图
}
}
}
}
//添加启动方法
public void action() {
wall = new Cell[ROWS][COLS];
//启动
startAction();
//处理键盘按下事件
KeyAdapter l = new KeyAdapter(){
if(gameOver) {
g.drawImage(overImage,0,0,null);
}
}
//画分数
private void paintScore(Graphics g) {
int x = 390;//基线位置
int y = 190;//基线位置
g.setColor(new Color(FONT_COLOR));//颜色
俄罗斯方块——java源代码
levelField = new TextField(8);
scoreField.setEditable(false);
levelField.setEditable(false);
infoScr.add(scorep);
infoScr.add(scoreField);
int [][] scrArr; //屏幕数组
Block b; //对方快的引用
//画布类的构造方法
GameCanvas(){
rowNum = 15;
columnNum = 10;
maxAllowRowNum = rowNum - 2;
b = new Block(this);
blockInitRow = rowNum - 1;
ers.addWindowListener(win_listener);
}
//俄罗斯方块类的构造方法
ERS_Block(String title){
super(title);
setSize(600,480);
setLayout(new GridLayout(1,2));
gameScr = new GameCanvas();
controlScr.add(pause_b);
controlScr.add(quit_b);
setVisible(true);
gameScr.requestFocus();
}
}
//重写MyPanel类,使P
anel的四周留空间
levelField.setSize(new Dimension(20,60));
android平台俄罗斯方块游戏完整代码
整个游戏我分为10个java文件:先是俄罗斯方块的形状存储statefang.java,代码如下:package com.example.eluosifangkuai;public class statefang { //方块的逻辑类public static int [][][] state = new i整个游戏我分为10个java文件:先是俄罗斯方块的形状存储statefang.java,代码如下:package com.example.eluosifangkuai;public class statefang { //方块的逻辑类public static int [][][] state = new int[][][] {{// I{ 0, 0, 1, 0 }, { 0, 0, 1, 0 }, { 0, 0, 1, 0 }, { 0, 0, 1, 0 } }, {// I1 { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 1, 1, 1, 1 } }, {// I2 { 0, 0, 1, 0 }, { 0, 0, 1, 0 }, { 0, 0, 1, 0 }, { 0, 0, 1, 0 } }, {// I3 { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 1, 1, 1, 1 } }, {// I4 { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 } }, {// O5 { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 } }, {// O6 { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 } }, {// O7 { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 1, 1, 0 }, { 0, 1, 1, 0 } }, {// O8 { 0, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 1, 0, 0 }, { 0, 1, 1, 0 } }, {// L9 { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 1, 1, 1, 0 }, { 1, 0, 0, 0 } }, {// L10 { 0, 0, 0, 0 }, { 0, 1, 1, 0 }, { 0, 0, 1, 0 }, { 0, 0, 1, 0 } }, {// L11 { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 1, 0 }, { 1, 1, 1, 0 } }, {// L12 { 0, 0, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 1, 0 }, { 0, 1, 1, 0 } }, {// J13{ 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 1, 0, 0, 0 }, { 1, 1, 1, 0 } }, {// J14{ 0, 0, 0, 0 }, { 0, 1, 1, 0 }, { 0, 1, 0, 0 }, { 0, 1, 0, 0 } }, {// J15{ 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 1, 1, 1, 0 }, { 0, 0, 1, 0 } }, {// J16{ 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 1, 0, 0 }, { 1, 1, 1, 0 } }, {// T17{ 0, 0, 0, 0 }, { 0, 0, 1, 0 }, { 0, 1, 1, 0 }, { 0, 0, 1, 0 } }, {// T18{ 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 1, 1, 1, 0 }, { 0, 1, 0, 0 } }, {// T19{ 0, 0, 0, 0 }, { 1, 0, 0, 0 }, { 1, 1, 0, 0 }, { 1, 0, 0, 0 } }, {// T20{ 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 1, 1, 0 }, { 1, 1, 0, 0 } }, {// S21{ 0, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 1, 1, 0 }, { 0, 0, 1, 0 } }, {// S22{ 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 1, 1, 0 }, { 1, 1, 0, 0 } }, {// S23{ 0, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 1, 1, 0 }, { 0, 0, 1, 0 } }, {// Z24{ 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 1, 1, 0, 0 }, { 0, 1, 1, 0 } }, {// Z25{ 0, 0, 0, 0 }, { 0, 0, 1, 0 }, { 0, 1, 1, 0 }, { 0, 1, 0, 0 } }, {// Z26{ 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 1, 1, 0, 0 }, { 0, 1, 1, 0 } }, {// Z27{ 0, 0, 0, 0 }, { 0, 0, 1, 0 }, { 0, 1, 1, 0 }, { 0, 1, 0, 0 } } // 28};}我们当然还要编写音乐播放类,资源播放类了等等。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
scoreField.setSize(new Dimension(20,60));
levelp.setSize(new Dimension(20,60));
levelField.setSize(new Dimension(20,60));
timer.suspend();
add(gameScr);
Panel rightScr = new Panel();
rightScr.setLayout(new GridLayout(2,1,0,30));
rightScr.setSize(120,500);
add(rightScr);
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++){
scrArr[row][col] = type;
Graphics g = getGraphics();
tch(type){ //表示画方快的方法
case 0: g.setColor(Color.black);break; //以背景为颜色画
case 1: g.setColor(Color.blue);break; //画正在下落的方块
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){
return(blockInitCol); //返回新块的初始列坐标
}
//满行删除方法
void deleteFullLine(){
int full_line_num = 0;
int k = 0;
for (int i=0;i<rowNum;i++){
boolean isfull = true;
}
public Block getBlock(){
return b; //返回block实例的引用
}
//返回屏幕数组中(row,col)位置的属性值
public int getScrArrXY(int row,int col){
if (row < 0 || row >= rowNum || col < 0 || col >= columnNum)
scoreField.setEditable(false);
levelField.setEditable(false);
infoScr.add(scorep);
infoScr.add(scoreField);
infoScr.add(levelp);
infoScr.add(levelField);
//定义按钮play
Button play_b = new Button("开始游戏");
play_b.setSize(new Dimension(50,200));
play_b.addActionListener(new Command(Command.button_play,gameScr));
setLayout(new GridLayout(1,2));
gameScr = new GameCanvas();
gameScr.addKeyListener(gameScr);
timer = new MyTimer(gameScr);
timer.setDaemon(true);
timer.start();
WindowListener win_listener = new WinListener();
ers.addWindowListener(win_listener);
}
//俄罗斯方块类的构造方法
ERS_Block(String title){
super(title);
setSize(600,480);
int blockInitRow; //新出现块的起始行坐标
int blockInitCol; //新出现块的起始列坐标
int [][] scrArr; //屏幕数组
Block b; //对方快的引用
//画布类的构造方法
GameCanvas(){
rowNum = 15;
columnNum = 10;
case 2: g.setColor(Color.magenta);break; //画已经落下的方法
}
g.fill3DRect(col*unitSize,getSize().height-(row+1)*unitSize,unitSize,unitSize,true);
g.dispose();
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){
Label scorep = new Label("分数:",Label.LEFT);
Label levelp = new Label("级数:",Label.LEFT);
scoreField = new TextField(8);
levelField = new TextField(8);
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++){
for (int col = 0 ; col <columnNum; col ++){
if(scrArr[maxAllowRowNum][col] !=0)
return true;
}
return false;
return(-1);
else
return(scrArr[row][col]);
}
//返回新块的初始行坐标方法
public int getInitRow(){
return(blockInitRow); //返回新块的初始行坐标
}
//返回新块的初始列坐标方法
public int getInitCol(){
gameScr.requestFocus();
}
}
//重写MyPanel类,使Panel的四周留空间
class MyPanel extends Panel{
public Insets getInsets(){
return new Insets(30,50,30,50);
}
}
//游戏画布类
scoreField.setText("0");
levelField.setText("1");
//右边控制按钮窗体的布局
MyPanel controlScr = new MyPanel();
controlScr.setLayout(new GridLayout(5,1,0,5));
rightScr.add(controlScr);
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");
controlScr.add(play_b);
controlScr.add(level_up_b);
controlScr.add(level_down_b);
controlScr.add(pause_b);
controlScr.add(quit_b);
setVisible(true);
maxAllowRowNum = rowNum - 2;
b = new Block(this);
blockInitRow = rowNum - 1;
blockInitCol = columnNum/2 - 2;