shell脚本制作俄罗斯方块游戏

合集下载

小游戏源代码

小游戏源代码
}
/* create a new block by key number,
* the block anchor to the top-left corner of 4*4 cells
*/
void _INNER_HELPER GenerateBlock(Block *block)
/*Scan Codes Define*/
enum KEYCODES
{
K_ESC =0x011b,
K_UP =0x4800, /* upward arrow */
K_LEFT =0x4b00,
K_DOWN =00,
K_RIGHT =0x4d00,
K_SPACE =0x3920,
K_P =0x1970
} Block;
/* game's global info */
int FrameTime= 1300;
int CellSize= 18;
int BoardLeft= 30;
int BoardTop= 30;
/* next block grid */
int NBBoardLeft= 300;
int NBBoardTop= 30;
int y; /* block position cy [-4,BoardHeight-1] */
char color; /* block color */
char size; /* block max size in width or height */
char name; /* block name (the block's shape) */
#include <string.h>
#include <stdlib.h>

俄罗斯方块最简单代码

俄罗斯方块最简单代码

俄罗斯方块最简单代码俄罗斯方块游戏一直是老少皆宜的休闲游戏之一,它不仅富有挑战性,而且还能让人们在消磨时间的同时,放松身心,享受游戏的快乐。

在这篇文章中,我们将介绍俄罗斯方块最简单的代码,在这里让大家一窥游戏编程的神秘面纱。

1. 游戏规则俄罗斯方块的游戏规则非常简单,玩家需要通过移动俄罗斯方块的形状,让它们在屏幕底部的平台上堆叠起来。

当一整行方块被填满时,该行将被清除并给玩家带来积分。

如果游戏区域被方块堆满,则游戏结束。

2. 编写代码俄罗斯方块的代码可以使用各种编程语言实现,本文将使用简单易用的Python进行演示。

代码实现需要安装Python的pygame模块,因此您需要先安装它。

以下是代码实现的主要部分:```pythonimport pygame, sysdef run_game():pygame.init()game_width, game_height = 300, 600screen = pygame.display.set_mode((game_width,game_height))pygame.display.set_caption("Tetris")while True:for event in pygame.event.get():if event.type == pygame.QUIT:sys.exit()screen.fill((0, 0, 0))# 在这里添加游戏逻辑pygame.display.update()run_game()```以上代码展示了一个空白屏幕,并在屏幕标题中添加了“Tetris”游戏标题。

接下来,我们需要添加游戏逻辑。

3. 添加游戏逻辑在上方的主循环中,我们可以添加游戏逻辑。

为了使游戏逻辑尽可能简单,我们将使用一个简单的方块模型来代表俄罗斯方块。

```pythonclass Block:def __init__(self, color, width, height):self.color = colorself.width = widthself.height = heightdef draw(self, x, y, screen):pygame.draw.rect(screen, self.color, (x, y,self.width, self.height))```以上代码定义了一个Block类,其中包含方块的颜色、宽度和高度信息,并实现了一个draw()方法,用于在屏幕上绘制方块。

简单俄罗斯方块程序代码

简单俄罗斯方块程序代码

简单俄罗斯方块程序代码俄罗斯方块是一款非常经典的游戏,它需要玩家通过操作方块来消除行,随着游戏的深入,难度越来越大。

我们可以用Python语言来编写俄罗斯方块程序,它可以让我们体验到这个经典游戏的乐趣。

首先,我们需要导入相关的模块:```pythonimport pygameimport random```其中,pygame模块可以让我们创建图形化界面,random模块可以用于生成随机数,方便我们随机生成方块。

接下来,我们需要定义一些常量和变量:```python# 定义常量WIDTH = 480HEIGHT = 640CELL_SIZE = 30# 定义变量board = [[0] * 10 for i in range(20)]score = 0ticks = 0fall_speed = 60next_block = random.randint(0, 6)block_pos = (0, 3)current_block = None```这里定义了几个常量:游戏窗口的宽度和高度,单元格的大小。

同时,我们还需要一个二维数组board来表示游戏画面上的格子状态,score来表示当前得分,ticks表示已经落下的方块数量,fall_speed表示方块下落的速度,next_block表示下一个方块的类型,block_pos表示当前方块的位置,current_block则表示当前正在下落的方块。

接下来,我们需要定义一些函数来实现游戏的各种功能。

首先是绘制游戏画面的函数:```pythondef draw_game():screen.fill((0, 0, 0))# 绘制已经落下的方块for i in range(20):for j in range(10):if board[i][j] != 0:pygame.draw.rect(screen, (255, 255, 255),(j * CELL_SIZE, i * CELL_SIZE, CELL_SIZE, CELL_SIZE))# 绘制正在下落的方块if current_block:for i in range(4):for j in range(4):if current_block[i][j] != 0:pygame.draw.rect(screen, (255, 255, 255),((block_pos[1] + j) * CELL_SIZE, (block_pos[0] + i) * CELL_SIZE, CELL_SIZE, CELL_SIZE))# 绘制下一个方块draw_next_block()# 绘制得分font = pygame.font.SysFont('SimHei', 20)text = font.render('得分:%d' % score, True, (255, 255, 255))screen.blit(text, (10, 10))pygame.display.flip()```这个函数会首先清空画面,然后遍历board数组,绘制已经落下的方块。

俄罗斯方块完整源代码

俄罗斯方块完整源代码

//不多说,直接可以拷贝下面的东西,就可以运行。

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){}}}}。

俄罗斯方块ABAP代码

俄罗斯方块ABAP代码
* shift-f6 pf26 down
*------------------------------------------------------------*
* 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,

python实现简单俄罗斯方块游戏

python实现简单俄罗斯方块游戏

