Home Web Front-end JS Tutorial Writing Tetris in native JavaScript_javascript skills

Writing Tetris in native JavaScript_javascript skills

May 16, 2016 pm 04:07 PM
javascript

First of all, thank you @jdkleo for your valuable suggestions!
To be honest, if you don’t scold me for playing Tetris, long live it. It’s not completely finished yet, it’s only 50% complete, and there are still a lot of bugs.
Functions that can be implemented:
1. Drop blocks
2. Randomly generate new blocks
3. Block movement.
There are still a lot of bugs at the moment. Since this is my first time writing such a "big" game with more than 1,000 lines of code, I'm asking for advice from experts. There are too many bugs.
Press START to start the game.
Please give me some suggestions. This is my first time writing a JS game.
I referred to other people's codes on the Internet, but I didn't copy them.
The code can be run directly without referencing JQUERY.
I hope the experts can give me some advice! ! ! ! Not very grateful! ! !

Ver 0.2 has been released (2014-12-26), the latest code:
Things revised this time:
1. The left and right sides can be moved.
2.Can rotate
3. A full row of blocks can be eliminated.

Code:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

530

531

532

533

534

535

536

537

538

539

540

541

542

543

544

545

546

547

548

549

550

551

552

553

554

555

556

557

558

559

560

561

562

563

564

565

566

567

568

569

570

571

572

573

574

575

576

577

578

579

580

581

582

583

584

585

586

587

588

589

590

591

592

593

594

595

596

597

598

599

600

601

602

603

604

605

606

607

608

609

610

611

612

613

614

615

616

617

618

619

620

621

622

623

624

625

626

627

628

629

630

631

632

633

634

635

636

637

638

639

640

641

642

643

644

645

646

647

648

649

650

651

652

653

654

655

656

657

658

659

660

661

662

663

664

665

666

667

668

669

670

671

672

673

674

675

676

677

678

679

680

681

682

683

684

685

686

687

688

689

690

691

692

693

694

695

696

697

698

699

700

701

702

703

704

705

706

707

708

709

710

711

712

713

714

715

716

717

718

719

720

721

722

723

724

725

726

727

728

729

730

731

732

733

734

735

736

737

738

739

740

741

742

743

744

745

746

747

748

749

750

751

752

753

754

755

756

757

758

759

760

761

762

763

764

765

766

767

768

769

770

771

772

773

774

775

776

777

778

779

780

781

782

783

784

785

786

787

788

789

790

791

792

793

794

795

796

797

798

799

800

801

802

803

804

805

806

807

808

809

810

811

812

813

814

815

816

817

818

819

820

821

822

823

824

825

826

827

828

829

830

831

832

833

834

835

836

837

838

839

840

841

842

843

844

845

846

847

848

849

850

851

852

853

854

855

856

857

858

859

860

861

862

863

864

865

866

867

868

869

870

871

872

873

874

875

876

877

878

879

880

881

882

883

884

885

886

887

888

889

890

891

892

893

894

895

896

897

898

899

900

901

902

903

904

905

906

907

908

909

910

911

912

913

914

915

916

917

918

919

920

921

922

923

924

925

926

927

928

929

930

931

932

933

934

935

936

937

938

939

940

941

942

943

944

945

946

947

948

949

950

951

952

953

954

955

956

957

958

959

960

961

962

963

964

965

966

967

968

969

970

971

972

973

974

975

976

977

978

979

980

981

982

983

984

985

986

987

988

989

990

991

992

993

994

995

996

997

998

999

1000

1001

1002

1003

1004

1005

1006

1007

1008

1009

1010

1011

1012

1013

1014

1015

1016

1017

1018

1019

1020

1021

1022

1023

1024

1025

1026

1027

1028

1029

1030

1031

1032

1033

1034

1035

1036

1037

1038

1039

1040

1041

1042

1043

1044

1045

1046

1047

1048

1049

1050

1051

1052

1053

1054

1055

1056

1057

1058

1059

1060

1061

1062

1063

1064

1065

1066

1067

1068

1069

1070

1071

1072

1073

1074

1075

1076

1077

1078

1079

1080

1081

1082

1083

1084

1085

1086

1087

1088

1089

1090

1091

1092

