中安拓也のブログ

プログラミングについて書くブログ

Angularでテトリスを作った

f:id:l08084:20180215141549g:plain

はじめに

Angular5を使ってテトリスを作成しました。👇のGitHub Pagesで実際に遊べます。

https://l08084.github.io/angular-tetris/

操作方法:

キーボードの矢印キーでブロックの移動、スペースキーでブロックの回転ができます。なお、PC専用でChrome以外の動作確認を行なっていません

ソースコードは👇です

github.com

開発環境

  • Angular: 5.2.3

  • TypeScript: 2.5.3

  • angular/cli: 1.6.5

  • OS: darwin x64

  • Node: 8.1.4

このテトリスについて

下記サイト様のJavaScript版テトリスを参考に作成しました

coderecipe.jp

Angular感のあるところ

基本的に👆サイト様のコードと同じになってしまってるんですが、HTML5要素のcanvasを使用している部分と、キーボードイベントを取得している所をAngular風に書き直しています。

Angularによるcanvas参照

ViewChildアノテーションでcanvasタグのIDを指定すると、canvas要素を参照することができます。

@Component({
  selector: 'app-root',
  template: `<canvas #campas width='300' height='600'></canvas>
             <div class="how-control">
                <h1 class="title">- HOW TO PLAY-</h1>
                <p class="detail">ブロックの操作: keybord(←→↓)</p>
                <p class="detail">回転: keybord(space)</p>
             </div>`,
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, AfterViewInit, OnDestroy {
  private context: CanvasRenderingContext2D;

  @ViewChild('campas') campas;

  ngAfterViewInit() {
    const canvas = this.campas.nativeElement;
    this.context = canvas.getContext('2d');
    // 30ミリ秒ごとに状態を描画する関数を呼び出す
    setInterval(() => this.render(), 30);
  }

Angularによるキーボードイベント取得

form以外からのイベント取得ってどうやるのかわかんねえなと思ったんですが、Observableを使うのが今時っぽい。

import { Component, ViewChild, AfterViewInit, OnInit, OnDestroy } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import 'rxjs/add/observable/fromEvent';

@Component({
  selector: 'app-root',
  template: `<canvas #campas width='300' height='600'></canvas>
             <div class="how-control">
                <h1 class="title">- HOW TO PLAY-</h1>
                <p class="detail">ブロックの操作: keybord(←→↓)</p>
                <p class="detail">回転: keybord(space)</p>
             </div>`,
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, AfterViewInit, OnDestroy {
  private subscription: Subscription;

  ngOnInit() {
    this.newGame();
    this.subscription = Observable.fromEvent(document, 'keydown').subscribe((e: KeyboardEvent) => {
      this.keyPress(e);
    });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }

初めてのGithub Pages

angular-cli-ghpagesというライブラリを使ってGithub Pagesにあげることができます。

# インストールしていなければ
$ npm i -g angular-cli-ghpages

# "https://USERNAME.github.io/REPOSITORY/"
$ ng build --prod --base-href "https://l08084.github.io/angular-tetris/"
$ angular-cli-ghpages

参考サイト

qiita.com

qiita.com

Angular + Reduxでテトリスを作ってみた...に続く予定です