python实现简单俄罗斯⽅块游戏本⽂实例为⼤家分享了python实现简单俄罗斯⽅块游戏的具体代码,供⼤家参考,具体内容如下import pygame,sys,random,timeall_block = [[[0,0],[0,-1],[0,1],[0,2]],[[0,0],[0,1],[1,1],[1,0]],[[0,0],[0,-1],[-1,0],[-1,1]],[[0,0],[0,1],[-1,-1],[-1,0]],[[0,0],[0,1],[1,0],[0,-1]],[[0,0],[1,0],[-1,0],[1,-1]],[[0,0],[1,0],[-1,0],[1,1]]]background = [[0 for column in range(0,10)] for row in range(0,22)]background[0] = [1 for column in range(0,10)]select_block = list(random.choice(all_block))block_initial_position = [21,5]times = 0score = [0]gameover = []press = Falsepygame.init()screen = pygame.display.set_mode((250,500))title = pygame.display.set_caption("俄罗斯⽅块")#下落、位置、数组检测、得分、屏幕信息def block_move_down():y_drop=block_initial_position[0]x_move=block_initial_position[1]y_drop-=1for row,column in select_block:row+=y_dropcolumn+=x_moveif background[row][column]==1:breakelse:block_initial_position.clear()block_initial_position.extend([y_drop,x_move])returny_drop,x_move=block_initial_positionfor row,column in select_block:background[y_drop+row][x_move+column]=1complete_row=[]for row in range(1,21):if 0 not in background[row]:complete_row.append(row)complete_row.sort(reverse=True)for row in complete_row:background.pop(row)background.append([0 for column in range(0,10)])score[0]+=len(complete_row)pygame.display.set_caption(str(score[0])+'分')select_block.clear()select_block.extend(list(random.choice(all_block)))block_initial_position.clear()block_initial_position.extend([20,5])y_drop,x_move=block_initial_positionfor row,column in select_block:row+=y_dropcolumn+=x_moveif background[row][column]:gameover.append(1)#⽅块设置、变化、背景改变def new_draw():y_drop,x_move=block_initial_positionfor row,column in select_block:row+=y_dropcolumn+=x_movepygame.draw.rect(screen,(255,165,0),(column*25,500-row*25,23,23))for row in range(0,20):for column in range(0,10):bottom_block=background[row][column]if bottom_block:pygame.draw.rect(screen,(0,0,255),(column*25,500-row*25,23,23)) #⽅块的移动,防⽌出界,碰撞def move_left_right(n):y_drop,x_move=block_initial_positionx_move+=nfor row,column in select_block:row+=y_dropcolumn+=x_moveif column<0 or column>9 or background[row][column]:breakelse:block_initial_position.clear()block_initial_position.extend([y_drop,x_move])#旋转,位置都进⾏变化def rotate():y_drop,x_move=block_initial_positionrotating_position=[(-column,row)for row,column in select_block]for row,column in rotating_position:row+=y_dropcolumn+=x_moveif column<0 or column>9 or background[row][column]:breakelse:select_block.clear()select_block.extend(rotating_position)while True:screen.fill((255,255,255))for event in pygame.event.get():if event.type==pygame.QUIT:sys.exit()elif event.type==pygame.KEYDOWN and event.key==pygame.K_LEFT: move_left_right(-1)elif event.type==pygame.KEYDOWN and event.key==pygame.K_RIGHT: move_left_right(1)elif event.type==pygame.KEYDOWN and event.key==pygame.K_UP:rotate()elif event.type==pygame.KEYDOWN and event.key==pygame.K_DOWN: press=Trueelif event.type==pygame.KEYUP and event.key==pygame.K_DOWN:press=Falseif press:times+=10if times>=50:block_move_down()times=0else:times+=1if gameover:sys.exit()new_draw()pygame.time.Clock().tick(200)pygame.display.flip()效果:以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

俄罗斯方块游戏编程

俄罗斯方块游戏编程

俄罗斯方块游戏编程俄罗斯方块是一款非常经典且富有挑战性的游戏,它起源于俄罗斯,现已风靡全球。

这款游戏的编程实现涉及到许多关键的算法和技术,下面将为大家介绍一下俄罗斯方块游戏的编程过程。

一、游戏的整体结构俄罗斯方块游戏的编程可以分为前端和后端两个部分。

前端是指游戏的界面和用户交互逻辑,后端则负责游戏的核心算法和各种游戏逻辑的实现。

在前端部分,需要实现游戏界面的绘制和刷新,包括游戏区域的绘制、方块的绘制和下落效果、得分的实时更新等。

同时,还需要监听玩家的键盘操作,控制方块的移动、旋转和下落。

前端的编程通常使用图形库或者游戏引擎进行实现,比如常用的Python图形库Pygame。

在后端部分,核心算法是方块的下落和碰撞检测。

方块的下落是整个游戏的核心,需要考虑到方块的速度、位置和边界等因素。

碰撞检测是指判断方块是否与其他方块或者游戏区域的边界发生碰撞,如果发生碰撞,则需要停止方块的下落,并进行相关的处理,比如消除已满的行、生成新方块等。

此外,游戏还需要实现游戏开始、暂停、结束等功能,以及相应的状态管理和逻辑判断。

二、方块的表示和操作在俄罗斯方块游戏的编程中,方块是整个游戏的基本组成单元。

方块通常使用二维数组来表示,数组中的每个元素代表方块的一个单元格。

通过对方块数组的操作,可以实现方块的移动、旋转等效果。

方块的移动可以通过改变方块数组中元素的位置来实现。

比如向左移动方块,只需要将方块数组中每个元素的列索引减一;向右移动方块,则将列索引加一。

类似地,对于方块的旋转,可以通过改变方块数组中元素的行列索引来实现。

需要注意的是,在改变方块的位置和形状时,要进行边界检测,以防止方块超出游戏区域或者与其他方块发生重叠。

三、碰撞检测和处理在俄罗斯方块游戏中,碰撞检测是一个非常关键的环节。

碰撞检测的主要目的是判断当前的方块是否与其他方块或者游戏区域的边界发生碰撞,从而决定方块是否需要停止下落,并进行相应的处理。

对于方块与其他方块的碰撞检测,可以通过比较方块数组和游戏区域数组中相应位置的元素来实现。

python实现简单的俄罗斯方块

python实现简单的俄罗斯方块

python实现简单的俄罗斯⽅块本⽂实例为⼤家分享了python实现简单的俄罗斯⽅块的具体代码,供⼤家参考,具体内容如下1. 案例介绍俄罗斯⽅块是由 4 个⼩⽅块组成不同形状的板块,随机从屏幕上⽅落下,按⽅向键调整板块的位置和⽅向,在底部拼出完整的⼀⾏或⼏⾏。

这些完整的横条会消失,给新落下来的板块腾出空间,并获得分数奖励。

没有被消除掉的⽅块不断堆积,⼀旦堆到顶端,便告输,游戏结束。

本例难度为⾼级,适合具有 Python 进阶和 Pygame 编程技巧的⽤户学习。

2. 设计要点边框――由 15*25 个空格组成,⽅块就落在这⾥⾯。

盒⼦――组成⽅块的其中⼩⽅块,是组成⽅块的基本单元。