1093

1094

1095

1096

1097

1098

1099

1100

1101

1102

1103

1104

1105

1106

1107

1108

1109

1110

1111

1112

1113

1114

1115

1116

1117

1118

1119

1120

1121

1122

1123

1124

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>无标题文档</title>

  

<style type="text/css">

#test

{

  /*width:25px;*/

}

  

.t

{

width:10px;

height:10px;

border:1px solid black;

float:left;

    

}

  

body

{

  margin:0 auto;

  width:1000px;

  height:600px;

    

}

  

/*游戏相关*/

#startGame

{

    

}

  

#lines

{

    

}

  

#level

{

    

}

  

#time

{

    

}

  

/*俄罗斯方块实体类*/

#tetris-area

{

  width:auto;

  height:auto;

  background:blue;

}

  

/*JS生成的CLASS,俄罗斯方块实体*/

#tetris .block0,#tetris .block1, #tetris .block2, #tetris .block3,#tetris .block4,#tetris .block5,#tetris .block6

{

  z-index:1000;

  font-size:10px;

  line-height:1em;

  position:absolute;

  width:13px;

  height:13px;

  border:0.5px solid red;

  background:#000;

}

</style>

  

<script src="jquery.js"></script>

<script type="text/javascript">

//2维数组,用来存放俄罗斯方块的坐标

  

var xYAxis=[];

xYAxis.push([1,2],[3,4]);

  

//alert(xYAxis[1][0]);

  

//复制节点

/*$(document).ready(function(e) {

    

  for(i=0;i<2;i++)

  {

    if(i==1)

    {

     // $("#test").append("<br>");  //加上换行符

    }

    $(".t").clone().appendTo("#test");

  }

    

  //动态得到test(container)的宽度,包含两边的边框BORDER

  $("#test").width(($(".t").width()+2)*2+1);

});

*/

//获得区域的横坐标和纵坐标

function getArea(x,y,unit,id)

