es6+canvas+webpack+babel編譯實現簡單打字遊戲

之前用es5和canvas寫過打字遊戲,今天爲了增強對es6理解以及webpack環境配置,決定重新對以前代碼進行模塊化開發。

由於有些簡單,就直接上

目錄結構


項目依賴

{
  "name": "typing",
  "version": "1.0.0",
  "description": "es6 typingGame",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build":"webpack"
  },
  "author": "miao",
  "license": "ISC",
  "devDependencies": {
    "babel": "^6.23.0",
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.4",
    "css-loader": "^0.28.10",
    "extract-text-webpack-plugin": "^3.0.2",
    "less": "^3.0.1",
    "less-loader": "^4.1.0",
    "node-sass": "^4.7.2",
    "sass-loader": "^6.0.7",
    "style-loader": "^0.20.3",
    "webpack": "^4.1.1",
    "webpack-cli": "^2.0.11"
  }
}

webpack編譯配置,使用babel轉譯爲es5,裏面的一些依賴配置這個打字遊戲沒用上,只用到babel編譯。入口文件是src/js/main.js輸出文件是out/index.js

var webpack = require('webpack');
var path = require('path');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
module.exports = {
    devtool: 'eval-source-map',
    entry: './src/js/main.js',
    output: {
        path: path.resolve(__dirname, 'out'),
        publicPath: './out/',
        // publicPath: 'https://github.com/paysonTsung/Fighter/out',
        filename: 'index.js'
    },
    module: {
        rules: [
            {
                test: /\.css$/, 
                use: ExtractTextPlugin.extract({
                    fallback: 'style-loader',
                    use: 'css-loader',
                    // publicPath: './out',
                })
            },
            // { test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader") },
            { test: /\.less$/, use: ["style-loader", "css-loader", "less-loader"] },
            {
                test: /\.js$/,
                loader: "babel-loader",
                exclude: /node_modules/,
                query: {
                    presets: [
                        require.resolve('babel-preset-es2015'),
                    ]
                }
            },
            { test: /\.(jpg|png)$/, use: ["url-loader"] }
        ]
    }
}

index.html這裏的index.js是經過webpack編譯打包後的輸出文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>typing game</title>
    <!-- <script src="./out/index.js"></script> -->
    
</head>
<body>
    <div style="width: 732px;height: 472px;margin:50px auto;">
		<canvas id="canvas" style="background: #000;"></canvas>
	</div>

    <script src="./out/index.js"></script>
</body>
</html>

canvas.js提供畫圖接口

let canvas,ctx
canvas=document.getElementById('canvas');
ctx=canvas.getContext('2d');//畫筆
canvas.width=632;
canvas.height=472;

export {canvas,ctx}

letter.js提供字母接口

import {canvas,ctx} from './canvas'
export default class Letters {
    constructor(){
        this.x=Math.floor(Math.random()*400)+80
		this.y=50
		this.Ax=this.x-15
		this.Ay=this.y-40
		this.aLive=true
		this.speed=Math.random()*0.017+2
		this.lett=this.letters()[Math.floor(Math.random()*48)]
		this.lePic=new Image()
        this.lePic.src='./images/蘋果[圖形].png'
        this.ctx = ctx;
		this.fColor='yellow'
    }
    init(){
        this.leBackground();
    }
    letters(){
        return ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
        'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
    }
    leBackground() {
        this.Ay+=this.speed;
        this.y+=this.speed;
        if(this.aLive){
            this.ctx.save();
            this.ctx.drawImage(this.lePic,this.Ax,this.Ay,55,55);
            this.ctx.font = "40px Courier New";
            this.ctx.fillStyle =''+this.fColor+'';
            this.ctx.fillText(this.lett, this.x, this.y);
            this.ctx.restore();
        }
    }
    
}

draw.js提供繪圖接口

import {canvas,ctx} from './canvas'
import Letters from './letter'
export default class draw extends Letters{
    constructor(){
        super()
        this.bgPic
        this.le
    }
    init(){
        this.le = []
        for(let i = 0; i < 5; i++){
            super.init()
            this.le.push(new draw())
        }
        this.x = 0
        this.y = 0
        this.bgPic = new Image()
        this.bgPic.src = './images/bg2.png'
        this.ImageDraw()
    }
    ImageDraw(){
        this.ctx.drawImage(this.bgPic,this.x,this.y,632,472)
        for(let i = 0; i < this.le.length; i++){
            this.le[i].leBackground()
            if(this.le[i].Ay >= 432){
                this.born(i)
            }  
        }
    }
    born(i){
        this.le[i].aLive = false
        this.le[i].ctx = ctx
        this.le[i].x = Math.floor(Math.random()*400) + 80
        this.le[i].y = 0
        this.le[i].Ax = this.le[i].x - 15
        this.le[i].Ay = this.le[i].y - 40
        this.le[i].aLive = true
        this.le[i].speed = Math.random()*0.017 + 2
        this.le[i].lett = super.letters()[Math.floor(Math.random()*48)]
        this.le[i].lePic = new Image()
        this.le[i].lePic.src = './images/蘋果[圖形].png'
        this.le[i].fColor = this.le[i].fColor
        let le_i = this.le[i]
        this.le.splice(i,1,le_i)
    }
}

main.js作爲webpack編譯壓縮輸入文件,裏面引用draw,canvas提供的接口和按鍵判斷比對,遊戲運行功能

import {canvas,ctx} from './canvas'
import draw from './draw.js'
let dr,keyDown,speed,score

dr=new draw();

window.requestAnimFrame=(function(){
    return window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function( /* function FrameRequestCallback */ callback, /* DOMElement Element */ element) {
            return window.setTimeout(callback, 1000 / 60);
        };
})()

document.body.onload=game()

function game(){
    init()
    gameLoop()
}
function init(){
    dr.init();
    dr.ImageDraw()
}
function gameLoop(){
    dr.ImageDraw()
    requestAnimFrame(gameLoop)
}

//按鍵事件
keyDown={}
window.addEventListener('keydown',function(e){
    e=event||window.event
    let zh;
    let capsLockKey = e.keyCode ? e.keyCode : e.which
    let shifKey = e.shiftKey ? e.shiftKey:((capsLockKey == 16) ? true : false)
    if(((capsLockKey >= 65 && capsLockKey <= 90) && !shifKey)||((capsLockKey >= 97 && capsLockKey <= 122) && shifKey)){
        zh=true
    }else{
        zh=false
    }
    keyDown[e.keyCode]=true;
    for(let i=0;i<dr.le.length;i++){
        if(zh==true){
            if(String.fromCharCode(e.keyCode).toLocaleLowerCase()==dr.le[i].lett){
                dr.born(i)
            }
        }
        else{
            if(String.fromCharCode(e.keyCode)==dr.le[i].lett){
                dr.born(i)
            }
        }        
    }
});
window.addEventListener('keyup',function(e){
    delete keyDown[e.keyCode];//釋放按鍵對象
});				

裏面依賴自己安裝,步驟:npm install  ==> npm run build ==>用瀏覽器打開index.html

完整代碼:https://download.csdn.net/download/wujimiao/10289553

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章