⽅块――从边框顶掉下的东西,游戏者可以翻转和改变位置。

每个⽅块由 4 个盒⼦组成。

形状――不同类型的⽅块。

这⾥形状的名字被叫做 T, S, Z ,J, L, I , O。

如下图所⽰:模版――⽤⼀个列表存放形状被翻转后的所有可能样式。

全部存放在变量⾥,变量名字如 S or J。

着陆――当⼀个⽅块到达边框的底部或接触到在其他的盒⼦话,就说这个⽅块着陆了。

那样的话,另⼀个⽅块就会开始下落。

3. ⽰例效果4. ⽰例源码import pygameimport randomimport ospygame.init()GRID_WIDTH = 20GRID_NUM_WIDTH = 15GRID_NUM_HEIGHT = 25WIDTH, HEIGHT = GRID_WIDTH * GRID_NUM_WIDTH, GRID_WIDTH * GRID_NUM_HEIGHTSIDE_WIDTH = 200SCREEN_WIDTH = WIDTH + SIDE_WIDTHWHITE = (0xff, 0xff, 0xff)BLACK = (0, 0, 0)LINE_COLOR = (0x33, 0x33, 0x33)CUBE_COLORS = [(0xcc, 0x99, 0x99), (0xff, 0xff, 0x99), (0x66, 0x66, 0x99),(0x99, 0x00, 0x66), (0xff, 0xcc, 0x00), (0xcc, 0x00, 0x33),(0xff, 0x00, 0x33), (0x00, 0x66, 0x99), (0xff, 0xff, 0x33),(0x99, 0x00, 0x33), (0xcc, 0xff, 0x66), (0xff, 0x99, 0x00)]screen = pygame.display.set_mode((SCREEN_WIDTH, HEIGHT))pygame.display.set_caption("俄罗斯⽅块")clock = pygame.time.Clock()FPS = 30score = 0level = 1screen_color_matrix = [[None] * GRID_NUM_WIDTH for i in range(GRID_NUM_HEIGHT)]# 设置游戏的根⽬录为当前⽂件夹base_folder = os.path.dirname(__file__)def show_text(surf, text, size, x, y, color=WHITE):font_name = os.path.join(base_folder, 'font/font.ttc')font = pygame.font.Font(font_name, size)text_surface = font.render(text, True, color)text_rect = text_surface.get_rect()text_rect.midtop = (x, y)surf.blit(text_surface, text_rect)class CubeShape(object):SHAPES = ['I', 'J', 'L', 'O', 'S', 'T', 'Z']I = [[(0, -1), (0, 0), (0, 1), (0, 2)],[(-1, 0), (0, 0), (1, 0), (2, 0)]]J = [[(-2, 0), (-1, 0), (0, 0), (0, -1)],[(-1, 0), (0, 0), (0, 1), (0, 2)],[(0, 1), (0, 0), (1, 0), (2, 0)],[(0, -2), (0, -1), (0, 0), (1, 0)]]L = [[(-2, 0), (-1, 0), (0, 0), (0, 1)],[(1, 0), (0, 0), (0, 1), (0, 2)],[(0, -1), (0, 0), (1, 0), (2, 0)],[(0, -2), (0, -1), (0, 0), (-1, 0)]]O = [[(0, 0), (0, 1), (1, 0), (1, 1)]]S = [[(-1, 0), (0, 0), (0, 1), (1, 1)],[(1, -1), (1, 0), (0, 0), (0, 1)]]T = [[(0, -1), (0, 0), (0, 1), (-1, 0)],[(-1, 0), (0, 0), (1, 0), (0, 1)],[(0, -1), (0, 0), (0, 1), (1, 0)],[(-1, 0), (0, 0), (1, 0), (0, -1)]]Z = [[(0, -1), (0, 0), (1, 0), (1, 1)],[(-1, 0), (0, 0), (0, -1), (1, -1)]]SHAPES_WITH_DIR = {'I': I, 'J': J, 'L': L, 'O': O, 'S': S, 'T': T, 'Z': Z}def __init__(self):self.shape = self.SHAPES[random.randint(0, len(self.SHAPES) - 1)]# ⾻牌所在的⾏列self.center = (2, GRID_NUM_WIDTH // 2)self.dir = random.randint(0, len(self.SHAPES_WITH_DIR[self.shape]) - 1) self.color = CUBE_COLORS[random.randint(0, len(CUBE_COLORS) - 1)] def get_all_gridpos(self, center=None):curr_shape = self.SHAPES_WITH_DIR[self.shape][self.dir]if center is None:center = [self.center[0], self.center[1]]return [(cube[0] + center[0], cube[1] + center[1])for cube in curr_shape]def conflict(self, center):for cube in self.get_all_gridpos(center):# 超出屏幕之外,说明不合法if cube[0] < 0 or cube[1] < 0 or cube[0] >= GRID_NUM_HEIGHT or \ cube[1] >= GRID_NUM_WIDTH:return True# 不为None,说明之前已经有⼩⽅块存在了,也不合法if screen_color_matrix[cube[0]][cube[1]] is not None:return Truereturn Falsedef rotate(self):new_dir = self.dir + 1new_dir %= len(self.SHAPES_WITH_DIR[self.shape])old_dir = self.dirself.dir = new_dirif self.conflict(self.center):self.dir = old_dirreturn Falsedef down(self):# import pdb; pdb.set_trace()center = (self.center[0] + 1, self.center[1])if self.conflict(center):return Falseself.center = centerreturn Truedef left(self):center = (self.center[0], self.center[1] - 1)if self.conflict(center):return Falseself.center = centerreturn Truedef right(self):center = (self.center[0], self.center[1] + 1)if self.conflict(center):return Falseself.center = centerreturn Truedef draw(self):for cube in self.get_all_gridpos():pygame.draw.rect(screen, self.color,(cube[1] * GRID_WIDTH, cube[0] * GRID_WIDTH,GRID_WIDTH, GRID_WIDTH))pygame.draw.rect(screen, WHITE,(cube[1] * GRID_WIDTH, cube[0] * GRID_WIDTH,GRID_WIDTH, GRID_WIDTH),1)def draw_grids():for i in range(GRID_NUM_WIDTH):pygame.draw.line(screen, LINE_COLOR,(i * GRID_WIDTH, 0), (i * GRID_WIDTH, HEIGHT))for i in range(GRID_NUM_HEIGHT):pygame.draw.line(screen, LINE_COLOR,(0, i * GRID_WIDTH), (WIDTH, i * GRID_WIDTH))pygame.draw.line(screen, WHITE,(GRID_WIDTH * GRID_NUM_WIDTH, 0),(GRID_WIDTH * GRID_NUM_WIDTH, GRID_WIDTH * GRID_NUM_HEIGHT)) def draw_matrix():for i, row in zip(range(GRID_NUM_HEIGHT), screen_color_matrix):for j, color in zip(range(GRID_NUM_WIDTH), row):if color is not None:pygame.draw.rect(screen, color,(j * GRID_WIDTH, i * GRID_WIDTH,GRID_WIDTH, GRID_WIDTH))pygame.draw.rect(screen, WHITE,(j * GRID_WIDTH, i * GRID_WIDTH,GRID_WIDTH, GRID_WIDTH), 2)def draw_score():show_text(screen, u'得分:{}'.format(score), 20, WIDTH + SIDE_WIDTH // 2, 100)def remove_full_line():global screen_color_matrixglobal scoreglobal levelnew_matrix = [[None] * GRID_NUM_WIDTH for i in range(GRID_NUM_HEIGHT)]index = GRID_NUM_HEIGHT - 1n_full_line = 0for i in range(GRID_NUM_HEIGHT - 1, -1, -1):is_full = Truefor j in range(GRID_NUM_WIDTH):if screen_color_matrix[i][j] is None:is_full = Falsecontinueif not is_full:new_matrix[index] = screen_color_matrix[i]index -= 1else:n_full_line += 1score += n_full_linelevel = score // 20 + 1screen_color_matrix = new_matrixdef show_welcome(screen):show_text(screen, u'俄罗斯⽅块', 30, WIDTH / 2, HEIGHT / 2)show_text(screen, u'按任意键开始游戏', 20, WIDTH / 2, HEIGHT / 2 + 50)running = Truegameover = Truecounter = 0live_cube = Nonewhile running:clock.tick(FPS)for event in pygame.event.get():if event.type == pygame.QUIT:running = Falseelif event.type == pygame.KEYDOWN:if gameover:gameover = Falselive_cube = CubeShape()breakif event.key == pygame.K_LEFT:live_cube.left()elif event.key == pygame.K_RIGHT:live_cube.right()elif event.key == pygame.K_DOWN:live_cube.down()elif event.key == pygame.K_UP:live_cube.rotate()elif event.key == pygame.K_SPACE:while live_cube.down() == True:passremove_full_line()# level 是为了⽅便游戏的难度,level 越⾼ FPS // level 的值越⼩# 这样屏幕刷新的就越快,难度就越⼤if gameover is False and counter % (FPS // level) == 0:# down 表⽰下移⾻牌,返回False表⽰下移不成功,可能超过了屏幕或者和之前固定的# ⼩⽅块冲突了if live_cube.down() == False:for cube in live_cube.get_all_gridpos():screen_color_matrix[cube[0]][cube[1]] = live_cube.colorlive_cube = CubeShape()if live_cube.conflict(live_cube.center):gameover = Truescore = 0live_cube = Nonescreen_color_matrix = [[None] * GRID_NUM_WIDTH for i in range(GRID_NUM_HEIGHT)] # 消除满⾏remove_full_line()counter += 1# 更新屏幕screen.fill(BLACK)draw_grids()draw_matrix()draw_score()if live_cube is not None:live_cube.draw()if gameover:show_welcome(screen)pygame.display.update()以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