{

  this.x=x;

  this.y=y;

  this.unit=unit; //每个单元的大小,单位为像素

  this.el=document.getElementById(id); //得到ID对象

    

  this.board=[]; //面板,即在区域范围内的元素(俄罗斯方块)

    

  /*创建2D范围矩阵*/

  for(var y=0;y<this.y;y++)

  {

    this.board.push(new Array());

    for(var x=0;x<this.x;x++)

    {

      this.board[y].push(0);

    }

  }

    

  /*从2D矩阵中消除元素*/

  this.destroy=function()

  {

    for(var y=0;y<this.board.length;y++)

    {

      for(var x=0;x<this.board[y].length;x++)

      {

        if(this.board[y][x])

        {

          this.el.removeChild(this.board[y][x]);

          this.board[y][x]=0;

        

      

    

      

  }

    

  //添加元素

  this.addElement=function(el)

  {

    //得到起始元素的X开始坐标和Y开始坐标的位置(错误)

    //得到X坐标的下落次数,和Y轴的左右移动的次数

    var xBegin=parseInt(el.offsetLeft/unit); 

    var yBegin=parseInt(el.offsetTop/unit);

      

    if(xBegin>=0&&xBegin<=this.x&&yBegin>=0&&yBegin<=this.y)

    {

        this.board[yBegin][xBegin]=el; //确定元素的位置

    }

  

  }

    

  //消掉所有的行

  this.removeFullLines=function()

  {

    var lines=0;

    for(var i=this.y-1;i>0;i--)

    {

      if(this.linesRelated(i))

      {

        this.removeLines(i);

        lines++;

        y++;

      }

    }

    return lines; //返回线条 

  }

    

  //和线性有关的东西(判断是否满了)

  this.linesRelated=function(y)

  {

    for(var x=0;x<this.x;x++)

    {

        if(!this.board[y][x]){return false;}   //如果不为0的话,那么菜返回FALSE

    }

      

    return true;

  };

    

  //去掉行

  this.removeLines=function(y)

  {

    for(var x=0;x<this.x;x++)

    {

      this.el.removeChild(this.board[y][x]);

      this.board[y][x]=0;

    }

    y--;

    for(;y>0;y--)

    {

      /*今天暂时写到这里*/

      /*继续于2014-12-21*/

      for(var x=0;x<this.x;x++)

      {

        if(this.board[y][x])

        {

          var el=this.board[y][x];

          el.style.top=el.offsetTop+this.unit+"px";

          this.board[y+1][x]=el;

          this.board[y][x]=0;

        

      

    }

  };

    

  //活动区域

  this.getBlock=function(y,x)

  {

    if(y<0){return 0;} 

    if(y<this.y&&x<this.x)

    {

      return this.board[y][x]; 

    }

    else

    {

      throw "Area get failed!";

    }

      

  }

}

  

/*俄罗斯方块实体类*/

function Tetris()

{

  var self =this; //自身

  var operate=null;

    

  this.area=null;

  this.operate=null; //操作

    

  this.status=new State(); //新建状态

  /*初始化X,Y,单元为5或者20*/

  this.x=20;

  this.y=20;

  this.unit=20;

    

  this.running=null; //是否在运行中

    

  //俄罗斯方块实体ID

  this.id="tempid";

    

  /*开始的时候暂停是FALSE的*/

  this.paused=false;

    

  //开始游戏

  this.start=function()

  {

    self.reset(); //重新开始游戏

    self.status.start();

      

    this.area=new getArea(this.x,this.y,this.unit,"tetris-area"); //获得Area对象  ,其中TEMPID是俄罗斯方块实体类ID

    this.operate=new OperateTetris(this.area,self);

      

    //是否可以替换

    if(this.operate.mayPlace())

    {

      //alert(1);

      this.operate.place(); 

    }

    else

    {

      self.gameOver(); 

    }

      

      

  

    

  //游戏结束

  this.gameOver=function()

  {

    self.status.stopGame(); //停止游戏

    self.operate.stopGame(); //操作类停止游戏

      

  }

    

  /*重置游戏*/

  this.reset=function()

  {

    if(this.operate)

    {

      self.operate.destroy(); //重新开始

      self.operate=null;

    }

    if(self.area)

    {

      self.area.destroy();

      self.area=null;

    }

    //隐藏游戏结束

    document.getElementById("game_over").style.display="none";

    document.getElementById("next_operate").style.display="block"; //下一个操作

    document.getElementById("keys_Press").style.display="block"; //显示按键

      

    self.status.reset();

    self.paused=false;

      

    document.getElementById("tetris-pause").style.display="block"; //暂停按钮

  

  }

    

  /*暂停游戏*/

  this.pause=function()

  {

    if(self.operate==null)

    {

      return

    

    if(self.paused)

    {

      self.operate.running=true;

      /*这里还没写完2014-12-22*/ 

    }

    else

    {

          

    }

      

  }

    

  //上

  this.up=function()

  {

    if(self.operate&&self.operate.isRunning()&&!self.operate.isStopped())

    {

      if(self.operate.mayRotate())

      {

        self.operate.rotate();

        self.status.setActions(self.status.getActions()+1);

      

    }

  }

    

  //下

  this.down=function()

  {

    if(self.operate&&self.operate.isRunning()&&!self.operate.isStopped())

    {

      if(self.operate.mayMoveDown())

      {

        self.operate.moveDown();

        self.status.setActions(self.status.getActions()+1);

      

    }

  }

    

  //左

  this.left=function()

  {

    if(self.operate&&self.operate.isRunning()&&!self.operate.isStopped())

    {

      if(self.operate.mayMoveLeft())

      {

        self.operate.moveLeft();

        self.status.setActions(self.status.getActions()+1);          

      }

  

    }

  }

    

  //右

  this.right=function()

  {

    if(self.operate&&self.operate.isRunning()&&!self.operate.isStopped()) 

    {

      if(self.operate.mayMoveRight())

      {

        self.operate.moveRight();

        self.status.setActions(self.status.getActions()+1);

      }

    }

  }

    

    

    

  //开始游戏

  document.getElementById("startGame").onclick=function(){self.start()};

//} //Tetris是一个整体类,里面包含了很多方法。

  var keyboard=new Keyboard(); //创建键盘类实体

  keyboard.set(keyboard.n,this.start);

  keyboard.set(keyboard.up,this.up);

  keyboard.set(keyboard.down,this.down);

  keyboard.set(keyboard.left,this.left);

  keyboard.set(keyboard.right,this.right);

    

  document.onkeydown=keyboard.event; //按下按键按钮的事件

    

  

/*键盘操作方法*/

function Keyboard()

{

  this.up=38; //上

  this.down=40; //下

  this.left=37; //左

  this.right=39; //右

    

  this.n=78;

  this.p=80;

  this.r=82;

  this.space=32; //空格

  this.f12=123;

  this.escape=27; //退格键

    

  this.keys=[]; //键位集合

  this.funcs=[];

  var self=this;

    

  //设置键位

  this.set=function(key,func)

  {

    this.keys.push(key);

    this.funcs.push(func);

  }

    

  this.event=function(e)

  {

    if(!e){e=window.event;}

    for(var i=0;i<self.keys.length;i++)

    {

      if(e.keyCode==self.keys[i])

      {

        self.funcs[i](); 

      }

    }

  }

    

      

}

  

  

//具体的操作类

function OperateTetris(area,tetris)

{

  var self=this; //当前对象

  this.area=area;

  this.tetris=tetris;

    

  this.types=null; //方块的类型;

  this.nextType=null; //下一个类型

    

  //初始化X和Y

  this.x=null;

  this.y=null;

  this.position=0; //初始位置

    

  this.board=[]; //用来填充HTML元素的

  this.elements=[];

  this.nextElements=[]; //下一个元素

    

  this.running=null; //是否在运行中

  this.stopped=null; //是否停止

    

  this.fallDownId=null; //往下掉落的

  this.speed=null; //速度

    

  /*方块的组合方式,用数组进行组合(二维数组)

  用0,1表示是否有方块存在,如果是0:不存在,1:存在,

  以下的逻辑就可以非常的清楚了。*/

  this.blockComplex=[

  [

  [0,0,1],[1,1,1],[0,0,0] //_|

  ],

    

  [

  [1,0,0],[1,1,1],[0,0,0] //L

  ],

    

  [

  [0,1,0],[1,1,1],[0,0,0] //T

  ],

    

  [

  [0,0,0],[1,1,1],[0,0,0] //--

  ],

    

  [

  [0,0,0],[0,1,1],[0,1,1] //口

  ],

    

  [

  [0,1,1],[0,1,0],[1,1,0] //Z

  ]

  ];

    

  this.stopGame=function()

  {

    this.running=false;

  }

    

  /*一连串的GETTER方法

  分别是速度,X,Y轴,运行和停止的GETTER方法*/

  this.getSpeed=function()

  {

    return this.speed;

  }

    

  this.getX=function()

  {

    return this.x;

  }

    

  this.getY=function()

  {

    return this.y;

  }

    

  this.isRunning=function()

  {

    return this.running; 

  }

    

  this.isStopped=function()

  {

    return this.stopped;

  }

    

  //重置(初始化)

  this.reset=function()

  {

    if(this.fallDownId)

    {

      clearTimeout(this.fallDownId); //下落的时候去掉时间间隔 

    }

    this.types=this.nextType;

    this.nextType=random(this.blockComplex.length);

      

        

    this.position=0;

    this.board=[];

    this.elements=[];

    this.x=null;

    this.y=null;

    this.speed=200; //速度暂定为51

      

    this.running=false;

    this.stopped=false;

      

    //移除下一个元素

    for(var i=0;i<this.nextElements.length;i++)

    {

      document.getElementById("next_operate").removeChild(this.nextElements[i]);

    }

      

    this.nextElements=[]; //下一个元素

      

      

      

        

  }

  //下一个类型,随机抽取

  this.nextType=random(this.blockComplex.length);

    

  //重置

  this.reset();

    

  /*判断是否替换*/

  this.mayPlace=function()

  {

    var isOperate=this.blockComplex[this.types];

      

    /*area开始的坐标原点*/

    var areaStartX=parseInt(this.area.x-isOperate[0].length);

    var areaStartY=1;

    var lineFound=false;

    var lines=0;

    for(var y=isOperate.length-1;y>=0;y--)

    {

      for(var x=0;x<isOperate[y].length;x++)

      {

        if(isOperate[y][x])

        {

          lineFound=true;

          if(this.area.getBlock(areaStartY,areaStartX+x)) {return false;}

        

      

        

      if(lineFound)

      {

        lines++; 

      }

      if(areaStartY-lines<0)

      {

        break;

      }

        

    }

      

    return true;

  }

    

  /*替换*/

  this.place=function()

  {

    //初始化

    var operate=this.blockComplex[this.types];

      

      

    //区域开始X轴的位置

    var AreaXStartPos=parseInt(this.area.x-operate[0].length);

      

    //区域开始Y轴的位置

    //var AreaYStartPos=parseInt(this.area.y-operate[0]);

    var AreaYStartPos=1; //因为X轴的位置可能变化,而Y轴总是从最上面下来的,所以是1

      

    this.x=AreaXStartPos; //把新的位置赋给X;

    this.y=AreaYStartPos; //把新的位置赋给y;

      

    //构建空对象,并存入BOARD

    /*y:行,x:列*/

  

    //alert(operate[0].length+" "+operate.length);

    this.board=this.createEmpty(operate[0].length,operate.length);

      

    /*线条,往下掉落,初始化*/

    var lines=0;

    var foundLines=false;

      

    //循环遍历,先遍历行,每一行再来遍历列

    for(var yAxis=operate.length-1;yAxis>=0;yAxis--)

    {

      for(var xAxis=0;xAxis<=operate[yAxis].length;xAxis++)

      {

        if(operate[yAxis][xAxis])

        {

          var el=document.createElement("div");

          el.className="block"+this.types; //确定这个元素的CLASSNAME

            

          //确定左边距和上边距

          el.style.left=(this.x+xAxis)*this.area.unit+"px";

          el.style.top=(this.y+yAxis)*this.area.unit+"px";

          this.area.el.appendChild(el); //这个EL去APPEND主要的EL。

            

          this.board[yAxis][xAxis]=el;

          this.elements.push(el); //推入elements中

            

        }

      }

        

      /*个人感觉这个功能应该是加速往下掉落的方法?不明觉厉*/

      if(lines)

      {

        yAxis--; 

      }

        

      if(foundLines)

      {

        lines++;

      }

    

    }

      this.running=true;

      this.fallDownId=setTimeout(this.fallDown,this.speed); //间隔时间,掉落下的

        

      var nextOperate=this.blockComplex[this.nextType];

      for(var y=0;y<nextOperate.length;y++)

      {

        for(var x=0;x<nextOperate[y].length;x++)

        {

          //创建元素

          if(nextOperate[y][x])

          {

            /*先写到这里:2014-12-22*/ 

            var el=document.createElement("div");

            el.className="block"+this.nextType;

            el.style.left=(x*this.area.unit)+"px";

            el.style.top=(y*this.area.unit)+"px";

              

            document.getElementById("next_operate").appendChild(el);

            this.nextElements.push(el); //下一个元素

              

          

        

      }

        

  }

    

  //创建空对象,即所有的都为0的对象,并返回对象

  this.createEmpty=function(x,y)

  {

      var elements=[];

      for(var y2=0;y2<y;y2++)

      {

          

        elements.push(new Array());

          

        for(var x2=0;x2<x;x2++)

        {

          elements[y2].push(0); 

        }

            

      }

      return elements;

  }

    

  //下落(这是一个最关键的函数,决定了这个游戏的成败)

  this.fallDown=function()

  {

    if(self.isRunning()) 

    {

  

        if(self.mayMoveDown())

        {

          self.moveDown(); 

          self.fallDownId=setTimeout(self.fallDown,self.speed); //下落的间隔时间

            

        }

        else

        {

          for(var i=0;i<self.elements.length;i++)

          {

            self.area.addElement(self.elements[i]);

          }   

          var lines=self.area.removeFullLines();

          if(lines)

          {

            /*这里到时候再写*/

            self.tetris.status.setLines(self.tetris.status.getLines()+lines);

          }

            

          self.reset();

          if(self.mayPlace())

          {

            self.place(); 

          }

          else

          {

            self.tetris.gameOver();

          }

        }

    }

    else

    {

              

    }

      

  }

    

    

  //是否可以旋转俄罗斯方块

  this.mayRotate=function()

  {

    for(var y=0;y<this.board.length;y++)

    {

      for(var x=0;x<this.board[y].length;x++)

      {

        if(this.board[y][x])

        {

            

          /新的X,Y的值/

          var newY=this.getY()+this.board.length-1-x;

          var newX=this.getX()+y;

            

          if(newY>this.area.y){return false;}

          if(newX<0){return false;}

          if(newX>=this.area.x){return false;}

          if(this.area.getBlock(newY,newX)){return false;}   //获得区域

            

        

      

    }

    return true;

  }

    

  //旋转俄罗斯方块

  this.rotate=function()

  {

    var puzzle=this.createEmpty(this.board.length,this.board[0].length); //创建一个空的矩阵

    for(var y=0;y<this.board.length;y++)

    {

      for(var x=0;x<this.board[y].length;x++)

      {

        //旋转,X轴和Y轴的坐标互换

        if(this.board[y][x])

        {

          var newY=puzzle.length-1-x;

          var newX=y;

          var el=this.board[y][x]; //旋转前的对象

            

          var moveY=newY-y;

          var moveX=newX-x;

            

          //长度是offsetTop或left加上偏移量

          el.style.left=el.offsetLeft+(moveX*this.area.unit)+"px";

          el.style.top=el.offsetTop+(moveY*this.area.unit)+"px";

            

          puzzle[newY][newX]=el;

            

        

      

    }

    this.board=puzzle;

  }

    

  //下落方法(进行判断)

  this.mayMoveDown=function()

  {

    for(var y=0;y<this.board.length;y++)

    {

      for(var x=0;x<this.board[y].length;x++)

      {

        if(this.board[y][x])

        {

          if(this.getY()+y+1>=this.area.y){this.stopGame=true;return false;}  //如果触底,那么就停止游戏

          if(this.area.getBlock(this.getY()+y+1,this.getX()+x)){this.stopGame=true;return false;}

            

            

        

      

    

      

    return true;

  }

    

  //下落

  this.moveDown=function()

  {

    //用一个循环去控制下落

    for(var i=0;i<this.elements.length;i++)

    {

      this.elements[i].style.top=this.elements[i].offsetTop+this.area.unit+"px";

        

    

    this.y++;

  }

    

  this.mayMoveLeft=function()

  {

    /*可以向左移动(判断方法)*/

    for(var y=0;y<this.board.length;y++)

    {

      for(var x=0;x<this.board[y].length;x++)

      {

        if(this.board[y][x])

        {

          if(this.getX()-1+x<0)

          {

            return false; 

          

            

            

          if(this.area.getBlock(this.getY()+y,this.getX()+x-1)){return false;}

            

        }

      

    }

    return true;

      

  }

    

  //向左移动

  this.moveLeft=function()

  {

    /*向左移动(判断方法)*/

    for(var i=0;i<this.elements.length;i++)

    {

      this.elements[i].style.left=this.elements[i].offsetLeft-this.area.unit+"px";

    }

    this.x--;

        

  }

    

  /*是否可以向右移动*/

  this.mayMoveRight=function()

  {

    for(var y=0;y<this.board.length;y++)

    {

      for(var x=0;x<this.board[y].length;x++)

      {

        if(this.board[y][x])

        {

          if(this.getX()+1+x>=this.area.x){return false;}

          if(this.area.getBlock(this.getY()+y,this.getX()+x+1)){return false;}

        

      

    

      

    return true;

  }

    

  /*向右移动*/

  this.moveRight=function()

  {

    for(var i=0;i<this.elements.length;i++)

    {

      this.elements[i].style.left=this.elements[i].offsetLeft+this.area.unit+"px"

    

    this.x++;

  }

    

  /*摧毁方法*/

  this.destroy=function()

  {

    for(var i=0;i<this.elements.length;i++)

    {

      this.area.el.removeChild(this.elements[i]);

        

    

    this.elements=[];

    this.board=[];

    this.reset();

  }

}

  

/*俄罗斯方块状态*/

function State()

{

    

    

  /*初始化*/

  this.level;

  this.time;

  this.score;

  this.opeate;

  this.lines;

    

  this.apm; //不明觉厉

    

  this.actions; //动作

    

  this.el=

  {

    "lines":document.getElementById("lines"),

    "level":document.getElementById("level"),

    "time":document.getElementById("time"),

    "apm":document.getElementById("apm"),

    "operate":document.getElementById("operate")

  }

    

  this.timeId=null;

  var self=this;

    

  //开始游戏

  this.start=function()

  {

    this.reset(); //重置

    this.timeId=setInterval(this.incTime,1500);

        

  }

    

  /*停止游戏*/

  this.stopGame=function()

  {

    if(this.timeId)

    {

      clearInterval(this.timeId);

    }

        

  }

    

  //重置

  this.reset=function()

  {

    this.stopGame();

    this.level=1;

    this.time=0;

    this.score=0

    this.opeate=0;

    this.lines=0;

      

    /*以后可能加INNERHTML*/

    this.el.level=this.level;

    this.el.time=this.time;

    this.el.score=this.score;

    this.el.operate=this.opeate;

    this.el.lines=this.lines;

      

  }

    

  //和SetInterval有关

  this.incTime=function()

  {

    self.time++;

    self.el.time.innerHTML=self.time; //设置时间

    self.actions=parseInt(self.actions/self.time)*60;

    this.el.apm.innerHTML=self.apm;

      

  }

    

  /*设置分数*/

  this.setScore=function(i)

  {

    this.score==i;

    this.el.score.innerHTML=this.score;

  }

    

  /*设置等级*/

  this.setLevel=function(i)

  {

    this.level=i;

    this.el.level.innerHTML=this.level; //设置内部HTML

  };

    

  this.getLevel=function()

  {

    return this.level;

  }

    

  //线条的SETTER方法

  this.setLines=function(i)

  {

    this.lines=i;

    this.el.lines.innerHTML=this.lines;

  }

    

  this.getLines=function()

  {

    return this.lines;

  }

    

  //设置动作

  this.setActions=function(i)

  {

    this.actions=i;

    //this.el.actions.innerHTML=this.actions; 

  }

    

  this.getActions=function()

  {

    return this.actions; 

  }

    

  //设置apm

  this.setApm=function(i)

  {

    this.apm=i;

    this.el.apm.innerHTML=this.apm;

  }

    

  this.getApm=function()

  {

    return this.apm; 

  }

    

  //控制下落操作的类

  this.setOperate=function(i)

  {

    this.opeate=i;

    this.el.operate=this.operate;

  }

    

  this.getOperate=function()

  {

    return this.opeate;

  }

    

  

}

  

//随机数,产生1~6的

function random(i)

{

  return Math.floor(Math.random()*i);

}

  

} /*Tetris是一个整体类,里面包含了很多方法*/

</script>

  

</head>

  

<body>

  

  <div id="tetris">

  <!--正方形 -->

<div id="test">

  <div class="t"></div>

</div>

  

<!--长方形-->

<div id="rect">

  <div class="r">

    

  </div>

</div>

  

<!-- 俄罗斯方块实体类-->

<div id="tetris-area">

    

</div>

  

<!-- 下一个操作-->

<div id="next_operate"></div>

  

<!--游戏结束-->

<div id="game_over">Game Over</div>

  

<!-- 按键 -->

<div id="keys_Press">

  

  

</div>

  

<input type="button" id="startGame" value="Start" />

  

<!--线条 -->

<div id="lines"></div>

  

<!--等级 -->

<div id="level"></div>

  

<!--apm(不知道有什么作用) -->

<div id="apm"></div>

  

<!--时间 -->

<div id="time"></div>

  

<!--控制下落操作 -->

<div id="operate"></div>

  

<!-- 功能键(暂停)-->

<div id="tetris-pause">

  

</div>

  

<!-- 功能键(继续)-->

<div id="tetris-resume" style="display:none">

  

</div>

</div>

<script>

  var tx=new Tetris();

  tx.x=12;

  tx.y=22;

  tx.unit=14;

  //tx.start(); //开始游戏

</script>

  

</body>

</html>

Copy after login

Demo picture:

Project git address:
http://git.oschina.net/KMSFan/Tetris_Yang

Project demonstration address: http://runjs.cn/detail/ggo07ery

The above is the entire content of this article. I hope it will be helpful to everyone learning javascript.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles