Local storage working

This commit is contained in:
s-prechtl 2023-01-21 08:52:32 +01:00
parent 4c33b827c3
commit da018a5c73
2 changed files with 67 additions and 18 deletions

View file

@ -1,15 +1,23 @@
var __extends = (this && this.__extends) || (function () { var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) { var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf || extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || ({__proto__: []} instanceof Array && function (d, b) {
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; d.__proto__ = b;
}) ||
function (d, b) {
for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p];
};
return extendStatics(d, b); return extendStatics(d, b);
}; };
return function (d, b) { return function (d, b) {
if (typeof b !== "function" && b !== null) if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b); extendStatics(d, b);
function __() { this.constructor = d; }
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}; };
})(); })();
@ -36,64 +44,81 @@ var paused;
var hasAlreadyScored = false; var hasAlreadyScored = false;
var hasDied = true; var hasDied = true;
var ready = true; var ready = true;
function preload() { function preload() {
font = loadFont(FONT_PATH); font = loadFont(FONT_PATH);
backgroundImage = loadImage(BACKGROUND_IMAGE_PATH); backgroundImage = loadImage(BACKGROUND_IMAGE_PATH);
pipeImage = loadImage(PIPE_IMAGE_PATH); pipeImage = loadImage(PIPE_IMAGE_PATH);
floorImage = loadImage(FLOOR_IMAGE_PATH); floorImage = loadImage(FLOOR_IMAGE_PATH);
} }
function setup() { function setup() {
createCanvas(2000, 1000); createCanvas(1085, 600);
floorHeight = height / 5; floorHeight = height / 5;
setupObstacleConsts(); setupObstacleConsts();
setupFont(); setupFont();
setupGame(); setupGame();
var originalSetItem = localStorage.setItem; var originalSetItem = localStorage.setItem;
localStorage.setItem = function () { localStorage.setItem = function (key, value) {
document.createEvent('Event').initEvent('itemInserted', true, true); var event = new Event('itemInserted');
event.value = value; // Optional..
event.key = key; // Optional..
window.dispatchEvent(event);
originalSetItem.apply(this, arguments); originalSetItem.apply(this, arguments);
}; };
} }
function setupObstacleConsts() { function setupObstacleConsts() {
obstacleOffset = width / OBSTACLE_COUNT; obstacleOffset = width / OBSTACLE_COUNT;
obstacleWidth = width / 22.727272727272727272; obstacleWidth = width / 22.727272727272727272;
Obstacle.distanceBetweenPipes = height / 2.5; Obstacle.distanceBetweenPipes = height / 2.5;
Obstacle.startX = width; Obstacle.startX = width;
} }
function setupFont() { function setupFont() {
textSize(150); textSize(150);
textAlign(CENTER); textAlign(CENTER);
textFont(font); textFont(font);
} }
function setupGame() { function setupGame() {
paused = true; paused = true;
raspberry = new Raspberry(RASPBERRY_IMAGE_PATH); raspberry = new Raspberry(RASPBERRY_IMAGE_PATH);
setupObstacles(); setupObstacles();
} }
function setupObstacles() { function setupObstacles() {
obstacles = []; obstacles = [];
instantiateObstacles(OBSTACLE_COUNT); instantiateObstacles(OBSTACLE_COUNT);
obstacles.forEach(function (obstacle) { return obstacle.randomizeHeight(); }); obstacles.forEach(function (obstacle) {
return obstacle.randomizeHeight();
});
} }
function instantiateObstacles(number) { function instantiateObstacles(number) {
for (var i = 0; i < number; i++) { for (var i = 0; i < number; i++) {
obstacles.push(new Obstacle(new Position(width + obstacleOffset * i, 0), obstacleWidth, height, pipeImage)); obstacles.push(new Obstacle(new Position(width + obstacleOffset * i, 0), obstacleWidth, height, pipeImage));
} }
} }
function draw() { function draw() {
update(); update();
gameLoop(); gameLoop();
drawGame(); drawGame();
} }
function drawGame() { function drawGame() {
drawScenery(); drawScenery();
drawEntities(); drawEntities();
displayScore(); displayScore();
} }
function drawScenery() { function drawScenery() {
background(backgroundImage); background(backgroundImage);
drawFloor(); drawFloor();
} }
function drawFloor() { function drawFloor() {
push(); push();
noFill(); noFill();
@ -101,45 +126,55 @@ function drawFloor() {
rect(0, height - floorHeight, width, floorHeight); rect(0, height - floorHeight, width, floorHeight);
pop(); pop();
} }
function drawEntities() { function drawEntities() {
raspberry.draw(); raspberry.draw();
drawObstacles(); drawObstacles();
} }
function drawObstacles() { function drawObstacles() {
obstacles.forEach(function (obstacle) { obstacles.forEach(function (obstacle) {
obstacle.draw(); obstacle.draw();
}); });
} }
function gameLoop() { function gameLoop() {
if (!paused) { if (!paused) {
collisionCheck(obstacles[0]); collisionCheck(obstacles[0]);
checkRaspberryScore(); checkRaspberryScore();
} }
} }
function collisionCheck(o) { function collisionCheck(o) {
if (o.collides(raspberry)) { if (o.collides(raspberry)) {
die(); die();
setupGame(); setupGame();
} }
} }
function die() { function die() {
ready = false; ready = false;
hasDied = true; hasDied = true;
playTime = Date.now() - startTime; playTime = Date.now() - startTime;
exportToLocalStorage(); exportToLocalStorage();
setTimeout(function () { return ready = true; }, 1000); setTimeout(function () {
return ready = true;
}, 1000);
} }
function exportToLocalStorage() { function exportToLocalStorage() {
localStorage.setItem("game-playTime", String(playTime)); localStorage.setItem("game-playTime", String(playTime));
localStorage.setItem("game-score", String(score)); localStorage.setItem("game-score", String(score));
localStorage.setItem("game-isRunning", String(!hasDied)); localStorage.setItem("game-isRunning", String(!hasDied));
} }
function displayScore() { function displayScore() {
push(); push();
fill(195, 33, 34); fill(195, 33, 34);
text(score, 0, height / 10, width, height); text(score, 0, height / 10, width, height);
pop(); pop();
} }
function update() { function update() {
if (!paused) { if (!paused) {
raspberry.update(); raspberry.update();
@ -151,6 +186,7 @@ function update() {
} }
}); });
} }
function checkObstacleReset(obstacle) { function checkObstacleReset(obstacle) {
if (obstacle.position.x < -obstacleWidth) { if (obstacle.position.x < -obstacleWidth) {
obstacle.resetPosition(); obstacle.resetPosition();
@ -159,6 +195,7 @@ function checkObstacleReset(obstacle) {
hasAlreadyScored = false; hasAlreadyScored = false;
} }
} }
function checkRaspberryScore() { function checkRaspberryScore() {
if ((obstacles[0].position.x + obstacles[0].width / 2) < (raspberry.position.x + raspberry.width / 2) if ((obstacles[0].position.x + obstacles[0].width / 2) < (raspberry.position.x + raspberry.width / 2)
&& !hasAlreadyScored) { && !hasAlreadyScored) {
@ -166,6 +203,7 @@ function checkRaspberryScore() {
hasAlreadyScored = true; hasAlreadyScored = true;
} }
} }
function resetScore() { function resetScore() {
if (hasDied) { if (hasDied) {
hasDied = false; hasDied = false;
@ -175,6 +213,7 @@ function resetScore() {
exportToLocalStorage(); exportToLocalStorage();
} }
} }
function keyPressed() { function keyPressed() {
if (!ready) if (!ready)
return; return;
@ -184,11 +223,11 @@ function keyPressed() {
} }
if (key == "Escape") { if (key == "Escape") {
paused = !paused; paused = !paused;
} } else if (paused) {
else if (paused) {
paused = false; paused = false;
} }
} }
var Entity = (function () { var Entity = (function () {
function Entity(position, width, height, fill) { function Entity(position, width, height, fill) {
this.position = position; this.position = position;
@ -197,6 +236,7 @@ var Entity = (function () {
this.fill = fill; this.fill = fill;
this._showHitbox = false; this._showHitbox = false;
} }
Object.defineProperty(Entity.prototype, "position", { Object.defineProperty(Entity.prototype, "position", {
get: function () { get: function () {
return this._position; return this._position;
@ -247,6 +287,7 @@ var Entity = (function () {
}()); }());
var Obstacle = (function (_super) { var Obstacle = (function (_super) {
__extends(Obstacle, _super); __extends(Obstacle, _super);
function Obstacle(position, obstacleWidth, obstacleHeight, image) { function Obstacle(position, obstacleWidth, obstacleHeight, image) {
var _this = _super.call(this, position, obstacleWidth, obstacleHeight, 0) || this; var _this = _super.call(this, position, obstacleWidth, obstacleHeight, 0) || this;
_this.speed = 3; _this.speed = 3;
@ -254,6 +295,7 @@ var Obstacle = (function (_super) {
_this.createPipes(position, obstacleHeight, obstacleWidth, image); _this.createPipes(position, obstacleHeight, obstacleWidth, image);
return _this; return _this;
} }
Object.defineProperty(Obstacle, "startX", { Object.defineProperty(Obstacle, "startX", {
set: function (value) { set: function (value) {
this._startX = value; this._startX = value;
@ -301,11 +343,13 @@ var Obstacle = (function (_super) {
}(Entity)); }(Entity));
var Pipe = (function (_super) { var Pipe = (function (_super) {
__extends(Pipe, _super); __extends(Pipe, _super);
function Pipe(positionX, width, height, image) { function Pipe(positionX, width, height, image) {
var _this = _super.call(this, new Position(positionX, 0), width, height, 0) || this; var _this = _super.call(this, new Position(positionX, 0), width, height, 0) || this;
_this.image = image; _this.image = image;
return _this; return _this;
} }
Pipe.prototype.update = function () { Pipe.prototype.update = function () {
}; };
Pipe.prototype.draw = function () { Pipe.prototype.draw = function () {
@ -327,8 +371,7 @@ var Pipe = (function (_super) {
} }
image(this.image, this.position.x, this.position.y + imageYPosition, this.width, computedImageHeight); image(this.image, this.position.x, this.position.y + imageYPosition, this.width, computedImageHeight);
} }
} } else {
else {
image(this.image, this.position.x, this.position.y, this.width, this.height); image(this.image, this.position.x, this.position.y, this.width, this.height);
} }
}; };
@ -354,6 +397,7 @@ var Position = (function () {
this._x = x; this._x = x;
this._y = y; this._y = y;
} }
Object.defineProperty(Position.prototype, "x", { Object.defineProperty(Position.prototype, "x", {
get: function () { get: function () {
return this._x; return this._x;
@ -378,6 +422,7 @@ var Position = (function () {
}()); }());
var Raspberry = (function (_super) { var Raspberry = (function (_super) {
__extends(Raspberry, _super); __extends(Raspberry, _super);
function Raspberry(image) { function Raspberry(image) {
var _this = this; var _this = this;
Raspberry.position = new Position(width / 6, height / 2); Raspberry.position = new Position(width / 6, height / 2);
@ -391,6 +436,7 @@ var Raspberry = (function (_super) {
_this.image = image; _this.image = image;
return _this; return _this;
} }
Object.defineProperty(Raspberry.prototype, "velocity", { Object.defineProperty(Raspberry.prototype, "velocity", {
get: function () { get: function () {
return this._velocity; return this._velocity;

View file

@ -6,6 +6,8 @@
<script> <script>
import App from "@/App.vue"; import App from "@/App.vue";
import {Rest} from "@/model/Rest";
export default { export default {
name: "Game", name: "Game",
props: { props: {
@ -13,12 +15,13 @@ export default {
}, },
emits: ['gameFinished'], emits: ['gameFinished'],
created() { created() {
window.addEventListener('storage', this.localStorageHandler, false); window.addEventListener('itemInserted', event => this.localStorageHandler(event), false);
}, },
methods: { methods: {
localStorageHandler(event) {
if (event.key !== 'game-isRunning') return;
localStorageHandler() { if (event.value === 'false') { //means game is over
if (localStorage.getItem('game-isRunning') !== 'true') {
let playTime = this.msToHMS(Number(localStorage.getItem('game-playTime'))); let playTime = this.msToHMS(Number(localStorage.getItem('game-playTime')));
let score = Number(localStorage.getItem('game-score')); let score = Number(localStorage.getItem('game-score'));
this.submitGame(score, playTime); this.submitGame(score, playTime);
@ -35,17 +38,17 @@ export default {
const minutes = parseInt(String(seconds / 60)); // 60 seconds in 1 minute const minutes = parseInt(String(seconds / 60)); // 60 seconds in 1 minute
// 4- Keep only seconds not extracted to minutes: // 4- Keep only seconds not extracted to minutes:
seconds = seconds % 60; seconds = seconds % 60;
return hours + ":" + minutes + ":" + seconds; return ((hours < 10) ? "0" : "") + hours + ":" + ((minutes < 10) ? "0" : "") + minutes + ":" + ((seconds < 10) ? "0" : "") + Math.floor(seconds);
}, },
async submitGame(score, playTime) { async submitGame(score, playTime) {
let body = { let body = {
score: score, score: score,
playtime: playTime, playtime: playTime,
date: new Date(), date: new Date().toISOString(),
userId: this.userId, userId: this.userId,
} }
await fetch(App.data().restUrl + '/game/add', {method: 'POST', body: JSON.stringify(body)}); await fetch(Rest.URL + '/game/add', {method: 'POST', body: JSON.stringify(body)});
this.$emit('gameFinished'); this.$emit('gameFinished');
} }
}, },