用Shell编写的俄罗斯方块小游戏_Linux

用Shell编写的俄罗斯方块小游戏_Linux

#!/bin/bash#颜色定义cRed=1cGreen=2cYellow=3cBlue=4cFuchsia=5cCyan=6cWhite=7colorTable=($cRed $cGreen $cYellow $cBlue $cFuchsia $cCyan $cWhite)#位置和大小iLeft=3iTop=2((iTrayLeft = iLeft + 2))((iTrayTop = iTop + 1))((iTrayWidth = 10))((iTrayHeight = 15))#颜色设置cBorder=$cGreencScore=$cFuchsiacScoreV alue=$cCyan#控制信号#改游戏使用两个进程,一个用于接收输入,一个用于游戏流程和显示界面; #当前者接收到上下左右等按键时,通过向后者发送signal的方式通知后者。

sigRotate=25sigLeft=26sigRight=27sigDown=28sigAllDown=29sigExit=30#七种不同的方块的定义#通过旋转,每种方块的显示的样式可能有几种box0=(0 0 0 1 1 0 1 1)box1=(0 2 1 2 2 2 3 2 1 0 1 1 1 2 1 3)box2=(0 0 0 1 1 1 1 2 0 1 1 0 1 1 2 0)box3=(0 1 0 2 1 0 1 1 0 0 1 0 1 1 2 1)box4=(0 1 0 2 1 1 2 1 1 0 1 1 1 2 2 2 0 1 1 1 2 0 2 1 0 0 1 0 1 1 1 2)box5=(0 1 1 1 2 1 2 2 1 0 1 1 1 2 2 0 0 0 0 1 1 1 2 1 0 2 1 0 1 1 1 2)box6=(0 1 1 1 1 2 2 1 1 0 1 1 1 2 2 1 0 1 1 0 1 1 2 1 0 1 1 0 1 1 1 2)#所有其中方块的定义都放到box变量中box=(${box0[@]} ${box1[@]} ${box2[@]} ${box3[@]} ${box4[@]} ${box5[@]} ${box6[@]})#各种方块旋转后可能的样式数目countBox=(1 2 2 2 4 4 4)#各种方块再box数组中的偏移offsetBox=(0 1 3 5 7 11 15)#每提高一个速度级需要积累的分数iScoreEachLevel=50 #be greater than 7#运行时数据sig=0 #接收到的signaliScore=0 #总分iLevel=0 #速度级boxNew=() #新下落的方块的位置定义cBoxNew=0 #新下落的方块的颜色iBoxNewType=0 #新下落的方块的种类iBoxNewRotate=0 #新下落的方块的旋转角度boxCur=() #当前方块的位置定义cBoxCur=0 #当前方块的颜色iBoxCurType=0 #当前方块的种类iBoxCurRotate=0 #当前方块的旋转角度boxCurX=-1 #当前方块的x坐标位置boxCurY=-1 #当前方块的y坐标位置iMap=() #背景方块图表#初始化所有背景方块为-1, 表示没有方块for ((i = 0; i < iTrayHeight * iTrayWidth; i++)); do iMap[$i]=-1; done#接收输入的进程的主函数function RunAsKeyReceiver(){local pidDisplayer key aKey sig cESC sTTYpidDisplayer=$1aKey=(0 0 0)cESC=`echo -ne "\33"`cSpace=`echo -ne "\40"`#保存终端属性。

