2人でテニスゲーム

このエントリーをはてなブックマークに追加

obnizにはスイッチとディスプレイがあるので,簡単なゲームも作れちゃいます!

Program

 <!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <script src="https://obniz.io/js/jquery-3.2.1.min.js" ></script>
        <script src="https://unpkg.com/obniz@1.2.0/obniz.js" crossorigin="anonymous"></script>

    </head>

    <body>

<div id="obniz-debug"></div>
        <h1>obniz instant html</h1>
        <canvas id="canvas1" width="128" height="68"></canvas>
        <canvas id="canvas2" width="128" height="68" ></canvas>


        <script>
            const params = {local_connect:true,binary:true};
            const ctx1 = $("#canvas1")[0].getContext('2d');
            const ctx2 = $("#canvas2")[0].getContext('2d');

            var obniz1 = new Obniz("9582-4465",params);
          
            var obniz2;
            const width = obniz1.display.width;
            const height = obniz1.display.height;

            const msecPerFrame = 60;
            const  barSpeed = 2;
            const backgroundColor = "#000000";
            const mainColor = "#FFFFFF";


            var scenes = [];
            var currentScene = 0;

            function nextScene(i, params) {
              if (typeof i === "number") {
                currentScene = i;
              } else {
                currentScene++;
              }
              if(typeof i === "object"){
                  params = i;
              }
              scenes[currentScene].init(params);
            }

            // title scene
            scenes.push({
              init: function () {
                obniz1.display.clear();
                obniz1.display.print("push BUTTON");

                obniz2.display.clear();
                obniz2.display.print("wait for player1");
              },
              frame: async function () {
                if (obniz1.switch.state === "push") {
                  nextScene();
                }
              }
            });

            // game scene
            scenes.push({
              init: function () {
                this.results = null;

                this.ball = {x: width / 2, y: height / 2, radius: 3};
                this.speed = 1;
                this.ballVec = {x: -1, y: -1};
                this.myBar = {x: 10, y: height / 2, width: 5, height: 15};
                this.yourBar = {x: width - 10, y: height / 2, width: 5, height: 15};
              },
              frame: async function () {
                await this.calc();
                await this.draw();

                if(this.results){
                     nextScene(this.results);
                }
              },

              calc: async function () {
                this.userCalc();
                this.botCalc();
                this.ballCalc();
              },

              userCalc: function () {
                if (obniz1.switch.state === "right") {
                  this.myBar.y+=barSpeed;
                } else if (obniz1.switch.state === "left") {
                  this.myBar.y-=barSpeed;
                }

              },
              botCalc: function () {
                if (obniz2.switch.state === "right") {
                  this.yourBar.y+=barSpeed;
                } else if (obniz2.switch.state === "left") {
                  this.yourBar.y-=barSpeed;
                }
              },
              ballCalc: function () {
                this.ball.x += this.ballVec.x;
                this.ball.y += this.ballVec.y;

                if (isHitBall(this.ball, {x: 0, y: -100, width: width, height: 100})) {
                  this.ballVec.y *= -1;
                }
                if (isHitBall(this.ball, {x: 0, y: height, width: width, height: 100})) {
                  this.ballVec.y *= -1;
                }

                //ball
                var myHit = hitDirection(this.ball, this.myBar);
                if (myHit === "x") {
                  this.ballVec.x *= -1;
                }
                if (myHit === "y") {
                  this.ballVec.y *= -1;
                }

                //ball
                var yourHit = hitDirection(this.ball, this.yourBar);
                if (yourHit === "x") {
                  this.ballVec.x *= -1;
                }
                if (yourHit === "y") {
                  this.ballVec.y *= -1;
                }

                if (myHit || yourHit) {
                  this.ballVec.x *= 1 + Math.random();
                  this.ballVec.y *= 1 + Math.random();
                }

                //goal
                if (isHitBall(this.ball, {x: -100, y: -100, width: 100, height: 300})) {
                  this.results = {results1:"YOU LOSE" , results2 : "YOU WIN"};
                }

                if (isHitBall(this.ball, {x: width, y: -100, width: 100, height: 300})) {
                  this.results = {results1:"YOU WIN" , results2 : "YOU LOSE"};
                }

              },
              draw: async function(){
                this.clear();
                this.drawToContext();
                await obniz1.display.draw(ctx1);
                await obniz2.display.draw(ctx2);
              },
              clear: function () {
                ctx1.fillStyle = backgroundColor;
                ctx1.strokeStyle = mainColor;
                ctx1.fillRect(0, 0, width, height);
                ctx1.strokeRect(0, 0, width, height);

                ctx1.strokeStyle = mainColor;
                ctx1.fillStyle = mainColor;

                ctx2.fillStyle = backgroundColor;
                ctx2.strokeStyle = mainColor;
                ctx2.fillRect(0, 0, width, height);
                ctx2.strokeRect(0, 0, width, height);

                ctx2.strokeStyle = mainColor;
                ctx2.fillStyle = mainColor;
              },
              drawToContext: async function () {

                ctx1.beginPath();
                ctx1.arc(this.ball.x, this.ball.y, this.ball.radius, 0 * Math.PI / 180, 360 * Math.PI / 180, true);
                ctx1.fill();

                ctx1.fillRect(this.myBar.x, this.myBar.y, this.myBar.width, this.myBar.height);
                ctx1.fillRect(this.yourBar.x, this.yourBar.y, this.yourBar.width, this.yourBar.height);


                ctx2.fillRect(width - this.myBar.x - this.myBar.width, this.myBar.y, this.myBar.width, this.myBar.height);
                ctx2.fillRect(width - this.yourBar.x - this.yourBar.width, this.yourBar.y, this.yourBar.width, this.yourBar.height);

                ctx2.beginPath();
                ctx2.arc(width - this.ball.x, this.ball.y, this.ball.radius, 0 * Math.PI / 180, 360 * Math.PI / 180, true);
                ctx2.fill();
              }


            });

            // results scene
            scenes.push({
              init: function (obj) {
                obniz1.display.clear();
                obniz1.display.print(obj.results1);
                obniz2.display.clear();
                obniz2.display.print(obj.results2);
                this.beforeState = "none";
              },
              frame: async function () {
                if (obniz1.switch.state === "none"
                    && this.beforeState === "push") {
                  nextScene(0);
                }
                this.beforeState = obniz1.switch.state;
              }

            });


            obniz1.onconnect = async function () {
              obniz2 = new Obniz("17804573",params);
              obniz2.onconnect = async function () {
                console.log("obniz1",obniz1.socket_local && obniz1.socket.readyState ==1 ? "local":"server");
                console.log("obniz2",obniz2.socket_local && obniz2.socket.readyState ==1 ? "local":"server");
                nextScene(0);
                while (1) {
                  var lastTime = (new Date()).getTime();
                  await scenes[currentScene].frame();
                  await Promise.all([obniz1.pingWait(),obniz2.pingWait()]);
                  var time = (new Date()).getTime();
                  var waitTime = (lastTime + msecPerFrame) - time;
                  //console.log("margin time : ", waitTime);
                  if (waitTime > 0) {
                    await new Promise(( resolve )=>{ setTimeout(resolve, waitTime) });
                  }
                }
              };
            };


            function isHitBall(ball, rect) {
              if (Math.abs(rect.x + rect.width / 2 - ball.x) < rect.width / 2 + ball.radius
                  &&
                  Math.abs(rect.y + rect.height / 2 - ball.y) < rect.height / 2 + ball.radius) {
                return true;
              }
              return false;
            }

            function hitDirection(ball, rect) {
              if (isHitBall(ball, {x: rect.x, y: rect.y, width: 1, height: rect.height})
                  || isHitBall(ball, {x: rect.x + rect.width - 1, y: rect.y, width: 1, height: rect.height})) {
                return "x";
              }
              if (isHitBall(ball, {x: rect.x, y: rect.y, width: rect.width, height: 1})
                  || isHitBall(ball, {x: rect.x, y: rect.y + rect.height - 1, width: rect.width, height: 1})) {
                return "y";
              }
              return null;
            }



        </script>
    </body>

</html>