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 编译运行配图。
俄罗斯方块ABAP代码
*------------------------------------------------------------*
* 3.2) buttons
*------------------------------------------------------------*
* function z_nbcsh_delay .
* *"------------------------------------------------------------
* *" importing
* *" value(delay) type f default 1
* *"------------------------------------------------------------
AT PF23. "F7 ROTATE转
PERFORM fig_rotate."图形旋转
PERFORM out.
PERFORM f_call_rfc_wait.
AT PF24. "F8 RIGHT右
START-OF-SELECTION.
PERFORM init_figures."初始化方块子程序
PERFORM init_stakan."初始化图形界面子程序
PERFORM put_next_fig."下一个方块子程序
SET PF-STATUS 'STATUS_0'.
DATA: stakan TYPE c OCCURS 0,
stakan_fig LIKE stakan,
C语言编程俄罗斯方块的算法及源代码
//俄罗斯方块#include "stdio.h"#include "conio.h"#include "stdlib.h"#include "windows.h"#include "time.h"#define N 17#define M 13#define K 19int s[N][M]={{0,0,0},{0,0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0}, {1},{1,0,0,1},{1,1,1,1,1,1,0,1,1,0,0,1,1}};/*当前状态*/inta[K][3][3]={{0,2,0,2,2,2},{0,2,0,2,2,0,0,2},{0,2,0,0,2,2,0,2},{2,2,2,0,2},{2,2,2,0,0,2 ,0},{2,0,0,2,2,2},{2,0,0,2,0,0,2,2},{0,0,2,0,0,2,0,2,2},{0,0,2,2,2,2},{2,2,2,2,0,0}, {2,2,0,0,2,0,0,2,0},{0,2,2,0,2,0,0,2,0},{{2},{2},{2}},{2,2,2},{2,2,0,2,2,0},{2,0,0,2,2,0,0,2},{0,0,2,0,2,2,0,2},{2,2,0,0,2,2},{0,2,2,2,2,0}};void Disp(){int i,j;for(i=0;i<N;i++){for(j=0;j<M;j++)printf("%c",s[i][j]?48+s[i][j]:' ');printf("┃\n");}printf("━━━━━━━━");printf("\n\n操作说明:A-->左移,D-->右移,W-->变形,ESC-->退出\n");}void Down(){int i,j,k;for(j=0;j<M;j++)if(s[N-1][j]==2)break;/*判断是否在下边界*/if(j<M)/*若方块在下边界则将方块由2变1;因为用两种不同的符号,容易判断方块是否“着陆”及左右移动时,是否碰壁*/{for(i=0;i<N;i++)for(j=0;j<M;j++)if(s[i][j]==2)s[i][j]=1;for(i=N-1;i>=0;i--){for(j=0;j<M;j++)//判断第i行是否有空格if(s[i][j]==0)break;if(j==M)/*若第i行没空格消去第i行*/for(k=i++-1;k>=0;k--)//?for(j=0;j<M;j++)s[k+1][j]=s[k][j];}return;}for(i=0;i<N-1;i++){for(j=0;j<M;j++)if(s[i][j]==2)if(s[i+1][j]!=0&&s[i+1][j]!=2)break;/*方块下方不空说明触到1了退出内循环*/ if(j<M)break;/*方块下方不空退出外循环*/}if(i<N-1||j<M){for(i=0;i<N;i++)//若已触到1则将方块由 2变1*/for(j=0;j<M;j++)if(s[i][j]==2)s[i][j]=1;for(i=N-1;i>=0;i--){for(j=0;j<M;j++)if(s[i][j]==0)break;//判断第i行是否有空格if(j==M)/*若第i行没空格消去第i行*/for(k=i++-1;k>=0;k--)for(j=0;j<M;j++)s[k+1][j]=s[k][j];}return;}for(i=N-1;i>=0;i--)for(j=0;j<M;j++)if(s[i][j]==2)s[i+1][j]=s[i][j],s[i][j]=0;/*方块下移*/}void Right(){int i,j;for(i=0;i<N;i++)if(s[i][M-1]==2)return;/* 已经在右边界退出 */for(i=0;i<N;i++)for(j=0;j<M-1;j++)if(s[i][j]==2)if(s[i][j+1]!=0&&s[i][j+1]!=2)return;/* 方块右方不空,即方块右边有1 退出 */ for(j=M-2;j>=0;j--)for(i=0;i<N;i++)if(s[i][j]==2)s[i][j+1]=s[i][j],s[i][j]=0;/* 方块右移 */}void Left(){int i,j;for(i=0;i<N;i++)if(s[i][0]==2)return;/* 已经在左边界退出 */for(i=0;i<N;i++)for(j=1;j<M;j++)if(s[i][j]==2)if(s[i][j-1]!=0&&s[i][j-1]!=2)return;/* 方块左方不空退出 */ for(j=1;j<M;j++)for(i=0;i<N;i++)if(s[i][j]==2)s[i][j-1]=s[i][j],s[i][j]=0;/* 方块左移 */}int Have()/*判断是否有可移动方块,没有返回1,否则返回0*/{int i,j;for(i=0;i<N;i++)for(j=1;j<M;j++)if(s[i][j]==2)return 0;return 1;}int Add()/*随机生成方块*/{int t,x;/*生成两随机数t和x分别作为第t种方块和第x位置出现*/int i,j;srand((unsigned int)time(NULL));t=rand()%K;x=rand()%(M-3);if(x<0) x=-x%(M-3);//?for(i=0;i<3;i++)for(j=x;j<x+3;j++)//把生成的方块存到初状态中s[i][j]=a[t][i][j-x];}void bianxing(int t,int n){int i,j,k,m,x,y;for(i=0;i<N;i++)//首先扫描是否有移动方块;及方块变形前的位置“行、列”{m=-1;for(j=0;j<M;j++)if(s[i][j]==2){m=i,x=j,y=i;break;//y,x记录所在行、列;并退出内循环}if(m!=-1)//m!=-1证明有移动方块break;//退出外循环}if(m!=-1)//m!=-1证明有移动方块{if(x+3>M||y+3>N) return;//判断是否有可变形空间,没有就返回for(i=y;i<y+3;i++)//判断是否有3*3的变形空间,没有就返回for(j=x;j<x+3;j++)if(s[i][j]==1) return;/*擦除当前移动方块;因为上面判断3*3的移动空间,是从上面开始扫描,遇到第一个小格子时,依他为基点向右下方扫描是否有3*3的空间;显然只进行下面的变形--存储是不行的;如:002002022-->2220020时,显然前面的方格倒数第二个2,留在了3*3变形空间的外面,输出图形将多一个格子,所以要在变形-->存储操作前进行擦除操作*/for(i=y;i<y+3;i++)for(j=0;j<M;j++)if(s[i][j]==2)s[i][j]=0;//变形并把它存储到当前状态中if(t<=3&&t>=0){static int h1;if(h1>n)h1=0;for(i=y;i<y+3;i++)//把方块存储到当前状态中for(j=x;j<x+3;j++)s[i][j]=a[h1][i-y][j-x];h1++;}else if(t<=11&&t>=4){static int h2=4;if(h2>n)h2=4;for(i=y;i<y+3;i++)//把方块存储到当前状态中for(j=x;j<x+3;j++)s[i][j]=a[h2][i-y][j-x];h2++;}else if(t<=13&&t>=12){static int h3=12;if(h3>n)h3=12;for(i=y;i<y+3;i++)//把方块存储到当前状态中for(j=x;j<x+3;j++)s[i][j]=a[h3][i-y][j-x];h3++;}else if(t<=18&&t>=15){static int h4=15;if(h4>n)h4=0;for(i=y;i<y+3;i++)//把方块存储到当前状态中for(j=x;j<x+3;j++)s[i][j]=a[h4][i-y][j-x];h4++;}}void main(){char c;int i=0,t;char str[][50]={" ((`'-\"``\"\"-'`))"," ) - - ( "," / (o _ o) \ "," \ ( 0 ) /"," _'-.._'='_..-'_ "," /`;#'#'#.-.#'#'#;`\ "," \_)) '#' ((_/ "," #. ☆ Game ☆ # "," '#. Over! .#' "," / '#. .#' \ "," _\ \'#. .#'/ /_"," (((___) '#' (___) ",""};system("color 0a");while(1)/*判断是否有按键,没有循环输出i,否则停,conio.h*/{if(!kbhit())/*kbhit用来判断是否有按键输入,若有按键返回非零值,否则返回零;没有按键时c被赋予一个“非操作键值”,它将一直下移;有按键是调用getch函数,读取键值*/c='2';elsec=getch();if(c=='p')//停止键;按任意键可解除停止getch();system("CLS");/*清屏,TC用clrscr();,VC用system("CLS");*/if(Have())//Have()判断是否有可移动方块,没有返回1,否则返回0t=Add();switch(c){case 'a':Left();break; /*左移*/case 'd':Right();break; /*右移*/case 27: system("pause");return; /*按Esc(=27)另存后退出*/default:;}//变形if(c=='w')if(t>=0&&t<=3) bianxing(t,3);else if(t>=4&&t<=11) bianxing(t,11);else if(t==12||t==13) bianxing(t,13);else if(t>=15&&t<=18) bianxing(t,18);c='2';Down();//判断方块的停、走和消除//判断顶层是否有1 有:游戏结束for(i=0;i<M;i++)if(s[0][i]==1){system("CLS");i=0;while(1){if(strlen(str[i])==0)break;printf("%s\n",str[i++]);}system("pause");exit(0);}Disp();//刷屏Sleep(500);/*睡眠ms,windows.h*/}}***********************************************************。
俄罗斯方块-C语言-完整代码
int y; SetConsoleTextAttribute(Output,0xf0);
for(y=4;y<26;y++) {
//两条纵线 gotoxyWithFullwidth(10,y-3);//鼠标定位
gotoxyWithFullwidth(10,y-3);//鼠标定位 printf("%2s"," "); gotoxyWithFullwidth(23,y-3);//鼠标定位 printf("%2s"," "); }
bool dead;//挂 }Manager;//结构体别名
//构造存储游戏控制相关数据的结构体 typedef struct TetrisControl {
bool pause;//暂停 bool clockwise;//旋转方向;顺时针方向为ture int direction;//移动方向:0向左移动 1向右移动 //游戏池内每格的颜色 //此版本是彩色的,仅用游戏池数据无法存储颜色 int color[28][16]; }Control;//Control是结构体别名
//初始状态的游戏池 //每个元素表示游戏池的一行 //两端各置两个1,底部两行全部为1,便于进行碰撞 //这样一来游戏池的宽度为12列 共16列 //当某个元素为OXFFFF时,说明该行已经填满 //顶部4行用于给方块,不显示 //底部2行不显示,显示出来的游戏池高度为22行 static const unsigned int gs_uInitialTetrisPool[28]= {
效果图如下
俄罗斯方块-C语言-完整代码
#ifndef _DAY7_H #define _DAY7_H #include<windows.h> #include<time.h> #include<stdbool.h> #include<conio.h>//控制台输入输出函数getch通过键盘进行的操作 //游戏区域位置设计 #define COL_BEGIN 2 #define COL_END 14 #define ROW_BEGIN 4 #define ROW_END 26
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
俄罗斯方块c++源代码
#include <conio.h>#include <stdlib.h>#include<stdio.h>#include <windows.h>#include <mmsystem.h>#pragma comment(lib,"winmm.lib") //播放背景音乐的头文件#include "colorConsole.h"#include<time.h>#define SQUARE_COLOR BACKGROUD_BLUE|BACKGROUD_RED| BACKGROUD_INTENSITY //背景颜色#define SQUARE_COLOR FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_INTENSITY //方块的颜色#define up 72#define down 80#define left 75#define right 77#define esc 27#define MAPW 15 //地图的宽度#define MAPH 25 //地图的高度void initiate1();int * build(); //创建方块//初始化工作BOOL isavailable(int a[],int x,int y,int w,int h); //判定是否能放下void drawblocks(int a[],int w,int h,int x,int y,WORD wColors[],int nColors);void delete_cache(); //清除键盘缓冲区void revolve(int a[][4],int w,int h,int *x,int y); //转动方块void pro();void end();void delete_blocks(int *a,int w,int h,int x,int y);void gameover();void deletefull_line(int m[][MAPW],int row,int w,int h); //消除一行int dx=30,dy=5; //屏幕上的偏移量int score=0,level=0;int map[MAPH][MAPW];int a1[4][4]={{1},{1,1,1}};int a2[4][4]={{0,1},{1,1,1}};int a3[4][4]={{1,1},{0,1,1}};int a4[4][4]={{0,0,1},{1,1,1}};int a5[4][4]={{0,1,1},{1,1}};int a6[4][4]={{1,1,1,1}};int a7[4][4]={{1,1},{1,1}};int main(){HANDLE handle;handle=initiate();WORD wColors[1]={FOREGROUND_BLUE| FOREGROUND_GREEN|FOREGROUND_INTENSITY };while(1){sndPlaySound("Resource\\Just Dance.wav",SND_LOOP|SND_ASYNC);//用异步方式播放音乐,PlaySound函数在开始播放后立即返回system("CLS");int n=0;printf("目录\n1.开始游戏\n2.退出游戏\n\n\n");scanf("%d",&n);switch(n){case 1:system("CLS");textout(handle,22,6,wColors+2,1,"请选择游戏等级:");textout(handle,32,8,wColors+2,1,"1.初级");textout(handle,32,10,wColors+2,1,"2.中级");textout(handle,32,12,wColors+2,1,"3.高级");while(1){char choice;choice=_getch();if(choice=='1'){textout(handle,22,6,wColors+2,1,"开始游戏,初级");textout(handle,32,8,wColors+2,1," ");textout(handle,32,10,wColors+2,1," ");textout(handle,32,12,wColors+2,1," ");level=0,score=0;Sleep(2000);textout(handle,22,6,wColors+2,1," ");break;}else if(choice=='2'){textout(handle,22,6,wColors+2,1,"开始游戏,中级");textout(handle,32,8,wColors+2,1," ");textout(handle,32,10,wColors+2,1," ");textout(handle,32,12,wColors+2,1," ");level=2,score=20;Sleep(2000);textout(handle,22,6,wColors+2,1," ");break;}else if(choice=='3'){textout(handle,22,6,wColors+2,1,"开始游戏,高级");textout(handle,32,8,wColors+2,1," ");textout(handle,32,10,wColors+2,1," ");textout(handle,32,12,wColors+2,1," ");level=4,score=40;Sleep(2000);textout(handle,22,6,wColors+2,1," ");break;}else if(choice!='1'&&choice!='2'&&choice!='3')continue;}pro();break;case 2:return 0;default:printf("错误,按键继续");while(!_kbhit());}}}void pro() //游戏主题{initiate1();int *b=NULL;b=build(); //创建方块int sign,blank,x,y;while(1){for(int i=0;i<4;i++) //复制方块for(int j=0;j<4;j++)if(a[i][j]=*(b+i*4+j)) blank=i;y=1-blank;x=4;delete_blocks(&a[0][0],4,4,16,10);b=build();HANDLE handle;handle=initiate();WORD wColors[1]={FOREGROUND_BLUE| FOREGROUND_GREEN|FOREGROUND_INTENSITY };drawblocks(b,4,4,16,10,wColors,1);wColors[0]=SQUARE_COLOR;drawblocks(&a[0][0],4,4,x,y,wColors,1);delete_cache();char string[5];wColors[0]=FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_INTENSITY;textout(handle,dx-10,8+dy,wColors,1,itoa(score,string,10));textout(handle,dx-10,14+dy,wColors,1,itoa(level,string,10));sign=1;while(sign){int delay=0,max_delay=100-10*level; //延迟量while(delay<max_delay){if(_kbhit()) //用if避免按住键使方块卡住{int draw=0;int key=_getch();switch (key){case up:delete_blocks(&a[0][0],4,4,x,y);revolve(a,4,4,&x,y);draw=1;break;case down:delay=max_delay;break;case left:if(isavailable(&a[0][0],x-1,y,4,4)){delete_blocks(&a[0][0],4,4,x,y);x--;draw=1;}break;case right:if(isavailable(&a[0][0],x+1,y,4,4)){delete_blocks(&a[0][0],4,4,x,y);x++;draw=1;}break;case 32://32 是空格键的ASCII码,按空格键暂停while(1){textout(handle,dx,-2+dy,wColors,1,"Press any key to continue");Sleep(200);textout(handle,dx,-2+dy,wColors,1,"");Sleep(200);if(_kbhit()){draw=1;break;}}break;case esc://按键退出游戏exit(EXIT_SUCCESS);}if(draw){HANDLE handle;handle=initiate();WORD wColors[1]={SQUARE_COLOR};drawblocks(&a[0][0],4,4,x,y,wColors,1);draw=0;}}_sleep(5);delay++;}if(isavailable(&a[0][0],x,y+1,4,4)) //是否能下移{delete_blocks(&a[0][0],4,4,x,y);y++;HANDLE handle;handle=initiate();WORD wColors[1]={SQUARE_COLOR};drawblocks(&a[0][0],4,4,x,y,wColors,1);}else{sign=0; //标记,使跳出while(sign) 循环,产生新方块if(y<=1){system("CLS");HANDLE handle;handle=initiate();WORD wColors[1]={FOREGROUND_RED| FOREGROUND_GREEN};textout(handle,4+dx,6+dy,wColors,1,"GAME OVER!!!");textout(handle,4+dx,8+dy,wColors,1,"分数:");textout(handle,10+dx,8+dy,wColors,1,itoa(score,string,10));textout(handle,4+dx,10+dy,wColors,1,"制作者:***");delete_cache();exit(EXIT_SUCCESS);} //是否结束for(int i=0;i<4;i++) //放下方块for(int j=0;j<4;j++)if(a[i][j]&&((i+y)<MAPH-1)&&((j+x)<MAPW-1))map[i+y][j+x]=a[i][j];int full,k=0;for( i=y;i<min(y+4,MAPH-1);i++){full=1;for(int j=1;j<14;j++)if(!map[i][j]) full=0;if(full) //消掉一行{deletefull_line(map,i,MAPW,MAPH);k++;score=score+k;level=min(score/10,9);}}}}}}void initiate1() //初始化{int i;for(i=0;i<25;i++){map[i][0]=-2;map[i][14]=-2;}for(i=0;i<15;i++){map[0][i]=-1;map[24][i]=-1;}map[0][0]=-3;map[0][14]=-3;map[24][0]=-3;map[24][14]=-3;HANDLE handle;handle=initiate();WORD wColors[1]={FOREGROUND_GREEN| FOREGROUND_BLUE|FOREGROUND_INTENSITY};textout(handle,dx-10,6+dy,wColors,1,"SCORE");textout(handle,dx-10,12+dy,wColors,1,"LEVEL");textout(handle,32+dx,8+dy,wColors,1,"NEXT");wColors[0]=FOREGROUND_RED|FOREGROUND_BLUE|FOREGROUND_INTENSITY;drawblocks(&map[0][0],15,25,0,0,wColors,1);textout(handle,dx,dy,wColors,1,"◎═════════════◎");wColors[0]=FOREGROUND_BLUE|FOREGROUND_GREEN|FOREGROUND_INTENSITY;textout(handle,dx+8,dy+5,wColors,1,"按任意键开始");wColors[0]=FOREGROUND_BLUE|FOREGROUND_RED|FOREGROUND_INTENSITY ;textout(handle,dx+7,dy-3,wColors,1,"制作者:***");int x=_getch();srand(time(NULL));textout(handle,dx+8,dy+5,wColors,1," ");}int * build() //创建方块{int * a=NULL;int c=rand()%7;switch(c){case 0:a=&a1[0][0];break;case 1:a=&a2[0][0];break;case 2:a=&a3[0][0];break;case 3:a=&a4[0][0];break;case 4:a=&a5[0][0];break;case 5:a=&a6[0][0];break;case 6:a=&a7[0][0];break;}return a;}void drawblocks(int a[],int w,int h,int x,int y,WORD wColors[],int nColors) //画出方块{HANDLE handle;handle = initiate();int temp;for(int i=0;i<h;i++)for(int j=0;j<w;j++)if((temp=a[i*w+j])&&y+i>0){if(temp==-3){textout(handle,2*(x+j)+dx,y+i+dy,wColors,nColors,"◎");_sleep(30);}else if(temp==-2){textout(handle,2*(x+j)+dx,y+i+dy,wColors,nColors,"║");_sleep(30);}else if(temp==1)textout(handle,2*(x+j)+dx,y+i+dy,wColors,nColors,"◎");else if(temp==-1){textout(handle,2*(x+j)+dx,y+i+dy,wColors,nColors,"═");_sleep(30);}}}void delete_cache() //清除缓冲区{while(_kbhit()){_getch();}}void delete_blocks(int *a,int w,int h,int x,int y) //覆盖方块{HANDLE handle;handle=initiate();WORD wColors[1]={SQUARE_COLOR};for(int i=0;i<h;i++)for(int j=0;j<w;j++)if(a[i*w+j]&&i+y>0)textout(handle,2*(x+j)+dx,y+i+dy,wColors,1," ");}void revolve(int a[][4],int w,int h,int *x,int y) //转动方块{int b[4][4]={{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}};int sign=0,line=0;for(int i=h-1;i>=0;i--){for(int j=0;j<w;j++)if(a[i][j]){b[j][line]=a[i][j];sign=1;}if(sign){line++;sign=0;}}for(i=0;i<4;i++)if(isavailable(&b[0][0],*x-i,y,w,h)){*x-=i;for(int k=0;k<h;k++)for(int j=0;j<w;j++)a[k][j]=b[k][j];break;}}void deletefull_line(int m[][MAPW],int row,int w,int h) //消除满行的方块{HANDLE handle;handle=initiate();WORD wColors[1]={SQUARE_COLOR};textout(handle,2+dx,row+dy,wColors,1,"﹌﹌﹌﹌﹌﹌﹌﹌﹌﹌");_sleep(100);int i;for(i=row;i>1;i--){delete_blocks(&m[i][1],MAPW-2,1,1,i);for(int j=1;j<MAPW-1;j++)m[i][j]=m[i-1][j];drawblocks(&m[i][1],MAPW-2,1,1,i,wColors,1);}for(i=1;i<MAPW-1;i++)m[1][i]=0;}BOOL isavailable(int a[],int x,int y,int w,int h){for(int i=max(y,1);i<y+h;i++)for(int j=x;j<x+w;j++)if(map[i][j]&&a[w*(i-y)+j-x])return 0;return 1;}第二个cpp:#include "colorConsole.h"HANDLE initiate(){HANDLE hOutput;hOutput = GetStdHandle(STD_OUTPUT_HANDLE);return hOutput;}BOOL textout(HANDLE hOutput,int x,int y,WORD wColors[],int nColors,LPTSTR lpszString) {DWORD cWritten;BOOL fSuccess;COORD coord;coord.X = x; // start at first cellcoord.Y = y; // of first rowfSuccess = WriteConsoleOutputCharacter(hOutput, // screen buffer handlelpszString, // pointer to source stringlstrlen(lpszString), // length of stringcoord, // first cell to write to&cWritten); // actual number writtenif (! fSuccess)cout<<"error:WriteConsoleOutputCharacter"<<endl;for (;fSuccess && coord.X < lstrlen(lpszString)+x; coord.X += nColors){fSuccess = WriteConsoleOutputAttribute(hOutput, // screen buffer handlewColors, // pointer to source stringnColors, // length of stringcoord, // first cell to write to&cWritten); // actual number written}if (! fSuccess)cout<<"error:WriteConsoleOutputAttribute"<<endl;return 0;}二很经典的游戏.简单又让人着迷.今天就用mfc来实现个自己的俄罗斯方块.运行截图如下:看起来还行吧..网上有很多版本的实现代码.但是看了几个都是用一个很大的数组记录这些下落的物体的形状.然后写一个很大的switch case来实现变形.感觉真麻烦.今天提出一个容易的实现方法.下面切入正题思路是这样的:一:随机生成物体二:控制1.变形围绕一个方块向右旋转90度.以变形2.左右下移动1>物体左右移动的时候不要过界.2>物体落定后.(1).设定它落下的位置.(2).看是否满了一行.满了一行消去(3).看是否方块垒到顶了.到了game over三:重复以上步骤约定:下落的会变形的那个小东东,我们叫物体Object (--!!.大家忍受下这个名字.我是想不出其他的名字了.)左侧那个物体在里面移动的区域叫游戏区域Block实现这个游戏的思路跟玩这个游戏一样简单...1,随机生成一个物体.2,响应键盘的输入,做左右下移动和变形3,物体落到底部,判断是否满一行,物块垒满一行消除之.垒到顶部game over但是实现起来貌似又不是那么简单了.首先看起来随机生成一个不同形状的物体就是挑战怎么在视图上画一个个的不同形状的物体呢?我们看下这个游戏.每个物体都是由更小的方块组成.这些基本的小方块没有什么不同,再看看这个二维的游戏界面,左边的游戏区域,一个个的小方块合在一起是否就是我们所熟悉的二维数组?假如我们把这个游戏区域映射到一个二维数组,当这个数组元素有物体占据的时候就在上面涂颜色,没有则涂背景色.不就实现了么?.好了可以定义游戏的区域的数据结构了.这个游戏中由于要画不同的颜色,因此数据结构可以如下定义:2struct tagBlock3{4bSet;5COLORREF color;6}block[18][10]; // 我们将这个游戏区域格式化为18*10 (row*col);那么画一个物体又该如何画呢?假如我们先用数组定义好物体的形状,然后移动变化,那就太麻烦了.可以看到这些物体都是更小的方块组成的.(我们用四个小方块组成一个大的物体).用四个小方块,通过相对位置的不同可以变化成各种各样的不同形状.我们最终是要在那个二维数组中画不同形状的物体.那么在画的时候就要直到当前的物体应该画到哪儿.假如我们对二维数组的每个元素再抽象出来一个数据结构.在这个数据结构中保存当前它在二维数组中的位置(行列值).那就容易多了.7typedef struct tagPane9int row; // 在block[18][10]的行10int col; // 列11}Pane;这是一个小方格的定义,那每个物体要四个小方格,于是12struct tagObject13{14Pane object[4];15COLORREF color; // 每个物体有自己的颜色16int t; // 对应于最上面的一个方块的行值row17int b; // 对应于最下面一个方块行值18int l; // 对应于最左面一个方块的列值col19int r; // 对应于最右面一个方块列值20};由于我们要在画一个当前的下落的物体和一个下次将出现的物体.因此定义两个物体的对象21tagObject Object,NextObject;每个物体都是有边界的(把四个小方格全部盛下的最小矩形边界),我们把这个物体的四个小方块当前在block中的行列值,记录下来作为边界,放置在 tblr中.下面很多地方是用到这几个值的我们规定每个小方块的实际大小是 (24*24)像素那这个游戏区域实际上就是 height = 18*24 ,width = 10*24大小的矩形内(要注意数组的行列和矩形宽高的对应,col 对应的是width, row 对应的是height)22// 定义方格大小和游戏区域的矩形23const int PANE_WIDTH = 24; // 每个方格大小时24 * 24 pixel24const CRect BLOCK_RECT = CRect(29,31,271,463); // 游戏区域矩形现在的问题是,你怎么知道具体应该在视图的哪个地方画这些小方块呢?太简单了.我们可以由行列值(row,col)立即得到它在视图中所对应的矩形区域CRect(col*PANE_WIDTH,row*PANE_WIDTH,(col+1)*PANE_WIDTH,(row+1)*PANE_WIDTH); 假如我们要画一个物体,物体的四个方块的行列值都知道的.比如是在二维数组中(<0,0> <0,1> <1,0> <1,1>) 那<0,0>对应的视图的坐标矩形是(0,0,24,24)<0,1> -----(24,0,48,24)....自己那么对比几下就明白了.可以写一个函数专门获取小方块对应的实际视图中的矩形区域(实际上,我们的游戏区域不是从视图的0,0开始画的,而是上和左都有空白,左边空白LEFT_MARGIN个像素,上边空白是TOP_MARGIN个像素,因此是以(LEFT_MARGIN,TOP_MARGIN)点处作为游戏区域的左上角 .方块的长和宽相等,定义为PANE_WIDTH = 24)25// 根据坐标取得客户区矩形26CRect CRBlock::GetPaneRect(int row, int col)27{28if (row < 0 || col < 0)29{30return CRect(0,0,0,0);32returnCRect(col*PANE_WIDTH+LEFT_MARGIN,row*PANE_WIDTH+TOP_MARGIN,33(col+1)*PANE_WIDTH+LEFT_MARGIN,(row+1)*PANE_WIDTH+TOP_MARGIN);34}35//为方便.给出另一个重载的版本36// 由Pane的坐标取得对应的客户区的矩形37CRect CRBlock::GetPaneRect(Pane *p)38{39return GetPaneRect(p->row,p->col);40}现在再绘制一个物体还难么???张飞吃豆芽.!41#define RANDOM_COLOR RGB(rand()%256,rand()%256,rand()%256)42// 绘制当前下落的物体43void CRBlock::DrawFallingObject(CDC *pDC)44{45CBrush brush(Object.color);46CBrush brBorder(RANDOM_COLOR);47CBrush *pOld = pDC->SelectObject(&brush);48for (int i = 0; i < 4; i++)49{50CRect rc = GetPaneRect(&(Object.object[i]));51if (!rc.IsRectNull()) //这个组成物体的小方块还未出现在游戏区域内52{53pDC->Rectangle(&rc);54pDC->FrameRect(&rc,&brBorder); // 绘制边界,看起来会漂亮点哦.55}56}57pDC->SelectObject(pOld);58}咦.郁闷了...吃豆芽的时候遇到点problem.....需要绘制下一个将出现的物体.这个物体不是绘制在游戏区域内的.而是在游戏区域的右侧.没关系.假如我们在游戏区域和这下个物体绘制的区域之间隔一个方块的宽度.所有的问题都又解决了,原来的函数还照样可以用......继续吃豆芽59const CRect RECT_NEXTOBJECT = CRect(294,30,438,174); // 在这个矩形局域画下一个物体4*6 *PANE_WIDTH 大小60//294 = LEFT_MARGIN + 10 * PANE_WIDTH + 1*PANE_WIDTH;61现在这个4*6的区域的左上角,即是第一个方格的列坐标就是10+1 = 11 了.至于行坐标,由于这个区域是和原来的游戏区域上对齐的,所以依然是0;62// 绘制下一个将出现的物体63void CRBlock::DrawNextObject(CDC *pDC)64{65int l = NextObject.l;66int t = NextObject.t;67int r = NextObject.r;68int b = NextObject.b;6970// 把NextObject 的行列映射到要画在的矩形中71int offsetRow = (0+(6-(b-t+1))/2)-t; /// 这只是要把物体画到这个区域的中心72int offsetCol = (11+(6-(r-l+1))/2)-l; //7374// 这一段只是美化75CBrush brBkgnd(COLOR_BKGND);76CBrush *pOld = pDC->SelectObject(&brBkgnd);77CPen pen;78pen.CreatePen(PS_SOLID,1,RANDOM_COLOR);79CPen *pOldPen = pDC->SelectObject(&pen);80pDC->Rectangle(&RECT_NEXTOBJECT);81pDC->SelectObject(pOldPen);82pDC->SelectObject(pOld);8384CBrush brush(NextObject.color);85CBrush brBorder(RANDOM_COLOR);86pDC->SelectObject(&brush);87// 画下一个物体88for (int i = 0; i < 4; i++)89{90int row = NextObject.object[i].row;91int col = NextObject.object[i].col;92CRect rc = GetPaneRect(row+offsetRow,col+offsetCol);93if (!rc.IsRectNull())94{95pDC->Rectangle(&rc);96pDC->FrameRect(&rc,&brBorder);97}98}99}1>生成物体大家想的都过于复杂了.生成物体只是为几个小方块生成几个行列值,当然这个行列值不是随意的.而是有限制的.假如我们让第一个方块的行列值为 <-1,4> 然后依据这个方块在它的上下左右四个方向随机生成第二个方块,然后再根据第二个生成第三....根据第三个生成第四个.每个方块都是上一个方块的上下左右四个方向中非上一个方块的地方,那这个生成的物体正是我们要的!!!不信在纸上画一下! 根据这个思路进行改变.可以生成任何你要的形状!! 但是这样生成的却没有 T 形状的...(下面给出的是可以生成这个形状的代码)知道了上一个方块的位置,我们只要一个相对于上一个方块位置的偏移就好了(0,1) ---- 右(-1,0) ---- 上(1,0) ---- 下(0,-1) -- 左我们随机在这四个偏移量中拿出一个,生成下一个物体,但是又不能和上一个物体重叠 ,其实这次生成的偏移量不等于上一次生成偏移量的取反就满足要求.(在纸上画一下.任何时候你在纸上画画都能很快想明白一些问题,有时会得到不同的灵感)1// 随机的产生物体2void CRBlock::GenerateObject(struct tagObject &obj)3{4obj.object[0].row = obj.object[3].row = -1;5obj.object[0].col = obj.object[3].col = 4;6int x = -2,y = -2; // x,y 为偏移量7for (int c = 1; c <= 2; c++)8{9MakeRandomOffset(x,y); // 每次产生的位移不能是上一个方块的位置10obj.object[c].row = obj.object[c-1].row + x;11obj.object[c].col = obj.object[c-1].col + y;12x=-x,y=-y; // 上次生成的偏移量的取反13}14UpdateLimit(obj);15MakeRandomOffset(x,y);16/// 这个只是为了要得到一个T 形状的物体而做的.否则把下面的代码写到上面的循环中就完成任务了17if (obj.r-obj.l == 2 || obj.b-obj.t == 2)18{19obj.object[c].row = obj.object[1].row + x;20obj.object[c].col = obj.object[1].col + y;21}22else23{24obj.object[c].row = obj.object[2].row + x;25obj.object[c].col = obj.object[2].col + y;26}27obj.color = RANDOM_COLOR;28UpdateLimit(obj);29}3031// 随即产生一个偏移量.这个偏移量不能是参数x和y相同的32// 随即值只有4种可取,即是x和y的绝对值不相同的.(0,0) (+-1,+-1) 的偏移都是不合法的.33void CRBlock::MakeRandomOffset(int &offsetX, int &offsetY)34{35static const int offset[] = {-1,0, 1,0, 0,-1, 0,1};36int oldX = offsetX;37int oldY = offsetY;38do39{40int _i = (rand()%4)*2;41offsetX = offset[_i];42offsetY = offset[_i+1];43} while (offsetX == oldX && offsetY == offsetY);44}4546上面有一个函数还没有定义下面就是:4748// 更新物体的上下左右边界49// 左和上取最小50// 右和下取最大51void CRBlock::UpdateLimit(struct tagObject &obj)52{53obj.l = obj.object[0].col;54obj.r = obj.object[0].col;55obj.t = obj.object[0].row;56obj.b = obj.object[0].row;57for (int i = 1; i <= 3; i++)58{59if (obj.l > obj.object[i].col)60{61obj.l = obj.object[i].col;62}63if (obj.r < obj.object[i].col)64{65obj.r = obj.object[i].col;66}67if (obj.t > obj.object[i].row)68{69obj.t = obj.object[i].row;70}71if (obj.b < obj.object[i].row)72{73obj.b = obj.object[i].row;74}75}76}假如你不想要这样的形状,你可以调整生成的四个小方块的相对位置.就这样简单几步你就可以生成任何你想要的形状.爽否?三>变形上面是吃豆芽,下面就是啃骨头了.这是本程序的第二个难点真的那么难么?你认为变形会如何解决?说出来真让人失望.但又不得不说.这个骨头如此的脆弱,以至于当初摩拳擦掌准备下一翻苦功夫,栽几个大跟头的决心后备都用不上了,像是下了老劲而一拳打在了棉花上.用钱钟书在<围城>里形容李梓梅见到"情敌"方鸿渐的时候的话说:这是快意的失望!(最近在看<围城>,钱钟书真是人才.写的书太好了.)假如我们先找出这四个小方块最中间的一个,让它保持位置不变.而让其余的三个方块围着他向右做90度的旋转.是不是就是变形了?估计有人在这个时候该骂 "他妈的" 了...我当时就是.在纸上坐标啊.角啊,余弦啊,比划了半天.结果就是这样就变形了. 真 "他妈的".但是我想用三角函数和角在一个 x轴向右为正方向,y轴向下为正方向的坐标象限内(二维数组的逻辑)进行变形.就只是套用几个三角函数的公式就能完成了.这样程序将会简洁许多了.谁数学好,可以做一下,做好别忘了告诉我啊.(恨当初不该花那么多的时间跑出去玩通宵,数学没学好,真是后悔的我肠子都青了.童鞋们引以为戒).现在是0点48分.每这个时候大脑都会脱离我的精神独立控制四肢,因此废话多了些.说话意识流了点儿.不要介意.--!!下面是变形的代码:变形的过程中要注意的事情是:变形后不能覆盖住原来已经存在的方块位置.不能超出游戏区域边界.因此一旦变形失败就重建到原来的状态.77// 方块变形78// 变形的实现步骤:79// 找出4个方块的中心方块..80// 其他3个方块围绕这个方块向右旋转90度.81// 其他3个方块相对于这个中心方块的位置只可能时8中情况,82// 即是它的八个方向(包括对角线上的和水平垂直)83// 这个算法对物体变形的同时可能会造成物体左移,因此规定连续两次变形就右移一列84void CRBlock::Transform()85{86// 假如变形后失败,则重建到原来状态87struct tagObject objTemp = Object;88// 以(row,col)为中心旋转89int l = Object.l;90int ri = Object.r;91int t = Object.t;92int b = Object.b;93if (ri-l == b-t) // 正方形方块不变形,这个判断依据是,只有正方形的长和宽是相等的94{95return;96}97const int r = (t + b)/2;98const int c = (l + ri)/2;99// 变形实现,对4个小方块依次判断重新设定位置100 for (int i = 0; i < 4; i++)101 {102103 int &row = Object.object[i].row;104 int &col = Object.object[i].col;105 if ( row== r && col == c) // 中心方块不旋转106 continue;107 int offsetX = col - c;108 int offsetY = row - r;109 // 分八种情况分别变化110 if (offsetX > 0) // 在中心方块右边111 {112 if (offsetY == 0) // 正右方113 { // 到正下方114 row = r + offsetX;115 col = c;116 }117 else if (offsetY > 0) // 在右下方118 { // 到左下方119 col = c - offsetX;120 }121 else // 右上方122 { // 到右下方123 // 列不变124 row = r - offsetY;125 }126 }127 else if (offsetX == 0) // 和中心点在同一列,offsetY有正负号,恰好可以写成一个式子128 {129 row = r;130 col = c - offsetY;131 }132 else // 在中心方块左边133 {134 if (offsetY > 0) // 左下135 {// 到左上136 //列不变137 row = r - offsetY;138 }139 else if (offsetY == 0)// 正左方140 {// 到正上方141 row = r + offsetX;142 col = c;143 }144 else // 左上145 {// 到右上146 // 行不变147 col = c - offsetX;148 }149 }150 if (col < 0 || col >= 10 || (row > 0 && block[row][col].bSet)) // 变形失败151 {152 Object = objTemp;153 return;154 }155 }156 UpdateLimit(Object); // 更新方块的边界157 if (m_nTimesTransform == 2) // 连续变形了两次158 {159 Move(RIGHT); // 右移一个单位160 m_nTimesTransform = 0;161 }162 }3> 控制控制程序比控制我自己的意识要容易多了. 响应键盘的上下左右键就万事大吉enum {TRANSFORM = 0,DOWN = 2,LEFT = -1,RIGHT = 1,FASTTOBOTOOM = 3};先定义好变形和移动代码,在switch case中用到.FASTTOBOTOOM = 3 是什么意思咧? 先它是说不要一格一格的移动而要立即落到底部滴干活.每按一下向下的方向键它就下移动一行,但是要按空格键它就会立即下落到底部了.(对急性子和需要炫耀自己反应灵敏的人来说这个定义尤其爽!我属于有时候会炫耀自己反应敏捷的急性子的人!每次按空格键浑身都舒畅无比)....需要很多代码么?不需要.需要的是一点编码技巧1// 移动2// 左右下3void CRBlock::Move(int to)4{5int i;6switch (to)7{8case TRANSFORM: // 方向键向上是变形9m_nTimesTransform++; // 连续变形的次数10Transform();11break;12case LEFT:13case RIGHT:14if (IsBorder(to)) // 到最左或最右边或者物体下面有物体阻挡15{16return;17}18for (i = 0; i < 4; i++)19{20Object.object[i].col += to;21}22Object.r += to;23Object.l += to;24break;25case DOWN: // 一行26MoveDown(FALSE);27break;28case FASTTOBOTOOM: // 到底儿29MoveDown(TRUE);30break;31}32}技巧在这儿,do while 循环配合BOOL参数加上break.不需要额外的判断,顺溜的就向<梦想照进现实>中的那男人喝的好酒:冰爪子,从这儿下去到胃里成火线了.冰火两重天,你来试试!33// 向下移动bContinue 代表是一次到底还是移动一行34void CRBlock::MoveDown(BOOL bContinue)35{36do37{38if (IsBottom()) // 到底了39{40SetBlockFlag();41IsLineFull(); // 是否一行满?42if (Object.t < 0) // 组成当前物体的最上面的方块在游戏区域外43GameOver();44Object = NextObject;45GenerateObject(NextObject);// 产生下一个46m_nTimesTransform = 0; // 新产生的方块还未变形47break;48}49for (int i = 0; i < 4; i++)50{51Object.object[i].row += 1; // 方块下移一行52}53Object.b += 1; // 方块边界变了54Object.t += 1;55} while (bContinue);56}在移动物体的时候要注意的事项:1>不能过界吧2>不能覆盖已有物体吧57// 检测正在下落的物体下面是否已经存在物体了58// 或者到了最下面59BOOL CRBlock::IsBottom()60{61if (Object.b >= 17) // 游戏区域时10 * 18 转换到数组是9 17 ,9 是最右,17 是最下62{63return TRUE;64}65for (int c = 0; c < 4; c++) // 找出每一个物体的4个方块的位置然后判断66{67int i = Object.object[c].row;68int j = Object.object[c].col;69if ((i >= 0 && j >= 0) && block[i+1][j].bSet) // 此处已经有物体了70{71return TRUE;72}73}74return FALSE;75}物体落下后要干什么?当然是保存它落下的位置了?76// 检查现在在游戏区域中最上面的一个物体所在row (0 ~ 17)77// 在物体落下的位置标志为true.表示应该在这个地方画图形78void CRBlock::SetBlockFlag(BOOL bSet)79{80if (m_topLine > Object.t)81{82m_topLine = Object.t;83}84// 检测组成物体的4个方块的位置85for (int c = 0; c < 4; c++)86{87int i = Object.object[c].row;88int j = Object.object[c].col;89block[i][j].bSet = TRUE; // 设置此处已经被物体占据90block[i][j].color = Object.color;91}92}m_topLine 又是什么东东? 是当前垒的最高的物体所在二维数组的行值.这个值变成小于0 就算是game over了.....希望你垒的最后一块砖不是长条.....因为那样就像是囧到极点的老坟! ----- 装上了避雷针的埃及金字塔! <猜火车>中屎霸对马克说:That's fucking nightmare! 物体落下后光记录它落在的位置还不够,还得判断是否一行满了.93// 看一行是否满了,假如某一行都被标记为TRUE就时满了94BOOL CRBlock::IsLineFull()95{96int s = Object.t; // 最上97int topLine = m_topLine;98for (int e = Object.b; e >= s;) // e 和s都有被改变的可能99{100 int k = 0;101 for (k; k < 10; k++)102 {103 if (!block[e][k].bSet) // 未满104 {105 break;106 }107 }108 if (k == 10) // 满了就得删除这一行,并且自这行向上的行都要下移一行109 {110 for (int i = e; i >= m_topLine; i--)111 {112 for (int j = 0; j < 10; j++)113 {114 block[i][j].bSet = block[i-1][j].bSet;115 }116 }117 for (i = 0; i < 10; i++)118 {119 block[m_topLine][i].bSet = FALSE;120 }121 m_score += 100;122 m_topLine++; // 删除一行,则最高行向下移动一行123 s++; // Object所占的位置最上的一行要下移一行124 }125 else // 没有满126 {127 e--; // 则从object所占的位置行自下向上依次检测128 }129 }130 return FALSE; 131 }。
俄罗斯方块python代码
俄罗斯方块python代码首先,解释一下俄罗斯方块的规则。
俄罗斯方块是一种经典的益智游戏,玩家需要操作方块,在一个逐渐升高的场景中,将方块拼接在一起,以便填满场地的横行。
一旦填满一行,该行将被消除,这样就会为新的方块提供更多的空间。
玩家可以利用不断下落的方块,进行更高难度的拼图和连锁爆破,获取更高的分数。
下面我将介绍如何用Python编写俄罗斯方块游戏。
首先要实现的是基本的游戏框架。
我们需要使用Python中的pygame库,它提供了许多游戏开发所需的功能。
通过pygame实现的基本游戏框架如下:import pygame from pygame.locals import *# 初始化pygame pygame.init()# 定义颜色 BLACK = ( 0, 0, 0) WHITE = ( 255, 255, 255) BLUE = ( 0, 0, 255)# 设置屏幕尺寸 size = (400, 500) screen = pygame.display.set_mode(size)# 设置窗口标题 pygame.display.set_caption("俄罗斯方块")# 游戏主循环 done = False while not done: for event in pygame.event.get(): ifevent.type == pygame.QUIT: done = True # 界面绘制 screen.fill(WHITE)# 画出方块 pygame.draw.rect(screen, BLUE, [500, 0, 50, 50])# 将图像更新到屏幕上pygame.display.flip()# 退出游戏 pygame.quit()上述代码创建了一个窗口,准备开始游戏开发。
但是我们需要对其进行改进,以便创建一个完整的俄罗斯方块游戏。
接下来,我们需要定义方块的基本形状。
俄罗斯方块游戏原代码
#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键,退出游戏 */}}。
俄罗斯方块游戏的开发需求分析
俄罗斯方块游戏的开发组长:XXX组员:XXX XXX XXX XXX05软件工程一班一、课程设计的目的和意义俄罗斯方块游戏是一个经典的小游戏,由于它简单有趣,因而得到了广泛的流行,男女老幼都适合。
而俄罗斯方块游戏的设计工作复杂且富有挑战性,它包含的内容多,涉及的知识广泛,与图形界面联系较大,包括界面的显示与更新、数据收集等,在设计的过程中,必将运用到各方面的知识,这对于visualbasi语言设计者而言,是个很好的锻炼机会。
二、系统功能设计本系统主要设计以下几种功能1、游戏难度选择功能游戏难度选择界面设置在程序运行开始时,一共有九种难度供玩家选择,每选一级难度,都会相应地显示出代表该难度的图片。
开始时不设置任何默认的难度,如果玩家不选难度直接按“Enter”进入,将会弹出提示框,提示其先选难度再进入。
2、方块下落、变形功能在整个俄罗斯方块游戏中,方块的设计是核心。
这里设计了一个方块类:Square(),用来生成方块以及实现块的左移、右移、向下、变形、重画、同步显示、初始化新块等。
3、自动升级功能当分数累积到一定大小时,系统将自动为玩家提高难度。
这里设置了每消除10行方块,就增加一级难度。
当难度增加的时候,方块会相应地改变颜色,以作为对玩家的提示。
4、游戏音乐功能游戏开始音乐就自动播放,游戏暂停与结束时音乐相应消除。
5、获取帮助功能这里设置了一个类,用来显示帮助,按F1键就能弹出窗口,显示游戏规则。
三、系统功能设计分析俄罗斯方块游戏根据功能的不同,设置了如下12个类:Square,Command,GameArea,GameSetting,GameOver,Help,ImagePanel,JieMian,MyPanel, MyTimer,PlayMidi,WinListener,每个类的描述如下:1、Square,方块类。
这个类中定义了生成方块的方法,用二维数组int[][]pattern,存放7种方块的四种状态。
俄罗斯方块代码
int getW();
int getH();
void clearOldBox();
void putNewBox();
int collisionRotate(int box[][4]);
void getMessage();
void dispatchMessage();
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x20,0x00,0x01,0x00,0x70,0x00,
0x01,0x00,0x30,0x00,0x01,0x00,0x30,0x00,
0x00,0xF4,0x00,0xE0,0x0F,0x86,0x00,0xC0,
0x00,0x03,0x83,0x00,0x00,0x00,0x3C,0x00,
0x00,0x00,0x70,0x00,0x00,0x03,0xC0,0x00,
0x00,0x7E,0x00,0x00,0x3F,0xF0,0x00,0x00,
#define WINY 470
#define GAP 6
#define AREAX (WINX+GAP)
#define AREAY (WINY-GAP)
#define BOXW 15
int oldarea[MAXY+1][MAXX];
0x00,0xE0,0x06,0x00,0x03,0xC0,0x06,0x00,
0x0F,0x80,0x0C,0x00,0x3E,0x04,0x38,0x00,
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};}我们当然还要编写音乐播放类,资源播放类了等等。
C语言小游戏源代《俄罗斯方块》
C语言小游戏源代码《俄罗斯方块》#include <stdlib.h>#include <stdio.h>#include <graphics.h>#define ESC 27#define UP 328#define DOWN 336#define LEFT 331#define RIGHT 333#define BLANK 32#define BOTTOM 2#define CANNOT 1#define CAN 0#define MAX 30#define F1 315#define ADD 43#define EQUAL 61#define DEC 45#define SOUNDs 115#define SOUNDS 83#define PAUSEP 80#define PAUSEp 112void Init();void Down();void GoOn();void ksdown();void Display(int color);void Give();int Touch(int x,int y,int dx,int dy);int GeyKey();void Select();void DetectFill();void GetScores();void Fail();void Help();void Quit();void DrawBox(int x,int y,int Color);void OutTextXY(int x,int y,char *String); void DispScore(int x,int y,char Ch);void DrawNext(int Color);int Heng=12,Shu=20; /*横竖*/int Position[MAX][MAX];int middle[MAX][MAX];int ActH,ActS;int Act,Staus;int i,j,k;int Wid=10;int NoPass=CAN;float Delays=15000;int BeginH=250,BeginS=7;float Seconds=0;int Scores=0;int flag=1;int Sounds=CAN;int PreAct,NextAct;int a[8][4][4][4]={{{1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0}, {1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0},{1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0},{1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0}},{{1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0},{1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0},{1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0},{1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0}},{{1,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0},{0,1,0,0,1,1,0,0,0,1,0,0,0,0,0,0},{0,1,0,0,1,1,1,0,0,0,0,0,0,0,0,0},{1,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0}},{{1,0,0,0,1,1,0,0,0,1,0,0,0,0,0,0},{0,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0},{1,0,0,0,1,1,0,0,0,1,0,0,0,0,0,0},{0,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0}},{{0,1,0,0,1,1,0,0,1,0,0,0,0,0,0,0},{1,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0},{0,1,0,0,1,1,0,0,1,0,0,0,0,0,0,0},{1,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0}},{{1,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0},{1,1,0,0,1,0,0,0,1,0,0,0,0,0,0,0},{1,1,1,0,0,0,1,0,0,0,0,0,0,0,0,0}, {0,1,0,0,0,1,0,0,1,1,0,0,0,0,0,0}}, {{0,0,1,0,1,1,1,0,0,0,0,0,0,0,0,0}, {1,0,0,0,1,0,0,0,1,1,0,0,0,0,0,0}, {1,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0}, {1,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0}}, {{1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0}}}; int b[4][4];main(int argc,char *argv[]){if (argc!=1){if (argv[1]!="")Heng=atoi(argv[1]);if (argv[2]!="")Shu=atoi(argv[2]);}Init(); /*初始化界面*/PreAct=random(8); /*取得当前的方块*/ for(;;) /*以下是游戏流程*/{NextAct=random(8); /*取得下一个方块*/ DrawNext(1); /*画出下一个方块*/Act=PreAct;if (Heng%2==0) ActH=Heng/2;else ActH=(Heng-1)/2;ActS=0; /*方块开始从游戏空间的中间下落*/Staus=0; /*取开始的状态*/NoPass=CAN; /*物体可以下落*/Give(); /*取得当前的方块*/Display(Act+1); /*显示当前的方块,每种方块的颜色不同*/ GoOn(); /*游戏的算法精髓所在*/PreAct=NextAct; /*方块下落完毕,取得下一个方块*/ DrawNext(0);}}void Init(){int GraphDriver=DETECT,GraphMode;registerbgidriver(EGAVGA_driver);initgraph(&GraphDriver,&GraphMode,"");if (kbhit()) Sounds=CANNOT;setcolor(1);OutTextXY(10,10,"Tetris");OutTextXY(30,30,"Version 2.0");OutTextXY(10,120,"Help:");OutTextXY(20,140,"+ :Faster");OutTextXY(20,160,"- :Slower");OutTextXY(20,180,"Esc :Quit");OutTextXY(20,200,"F1 :Help");OutTextXY(10,310,"Copyright(c) 1998.2.22");OutTextXY(10,320,"By Mr. Unique");outtextxy(10,250,"Score: 00000");rectangle(BeginH-3,BeginS-3,BeginH+Heng*(Wid+2)+2,BeginS+Shu*(Wid+2)+2);rectangle(BeginH-5,BeginS-5,BeginH+Heng*(Wid+2)+4,BeginS+Shu*(Wid+2)+4);rectangle(BeginH+(Heng+4)*(Wid+2)-2,BeginS+10,BeginH+(Heng+8)*(Wid+2)+2,BeginS+12+4*( Wid+2));for (i=0;i<MAX;i++)for (j=0;j<MAX;j++){Position[i][j]=1;middle[i][j]=-1;}for (i=0;i<Heng;i++)for (j=0;j<Shu;j++)Position[i][j]=0;for (i=0;i<Heng;i++)for (j=0;j<Shu;j++)DrawBox(i,j,0);randomize();}void GoOn(){for(;;){Seconds+=0.2; /*控制方块的下落速度*/if (Seconds>=Delays){Down();Seconds=0;if (NoPass==BOTTOM){DetectFill();middle[ActH][ActS]=Act;if (ActS==0)Fail();return;}}if (kbhit())Select();}}void Down() /*方块下降*/{Display(0);if (Touch(ActH,ActS,0,1)==CAN) ActS++;elsemiddle[ActH][ActS]=Act; Display(Staus+1);}int Touch(int x,int y,int dx,int dy) {NoPass=CAN;for (i=0;i<4;i++)for (j=0;j<4;j++)Position[x+dx+i][y+dy+j]+=b[i][j];for (i=0;i<MAX;i++)for (j=0;j<MAX;j++)if (Position[i][j]>1)NoPass=CANNOT;for (i=0;i<4;i++)for (j=0;j<4;j++){Position[x+dx+i][y+dy+j]-=b[i][j]; middle[x+dx+i][y+dy+j]=Act;}if (NoPass==CANNOT && dx==0 && dy==1) {for (i=0;i<4;i++)for (j=0;j<4;j++)Position[x+i][y+j]+=b[i][j];NoPass=BOTTOM;}return NoPass;}int GetKey(void){int Ch,Low,Hig;Ch=bioskey(0);Low=Ch&0x00ff;Hig=(Ch&0xff00)>>8;return(Low==0?Hig+256:Low);}void Select(){int OldStaus,acts=ActS;switch(GetKey()){case ESC :Quit();break;case DOWN :Seconds+=14500;break;case LEFT :Display(0);if (ActH>0 && Touch(ActH,ActS,-1,0)==CAN) { ActH--;}Display(Act+1);break;case RIGHT :Display(0);if (ActH<Heng && Touch(ActH,ActS,1,0)==CAN) { ActH++;}Display(Act+1);break;case BLANK : Display(0);ksdown();Display(Act+1);break;case F1 :Help();break;case EQUAL :case ADD :if (Delays>300) Delays-=100;break; case DEC :if (Delays<3000) Delays+=100;break; case PAUSEP :case PAUSEp :getch();break;case SOUNDS :case SOUNDs :if (Sounds==CAN)Sounds=CANNOT;elseSounds=CAN;break;case UP :if(Act==7){while(acts<Shu-1&&Position[ActH][acts]!=1) acts++;Position[ActH][acts]=0;DrawBox(ActH,acts,0);acts=ActS;break;}else{Display(0);OldStaus=Staus;switch(Act){case 0:case 3:case 4:if (Staus==1) Staus=0;else Staus=1;break; case 1:break;case 2:case 5:case 6:if (Staus==3) Staus=0;else Staus++;break; }Give();if (Touch(ActH,ActS,0,0)==CANNOT){Staus=OldStaus;Give();}Display(Act+1);break;}}}void ksdown(){while(flag){if(Touch(ActH,ActS,0,0)==CAN){ActS++;}else {ActS--;flag=0;}}flag=1;}void Quit(){int ch,TopScore;FILE *fp;if ((fp=fopen("Russian.scr","r+"))!=NULL) {fscanf(fp,"%d",&TopScore);if (Scores>TopScore){setcolor(1);outtextxy(470,80,"Hello !");outtextxy(470,100,"In all the players,"); outtextxy(470,120,"You are the First !"); outtextxy(470,140,"And your score will"); outtextxy(470,160,"be the NEW RECORD !"); fseek(fp,0L,0);fprintf(fp,"%d",Scores);}fclose(fp);}setcolor(1);OutTextXY(470,220,"Are You Sure (Yes/no)?");ch=getch();if (ch=='y'||ch=='Y'){closegraph();delay(20);exit(0);}setcolor(0);outtextxy(470,220,"Are You Sure (Yes/no)?"); }void OutTextXY(int x,int y,char *String) {int i=0;char a[2];moveto(x,y);a[1]='\0';while (*(String+i)!='\0'){a[0]=*(String+i);outtext(a);if (Sounds==CAN && a[0]!=' '){sound(3000);delay(50);nosound();}i++;}}void Help(){unsigned Save;void *Buf;Save=imagesize(160,120,500,360);Buf=malloc(Save);getimage(160,120,500,360,Buf);setfillstyle(1,1);bar(160,120,500,280);setcolor(0);OutTextXY(170,130," About & Help");OutTextXY(170,150," # # # ########## # # # "); OutTextXY(170,160," # ## # # # # # # ###### ### "); OutTextXY(170,170," ########## ########## ## # # "); OutTextXY(170,180," # # # # # # # ## #### "); OutTextXY(170,190," # ## # #### ## # # # "); OutTextXY(170,200," # ## # # # # # ## # # # "); OutTextXY(170,210," # # # ## ## # ###### # # # "); OutTextXY(170,220," ## # ## # ## # # # # "); OutTextXY(170,230," # ## # #### # ## # "); OutTextXY(170,260," Good Luckly to You !!! ");getch();putimage(160,120,Buf,0);free(Buf);}void GetScores(){int Sec10000,Sec1000,Sec100,Sec10,Sec1; setfillstyle(0,1);bar(60,250,109,260);Sec1=Scores%10;Sec10=(Scores%100-Scores%10)/10;Sec100=(Scores%1000-Scores%100)/100;Sec1000=(Scores%10000-Scores%1000)/1000; Sec10000=(Scores%100000-Scores%10000)/10000; DispScore(60,250,'0'+Sec10000);DispScore(70,250,'0'+Sec1000);DispScore(80,250,'0'+Sec100);DispScore(90,250,'0'+Sec10);DispScore(100,250,'0'+Sec1);DispScore(110,250,'0');DispScore(120,250,'0');}void DispScore(int x,int y,char Ch){char a[2];a[1]='\0';a[0]=Ch;outtextxy(x,y,a);void Give(){for (i=0;i<4;i++)for (j=0;j<4;j++)b[i][j]=a[Act][Staus][i][j];}void Display(int color){for (i=0;i<4;i++)for (j=0;j<4;j++)if (b[i][j]==1) DrawBox(ActH+i,ActS+j,color); }void DrawBox(int x,int y,int Color){x=BeginH+x*(Wid+2);y=BeginS+y*(Wid+2);setfillstyle(1,Color);bar(x+2,y+2,x+Wid-1,y+Wid-1);if (Color==0)setcolor(9);elsesetcolor(Act+1);rectangle(x+4,y+4,x+Wid-4,y+Wid-4);}void DrawNext(int Color)for (i=0;i<4;i++)for (j=0;j<4;j++)if (a[NextAct][0][i][j]==1) DrawBox(Heng+4+i,1+j,Color); }void DetectFill(){int Number,Fall,FallTime=0;for (i=Shu-1;i>=0;i--){Number=0;for (j=0;j<Heng;j++)if (Position[j][i]==1) Number++;if (Number==Heng){FallTime++;if (Sounds==CAN){sound(500);delay(500);nosound();}for (Fall=i;Fall>0;Fall--)for (j=0;j<Heng;j++){Position[j][Fall]=Position[j][Fall-1];middle[j][Fall]=middle[j][Fall-1];if (Position[j][Fall]==0) DrawBox(j,Fall,0); else DrawBox(j,Fall,middle[j][Fall]+1);}i++;}}switch(FallTime){case 0:break;case 1:Scores+=1;break;case 2:Scores+=3;break;case 3:Scores+=6;break;case 4:Scores+=10;break;}if (FallTime!=0){GetScores();if (Scores%100==0) Delays-=100;}}void Fail(){if (Sounds==CAN){for (k=0;k<3;k++){sound(300);delay(200);nosound();}}setcolor(1);OutTextXY(440,200,"Game over!"); Quit();closegraph();exit(0);}。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
不多说,,直接可以拷贝下面的东西,然后记得把那个BLOCK的名字改成你自己的类名,这个很关键哦,不然是错的可别怪我,呵呵~~import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.applet.*;import ng.String.*;import ng.*;import java.io.*;public class Block 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[]){Block myBlock = new Block();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;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[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;game_body[game_sign_y[3] - 1][game_sign_x[3] - 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[2][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[3][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{Block myBlock;public MyTimer(Block myBlock){this.myBlock = myBlock;}public void run(){while(myBlock.startSign == 1){try{sleep((10-myBlock.speedMark + 1)*100);myBlock.down();}catch(InterruptedException e){}}}}。