按键精灵教程之俄罗斯方块

按键精灵教程之俄罗斯方块

前言:喵~你们相信按键精灵除了能做游戏辅助脚本外,还能做一个游戏玩玩吗?这是真的吗?小猫告诉你,是真的,编程是无所不能的,只要你敢想,就能实现!!!游戏下载地址:喵~用按键精灵做的<俄罗斯方块>游戏~[更新至1.11.0701]技术:1.多线程2.窗口句柄工具:按键精灵8361的窗口插件mp9999ddd的多线程互斥锁插件俄罗斯方块百度感谢以上两位高人提供的插件喵。

游戏背景图片:思路:要写一个游戏,必须要对游戏有一定的了解,而不是简简单单的知道怎么玩。

现在小猫要写的是俄罗斯方块,那么小猫需要知道以下几个数据:“游戏的边框长短,各个方块的具体形状,每次变形后的形状,得分的算法,游戏的规则。

”那怎么获得这些数据呢?对,活用百度谷歌,具体内容看上面的俄罗斯方块百科,已经写的很清楚了,游戏是10x20大小的,方块有S、Z、L、J、I、O、T这7种形状,得分的大致算法。

OK,游戏的一些大致数据已经收集好了,现在要利用这些数据了。

小猫刚开始的时候,是想用91的写屏插件,通过清屏和写屏两种功能完成游戏的,后来才发现,这个思路的代码和算法太复杂,于是果断放弃,转为使用361的窗口插件,通过创建一个游戏背景区域和多个方块(按钮),然后使用移动窗口和关闭窗口实现方块的移动和消除,而判断方法则是采用判断上下左右句柄得到。

正文:首先,我们要创建一个游戏区域,游戏原本是边框10x20,方块1x1的,我们将其放大30倍,即变为边框300x600,方块30x30,我们还要计算好游戏区域的左上角坐标,在这里,小猫电脑分辨率是1280x800的,小猫为了游戏区域在屏幕中间,故设置游戏区域的左上角坐标为489,99。

接着,大家注意找下361窗口插件中的“CreateCustomRgn 创建不规则区域”功能,简单的说,这个就是放置一张图片大小的窗口,只不过他会将指定颜色挖空。

在这里,我们使用上面那张300x600的背景图片,创建这个游戏区域即可。

《俄罗斯方块》程序编写超详细解释

《俄罗斯方块》程序编写超详细解释

《俄罗斯方块》程序编写超详细解释Tc2.0 编写俄罗斯方块游戏很多编程爱好者都编写过俄罗斯方块的游戏程序。

很久以前,我用Tc2.0也做过一个;最近有好些朋友看见我以前的俄罗斯方块的程序后,问我是怎么做的。

我一直想把这个程序的整个过程写一份详细的东西,与各位编程爱好者分享,一直没空。

正好现在放假了,而且离回家还有几天。

于是我就把这个程序重新写了一遍,尽量使程序的结构比较清晰好懂一些。

同时写了下面的这份东西。

俄罗斯方块游戏的程序中用到了一些方法。

为了比较容易理解这些方法,我在讲述的同时写了些专门针对这些方法的示例程序。

这些示例程序力求短小,目的是用最小的代码能够清楚的示例所用的方法。

这些示例程序都经过tc2.0测试。

最后还附了完整的俄罗斯方块游戏的源代码,和最终的可执行程序。

如果你看了这份东东,有什么意见和想法,请发电子邮件告诉我。

我将会继续更新这分东东,最新的版本可以在我的个人主页上下载。

下面的问题是有关俄罗斯方块程序的,其中有些是朋友问我的,有些是我认为可能会被问到的。

我尽量按问题从易到难排列这些问题。

关于俄罗斯方块程序的一些问题:******************************************************Tc2.0中怎么样设置图形显示?Tc2.0中常用图形函数的用法?怎样获取鍵盘输入?怎样控制方块的移动?怎样控制时间间隔(用于游戏中控制形状的下落)?游戏中的各种形状及整个游戏空间怎么用数据表示?游戏中怎么判断左右及向下移动的可能性?游戏中怎么判断某一形状旋转的可能性?按向下方向键时加速某一形状下落速度的处理?怎么判断某一形状已经到底?怎么判断某一已经被填满?怎么消去已经被填满的一行?怎么消去某一形状落到底后能够消去的所有的行?(如长条最多可以消去四行)怎样修改游戏板的状态?怎样统计分数?怎样处理升级后的加速问题?怎样判断游戏结束?关于计分板设计的问题。

关于“下一个”形状取法的问题。

俄罗斯方块游戏原代码

俄罗斯方块游戏原代码

#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键,退出游戏 */}}。

C语言实现俄罗斯方块小游戏

C语言实现俄罗斯方块小游戏

C语⾔实现俄罗斯⽅块⼩游戏C语⾔实现俄罗斯⽅块⼩游戏的制作代码,具体内容如下#include <stdio.h>#include <stdlib.h>#include <unistd.h>#define TTY_PATH "/dev/tty"#define STTY_ON "stty raw -echo -F"#define STTY_OFF "stty -raw echo -F"int map[21][14];char direct;int node[7][4][16]={{{0,0,0,0,1,1,1,1,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,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0},{0,1,0,0,0,1,0,0,0,1,0,0,0,1,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}},{{0,1,0,0,1,1,1,0,0,0,0,0,0,0,0,0},//3边加⼀中点{0,1,0,0,0,1,1,0,0,1,0,0,0,0,0,0},{0,0,0,0,1,1,1,0,0,1,0,0,0,0,0,0},{0,1,0,0,1,1,0,0,0,1,0,0,0,0,0,0}},{{0,1,1,0,0,1,0,0,0,1,0,0,0,0,0,0},//右锄头型{0,0,0,0,1,1,1,0,0,0,1,0,0,0,0,0},{0,1,0,0,0,1,0,0,1,1,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,0,1,0,0,0,1,0,0,0,0,0,0},//左锄头型{0,0,1,0,1,1,1,0,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,0,0,0,1,1,1,0,1,0,0,0,0,0,0,0}},{{0,1,0,0,0,1,1,0,0,0,1,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,0,1,1,0,0,0,1,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}}};typedef struct block{int x;int y;int blockType;int blockDirect;}Block;Block bl;void init_map()//初始化边框{int i,j;for(i=0; i<21; i++)for(j=0; j<14; j++){if(j==0 || j==13)map[i][j] = 200;else if(i==20)map[i][j] = 201;elsemap[i][j] = 0;}}void new_block()//⽣成随机的俄罗斯⽅块{int blockType = rand()%7;int blockDirect = rand()%4;int x = 1;int y = 5;bl.x = x;bl.y = y;bl.blockType = blockType;bl.blockDirect = blockDirect;}void input()//将移动后的俄罗斯⽅块,导⼊地图中作标记{int i, j;for(i=0; i<4; i++)for(j=0; j<4; j++)if(node[bl.blockType][bl.blockDirect][i*4+j]==1){map[bl.x+i][bl.y+j] = 1;}}void output()//移动时,将之前俄罗斯⽅块在地图信息清空。

按键精灵教程之俄罗斯方块

按键精灵教程之俄罗斯方块

按键精灵教程之俄罗斯方块按键精灵是一种自动化工具,可用于自动执行各种重复性任务。

在本教程中,我们将使用按键精灵来制作一个简单的俄罗斯方块游戏。

首先,让我们来了解一下俄罗斯方块的规则。

俄罗斯方块是一款经典的益智游戏,玩家需要将不同形状的方块逐行堆叠在一起,使得每一行的方块都被填满。

当一行被填满时,它将消失并腾出新的空间。

游戏结束的条件是当方块堆满整个游戏区域时。

接下来,我们将使用按键精灵创建一个简化版的俄罗斯方块游戏。

我们将使用鼠标点击来控制方块的移动和旋转,以及键盘触发来加快方块下降的速度。

首先,我们将创建一个方块的类。

每个方块都由四个正方形组成,可以进行旋转,并且在游戏区域中进行移动。

```class Block:def __init__(self, x, y):self.x = xself.y = ydef move_left(self):self.x -= 1def move_right(self):self.x += 1def move_down(self):self.y += 1def rotate(self):# to be implemented```接下来,我们将创建一个游戏区域的类。

游戏区域由一个二维数组表示,每个方块的状态都可以在其中更新。

```class GameBoard:def __init__(self, width, height):self.width = widthself.height = heightself.board = [[0] * width] * heightdef update(self, block):# to be implemented```在游戏区域的update方法中,我们需要将当前方块的状态更新到游戏区域中。

当方块堆满一行时,需要将该行删除并向下移动所有上方的方块。

接下来,我们将使用按键精灵来控制方块的移动和旋转。

首先,我们需要定义鼠标和键盘事件触发时的回调函数。

俄罗斯方块代码

俄罗斯方块代码
int rotate();
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,

linux课程设计俄罗斯方块

linux课程设计俄罗斯方块

linux课程设计俄罗斯方块一、教学目标本课程的教学目标是使学生掌握Linux操作系统的基本使用方法,通过学习俄罗斯方块游戏的设计与实现,培养学生运用Linux系统编程的能力。

具体分为以下三个维度:1.知识目标:使学生了解Linux操作系统的基本概念、命令和操作,理解Linux系统编程的基本原理和方法。

2.技能目标:培养学生能够使用Linux操作系统进行日常工作和学习,能够运用Linux系统编程实现简单的游戏程序。

3.情感态度价值观目标:培养学生对计算机科学的兴趣,提高学生独立思考和解决问题的能力,培养学生的团队协作精神和创新精神。

二、教学内容本课程的教学内容主要包括Linux操作系统的基本概念、命令和操作,以及Linux系统编程的基本原理和方法。

具体安排如下:1.第一部分:Linux操作系统的基本概念和命令。

包括Linux操作系统的发展历程、基本架构,以及常用的命令和操作。

2.第二部分:Linux系统编程的基本原理和方法。

包括进程管理、线程管理、文件操作和网络编程等内容。

3.第三部分:俄罗斯方块游戏的设计与实现。

通过分析俄罗斯方块游戏的算法和逻辑,引导学生运用Linux系统编程实现游戏程序。

三、教学方法为了达到本课程的教学目标,将采用以下教学方法:1.讲授法:用于讲解Linux操作系统的基本概念、命令和操作,以及Linux系统编程的基本原理和方法。

2.案例分析法:通过分析俄罗斯方块游戏的算法和逻辑,引导学生运用Linux系统编程实现游戏程序。

3.实验法:安排实验室实践环节,让学生亲自动手操作Linux操作系统,实践所学知识和技能。

4.讨论法:学生进行小组讨论,分享学习心得和经验,提高学生的团队协作能力和沟通能力。

四、教学资源为了支持本课程的教学内容和教学方法的实施,将准备以下教学资源:1.教材:选用《Linux操作系统原理与应用》等教材,为学生提供理论知识的学习材料。

2.参考书:推荐《Linux命令行与shell脚本编程大全》等参考书,供学生深入学习参考。

C语言小游戏源代《俄罗斯方块》

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. 俄罗斯方块```javascript// 俄罗斯方块// 定义一个游戏类class TetrisGame {constructor() {// 初始化游戏参数this.width = 10;this.height = 20;this.score = 0;this.level = 1;this.lines = 0;this.gameOver = false;this.gameBoard = [];this.currentBlock = null;this.nextBlock = null;this.init();}// 初始化游戏init() {// 初始化游戏板for (let i = 0; i < this.height; i++) {this.gameBoard[i] = new Array(this.width).fill(0); }// 生成下一个方块this.nextBlock = this.generateBlock();// 生成当前方块this.currentBlock = this.generateBlock();}// 生成方块generateBlock() {// 生成随机数,用来表示方块的类型let type = Math.floor(Math.random() * 7); let block = null;switch (type) {case 0:block = new IBlock();break;case 1:block = new JBlock();break;case 2:block = new LBlock();break;case 3:block = new OBlock();break;case 4:block = new SBlock();break;case 5:block = new TBlock();break;case 6:block = new ZBlock();break;}return block;}// 更新游戏update() {// 更新游戏板this.updateGameBoard();// 检测游戏是否结束this.checkGameOver();// 更新分数this.updateScore();// 更新关卡this.updateLevel();}// 更新游戏板updateGameBoard() {// 清除游戏板this.gameBoard.forEach(row => row.fill(0));// 将当前方块的位置更新到游戏板this.currentBlock.block.forEach((row, y) => {row.forEach((value, x) => {if (value !== 0) {this.gameBoard[y + this.currentBlock.y][x + this.currentBlock.x] = value;}});});}// 检测游戏是否结束checkGameOver() {// 如果当前方块的位置已经超出游戏板,则游戏结束if (this.currentBlock.y < 0) {this.gameOver = true;}}// 更新分数updateScore() {// 根据消除的行数更新分数this.score += this.lines * 10;}// 更新关卡updateLevel() {// 根据消除的行数更新关。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

#!/bin/bash# Tetris Game# 10.21.2003 xhchen<[email]xhchen@[/email]>#APP declarationAPP_NAME="${0##*[\\/]}"APP_VERSION="1.0"#颜色定义cRed=1cGreen=2cYellow=3cBlue=4cFuchsia=5cCyan=6cWhite=7colorTable=($cRed $cGreen $cYellow $cBlue $cFuchsia $cCyan $cWhite)#位置和大小iLeft=3iTop=2((iTrayLeft = iLeft + 2))((iTrayTop = iTop + 1))((iTrayWidth = 10))((iTrayHeight = 15))#颜色设置cBorder=$cGreencScore=$cFuchsiacScoreValue=$cCyan#控制信号#改游戏使用两个进程,一个用于接收输入,一个用于游戏流程和显示界面;#当前者接收到上下左右等按键时,通过向后者发送signal的方式通知后者。

sigRotate=25sigLeft=26sigRight=27sigDown=28sigAllDown=29sigExit=30#七中不同的方块的定义#通过旋转,每种方块的显示的样式可能有几种box0=(0 0 0 1 1 0 1 1)box1=(0 2 1 2 2 2 3 2 1 0 1 1 1 2 1 3)box2=(0 0 0 1 1 1 1 2 0 1 1 0 1 1 2 0)box3=(0 1 0 2 1 0 1 1 0 0 1 0 1 1 2 1)box4=(0 1 0 2 1 1 2 1 1 0 1 1 1 2 2 2 0 1 1 1 2 0 2 1 0 0 1 0 1 1 1 2) box5=(0 1 1 1 2 1 2 2 1 0 1 1 1 2 2 0 0 0 0 1 1 1 2 1 0 2 1 0 1 1 1 2) box6=(0 1 1 1 1 2 2 1 1 0 1 1 1 2 2 1 0 1 1 0 1 1 2 1 0 1 1 0 1 1 1 2) #所有其中方块的定义都放到box变量中box=(${box0[@]} ${box1[@]} ${box2[@]} ${box3[@]} ${box4[@]} ${box5[@]} ${box6[@]})#各种方块旋转后可能的样式数目countBox=(1 2 2 2 4 4 4)#各种方块再box数组中的偏移offsetBox=(0 1 3 5 7 11 15)#每提高一个速度级需要积累的分数iScoreEachLevel=50 #be greater than 7#运行时数据sig=0 #接收到的signaliScore=0 #总分iLevel=0 #速度级boxNew=() #新下落的方块的位置定义cBoxNew=0 #新下落的方块的颜色iBoxNewType=0 #新下落的方块的种类iBoxNewRotate=0 #新下落的方块的旋转角度boxCur=() #当前方块的位置定义cBoxCur=0 #当前方块的颜色iBoxCurType=0 #当前方块的种类iBoxCurRotate=0 #当前方块的旋转角度boxCurX=-1 #当前方块的x坐标位置boxCurY=-1 #当前方块的y坐标位置iMap=() #背景方块图表#初始化所有背景方块为-1, 表示没有方块for ((i = 0; i < iTrayHeight * iTrayWidth; i++)); do iMap[$i]=-1; done#接收输入的进程的主函数function RunAsKeyReceiver(){local pidDisplayer key aKey sig cESC sTTYpidDisplayer=$1aKey=(0 0 0)cESC=`echo -ne "\033"`cSpace=`echo -ne "\040"`#保存终端属性。

在read -s读取终端键时,终端的属性会被暂时改变。

#如果在read -s时程序被不幸杀掉,可能会导致终端混乱,#需要在程序退出时恢复终端属性。

sTTY=`stty -g`#捕捉退出信号trap "MyExit;" INT TERMtrap "MyExitNoSub;" $sigExit#隐藏光标echo -ne "\033[?25l"while :do#读取输入。

注-s不回显,-n读到一个字符立即返回read -s -n 1 keyaKey[0]=${aKey[1]}aKey[1]=${aKey[2]}aKey[2]=$keysig=0#判断输入了何种键if [[ $key == $cESC && ${aKey[1]} == $cESC ]]then#ESC键MyExitelif [[ ${aKey[0]} == $cESC && ${aKey[1]} == "[" ]]thenif [[ $key == "A" ]]; then sig=$sigRotate #<向上键> elif [[ $key == "B" ]]; then sig=$sigDown #<向下键>elif [[ $key == "D" ]]; then sig=$sigLeft #<向左键> elif [[ $key == "C" ]]; then sig=$sigRight #<向右键>fielif [[ $key == "W" || $key == "w" ]]; then sig=$sigRotate #W, welif [[ $key == "S" || $key == "s" ]]; then sig=$sigDown #S, selif [[ $key == "A" || $key == "a" ]]; then sig=$sigLeft #A, aelif [[ $key == "D" || $key == "d" ]]; then sig=$sigRight #D, delif [[ "[$key]" == "[]" ]]; then sig=$sigAllDown #空格键 elif [[ $key == "Q" || $key == "q" ]] #Q, q thenMyExitfiif [[ $sig != 0 ]]then#向另一进程发送消息kill -$sig $pidDisplayerfidone}#退出前的恢复function MyExitNoSub(){local y#恢复终端属性stty $sTTY((y = iTop + iTrayHeight + 4))#显示光标echo -e "\033[?25h\033[${y};0H"exit}function MyExit(){#通知显示进程需要退出kill -$sigExit $pidDisplayerMyExitNoSub}#处理显示和游戏流程的主函数function RunAsDisplayer(){local sigThisInitDraw#挂载各种信号的处理函数trap "sig=$sigRotate;" $sigRotatetrap "sig=$sigLeft;" $sigLefttrap "sig=$sigRight;" $sigRighttrap "sig=$sigDown;" $sigDowntrap "sig=$sigAllDown;" $sigAllDowntrap "ShowExit;" $sigExitwhile :do#根据当前的速度级iLevel不同,设定相应的循环的次数for ((i = 0; i < 21 - iLevel; i++))dosleep 0.02sigThis=$sigsig=0#根据sig变量判断是否接受到相应的信号if ((sigThis == sigRotate)); then BoxRotate; #旋转 elif ((sigThis == sigLeft)); then BoxLeft; #左移一列elif ((sigThis == sigRight)); then BoxRight; #右移一列elif ((sigThis == sigDown)); then BoxDown; #下落一行elif ((sigThis == sigAllDown)); then BoxAllDown; #下落到底fidone#kill -$sigDown $$BoxDown #下落一行done}#BoxMove(y, x), 测试是否可以把移动中的方块移到(x, y)的位置, 返回0则可以, 1不可以function BoxMove(){local j i x y xTest yTestyTest=$1xTest=$2for ((j = 0; j < 8; j += 2))do((i = j + 1))((y = ${boxCur[$j]} + yTest))((x = ${boxCur[$i]} + xTest))if (( y < 0 || y >= iTrayHeight || x < 0 || x >= iTrayWidth)) then#撞到墙壁了return 1fiif ((${iMap[y * iTrayWidth + x]} != -1 ))then#撞到其他已经存在的方块了return 1fidonereturn 0;}#将当前移动中的方块放到背景方块中去,#并计算新的分数和速度级。

(即一次方块落到底部)function Box2Map(){local j i x y xp yp line#将当前移动中的方块放到背景方块中去for ((j = 0; j < 8; j += 2))do((y = ${boxCur[$j]} + boxCurY))((x = ${boxCur[$i]} + boxCurX))((i = y * iTrayWidth + x))iMap[$i]=$cBoxCurdone#消去可被消去的行line=0for ((j = 0; j < iTrayWidth * iTrayHeight; j += iTrayWidth)) dofor ((i = j + iTrayWidth - 1; i >= j; i--))doif ((${iMap[$i]} == -1)); then break; fidoneif ((i >= j)); then continue; fi((line++))for ((i = j - 1; i >= 0; i--))do((x = i + iTrayWidth))iMap[$x]=${iMap[$i]}donefor ((i = 0; i < iTrayWidth; i++))doiMap[$i]=-1donedoneif ((line == 0)); then return; fi#根据消去的行数line计算分数和速度级((x = iLeft + iTrayWidth * 2 + 7))((y = iTop + 11))((iScore += line * 2 - 1))#显示新的分数echo -ne"\033[1m\033[3${cScoreValue}m\033[${y};${x}H${iScore} "if ((iScore % iScoreEachLevel < line * 2 - 1))thenif ((iLevel < 20))then((iLevel++))((y = iTop + 14))#显示新的速度级echo -ne"\033[3${cScoreValue}m\033[${y};${x}H${iLevel} "fifiecho -ne "\033[0m"#重新显示背景方块for ((y = 0; y < iTrayHeight; y++))do((yp = y + iTrayTop + 1))((xp = iTrayLeft + 1))((i = y * iTrayWidth))echo -ne "\033[${yp};${xp}H"for ((x = 0; x < iTrayWidth; x++))do((j = i + x))if ((${iMap[$j]} == -1))echo -ne " "elseecho -ne"\033[1m\033[7m\033[3${iMap[$j]}m\033[4${iMap[$j]}m[]\033[0m"fidonedone}#下落一行function BoxDown(){local y s((y = boxCurY + 1)) #新的y坐标if BoxMove $y $boxCurX #测试是否可以下落一行thens="`DrawCurBox 0`" #将旧的方块抹去((boxCurY = y))s="$s`DrawCurBox 1`" #显示新的下落后方块echo -ne $selse#走到这儿, 如果不能下落了Box2Map #将当前移动中的方块贴到背景方块中 RandomBox #产生新的方块fi}#左移一列function BoxLeft(){local x s((x = boxCurX - 1))if BoxMove $boxCurY $xthens=`DrawCurBox 0`((boxCurX = x))s=$s`DrawCurBox 1`echo -ne $sfi}#右移一列function BoxRight(){local x s((x = boxCurX + 1))if BoxMove $boxCurY $xthens=`DrawCurBox 0`((boxCurX = x))s=$s`DrawCurBox 1`echo -ne $sfi}#下落到底function BoxAllDown(){local k j i x y iDown siDown=$iTrayHeight#计算一共需要下落多少行for ((j = 0; j < 8; j += 2))do((i = j + 1))((y = ${boxCur[$j]} + boxCurY))((x = ${boxCur[$i]} + boxCurX))for ((k = y + 1; k < iTrayHeight; k++))do((i = k * iTrayWidth + x))if (( ${iMap[$i]} != -1)); then break; fidone((k -= y + 1))if (( $iDown > $k )); then iDown=$k; fidones=`DrawCurBox 0` #将旧的方块抹去((boxCurY += iDown))s=$s`DrawCurBox 1` #显示新的下落后的方块echo -ne $sBox2Map #将当前移动中的方块贴到背景方块中RandomBox #产生新的方块}#旋转方块function BoxRotate(){local iCount iTestRotate boxTest j i siCount=${countBox[$iBoxCurType]} #当前的方块经旋转可以产生的样式的数目#计算旋转后的新的样式((iTestRotate = iBoxCurRotate + 1))if ((iTestRotate >= iCount))then((iTestRotate = 0))fi#更新到新的样式, 保存老的样式(但不显示)for ((j = 0, i = (${offsetBox[$iBoxCurType]} + $iTestRotate) * 8; j < 8; j++, i++))doboxTest[$j]=${boxCur[$j]}boxCur[$j]=${box[$i]}doneif BoxMove $boxCurY $boxCurX #测试旋转后是否有空间放的下then#抹去旧的方块for ((j = 0; j < 8; j++))doboxCur[$j]=${boxTest[$j]}dones=`DrawCurBox 0`#画上新的方块for ((j = 0, i = (${offsetBox[$iBoxCurType]} + $iTestRotate) * 8; j < 8; j++, i++))doboxCur[$j]=${box[$i]}dones=$s`DrawCurBox 1`echo -ne $siBoxCurRotate=$iTestRotateelse#不能旋转,还是继续使用老的样式for ((j = 0; j < 8; j++))doboxCur[$j]=${boxTest[$j]}donefi}#DrawCurBox(bDraw), 绘制当前移动中的方块, bDraw为1, 画上, bDraw为0, 抹去方块。

相关文档
最新文档