<!doctype html>
<html>
<head>
<title>Get home</title>
<style>
table {
border-collapse: collapse;
}
td {
border: solid 1px #888;
width: 30px;
height: 30px;
font-family: sans-serif;
font-size: calc(30px/4.0 + 1px);
text-align: center;
}
.cell0 {
background: #88ff99;
}
.cell1 {
background: #116615;
}
.player {
background: #e11;
}
.home {
background: white;
}
.status {
font-size: 15pt;
font-family: Arial;
}
</style>
<script>
// Will be initialised to a 2-dimensional array
var gameBoard = [];
// Size of game
var size = 10;
// Current fuel and supply
var fuel = 20;
var supply = 0;
// Current position of player (start in the bottom-right)
var positionX = size - 1;
var positionY = size - 1;
// Whether we are playing the game
var playing = true;
// Use this function to make a move where x and y represent the direction of
// a move, e.g.
// move(-1, 0) means going left
// move(1, 0) means going right
// move(0, -1) means going up
// move(0, 1) means going down
function move(x, y) {
//
if (positionX + x < size && positionX + x >= 0 &&
positionY + y < size && positionY + y >= 0) {
// Move is within the board
}
}
// Use this function to update the status
function updateStatus() {
document.getElementById("fuel").innerHTML = fuel;
document.getElementById("store").innerHTML = supply;
}
function setup() {
// Set the gameboard to be empty
gameBoard = [];
var board = document.getElementById("board");
for (var i = 0; i < size; i++) {
// Create a new row of the game
var htmlRow = document.createElement("tr");
board.appendChild(htmlRow);
var row = []
for (var j = 0; j < size; j++) {
// Chose a random type of cell
var type = Math.round(Math.random());
var cell = document.createElement("td");
cell.className = "cell" + type;
// Add the cell to the row
htmlRow.appendChild(cell);
row.push(cell);
}
gameBoard.push(row);
}
// Setup the player
gameBoard[size-1][size-1].className = "player";
// Setup the home
gameBoard[0][0].className = "home";
gameBoard[0][0].innerHTML = "HOME";
// Register the listener and update the state
updateStatus();
document.body.addEventListener("keydown", keyEvent);
}
</script>
</head>
<body onLoad="setup();">
<div class="status">Fuel: <span id="fuel"></div>
<div class="status">Store: <span id="store"></div>
<table id="board"></table>
<div class="status" id="outcome"></div>
</body>
</html>
I'm creating a simple game on HTML, and I can't think of how to get the move function to work, while it automatically updates the game and the map, is anyone able to help. I'm new to coding and I genuinely cant fathom what code to put in to make the move function work, whether it be using arrow keys or creating buttons to make the entity move.
Without making too many changes to the way you have things set up, I added a function that will add the "player" class to elements based on "wsad" or arrow key presses.
<!doctype html>
<html>
<head>
<title>Get home</title>
<style>
table {
border-collapse: collapse;
}
td {
border: solid 1px #888;
width: 30px;
height: 30px;
font-family: sans-serif;
font-size: calc(30px/4.0 + 1px);
text-align: center;
}
.cell0 {
background: #88ff99;
}
.cell1 {
background: #116615;
}
.player {
background: #e11;
}
.home {
background: white;
}
.status {
font-size: 15pt;
font-family: Arial;
}
</style>
<script>
// Will be initialised to a 2-dimensional array
var gameBoard = [];
// Size of game
var size = 10;
// Current fuel and supply
var fuel = 20;
var supply = 0;
// Current position of player (start in the bottom-right)
var positionX = size - 1;
var positionY = size - 1;
// Whether we are playing the game
var playing = true;
function move(direction) {
let x = positionX;
let y = positionY;
switch (direction) {
case "left":
x--;
break;
case "right":
x++;
break;
case "up":
y--;
break;
case "down":
y++;
break;
}
const validMove =
x < size &&
x >= 0 &&
y < size &&
y >= 0;
if (!validMove) return console.error(
"What are you trying to do?" + "\n" +
"Break the implied rules of a game?" + "\n" +
"I expect more from you" + "\n" +
"That's a wall you dummy!"
);
positionX = x;
positionY = y;
gameBoard[y][x].classList.add("player");
}
// Use this function to update the status
function updateStatus() {
document.getElementById("fuel").innerText = fuel;
document.getElementById("store").innerText = supply;
}
function keyEvent(e) {
const keyMoveDict = {
"ArrowLeft": "left",
"ArrowRight": "right",
"ArrowUp": "up",
"ArrowDown": "down",
"a": "left",
"d": "right",
"w": "up",
"s": "down",
}
const movement = keyMoveDict[e.key];
if (movement) move(movement);
}
function setup() {
// Set the gameboard to be empty
gameBoard = [];
var board = document.getElementById("board");
for (var i = 0; i < size; i++) {
// Create a new row of the game
var htmlRow = document.createElement("tr");
board.appendChild(htmlRow);
var row = []
for (var j = 0; j < size; j++) {
// Chose a random type of cell
var type = Math.round(Math.random());
var cell = document.createElement("td");
cell.className = "cell" + type;
// Add the cell to the row
htmlRow.appendChild(cell);
row.push(cell);
}
gameBoard.push(row);
}
// Setup the player
gameBoard[size-1][size-1].className = "player";
// Setup the home
gameBoard[0][0].className = "home";
gameBoard[0][0].innerHTML = "HOME";
// Register the listener and update the state
updateStatus();
document.body.addEventListener("keydown", keyEvent);
}
</script>
</head>
<body onLoad="setup();">
<div class="status">Fuel: <span id="fuel"></span></div>
<div class="status">Store: <span id="store"></span></div>
<table id="board"></table>
<div class="status" id="outcome"></div>
</body>
</html>
I only started my way to JavaScript development. I'm trying to complete a task from the book for kids and I'm stuck in the following:Task description is here
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Interactive programming</title>
</head>
<body>
<h1 id="heading">Hello, world!</h1>
<script src="https://code.jquery.com/jquery-2.1.0.js"></script>
<script>
var leftOffset = 0;
var topOffset = 0;
var max = 200;
var moveHeading = function () {
var currentDirection;
if (!currentDirection || currentDirection === topOffset) {
for (var i = 0; i < max; i++) {
$("#heading").offset({left: leftOffset});
leftOffset++;
}
currentDirection = leftOffset;
}
if (currentDirection === leftOffset) {
for (var i = 0; i < max; i++) {
$("#heading").offset({top: topOffset});
topOffset++;
}
currentDirection = topOffset;
}
if (currentDirection === topOffset) {
for (var i = 0; i < max; i++) {
$("#heading").offset({left: leftOffset});
leftOffset--;
}
currentDirection = leftOffset;
}
if (currentDirection === leftOffset) {
for (var i = 0; i < max; i++) {
$("#heading").offset({top: topOffset});
topOffset--;
}
currentDirection = topOffset;
}
};
setInterval(moveHeading, 30);
</script>
</body>
</html>
The problem is that under debugging I do see how it moves from side to side in a form of square, but when I open the page in a browser tab(without opening DevTools), it doesn't move like it is requested in the Task. What am I missing here?
We can make this way better. But for now :)
<!DOCTYPE html>
<html>
<body>
<h1 id="heading">Hello, world!</h1>
<script src="https://code.jquery.com/jquery-2.1.0.js"></script>
<script>
var leftOffset = 0;
var topOffset = 0;
var max = 200;
var counter = 0;
var currentDirection = "right";
var moveHeading = function() {
if (currentDirection === "right") {
$("#heading").offset({
left: leftOffset
});
leftOffset++;
if (counter === max) {
currentDirection = "bottom";
counter = 0;
}
}
if (currentDirection === "bottom") {
$("#heading").offset({
top: topOffset
});
topOffset++;
if (counter === max) {
currentDirection = "left";
counter = 0;
}
}
if (currentDirection === "left") {
$("#heading").offset({
left: leftOffset
});
leftOffset--;
if (counter === max) {
currentDirection = "top";
counter = 0;
}
}
if (currentDirection === "top") {
$("#heading").offset({
top: topOffset
});
topOffset--;
if (counter === max) {
currentDirection = "right";
counter = 0;
}
}
counter++;
};
setInterval(moveHeading, 5);
</script>
</body>
</html>
but you can write this more compact and clean like this:
<!DOCTYPE html>
<html>
<body>
<h1 id="heading">Hello, world!</h1>
<script src="https://code.jquery.com/jquery-2.1.0.js"></script>
<script>
let max = 200,
counter = 0,
x = [1, 0, -1, 0],
y = [0, 1, 0, -1],
idx = 0,
el = $("#heading"),
l = 0,
t = 0,
move = () => {
l += x[idx];
t += y[idx];
el.offset({
left: l,
top: t
});
},
moveHeading = () => {
if (counter++ < max) {
move();
return;
}
idx++;
if (idx > 3) idx = 0;
counter = 0;
moveHeading();
};
setInterval(moveHeading, 5);
</script>
</body>
</html>
I have a bug in this code somewhere that cause the ship to fly faster and faster in space after returning from the planet. I cant figure this one out.
I set the speed to 0.1 so that its super slow in space. When you click on the planet, i run a function that will move canvas's off screen and use zindex to brong a div tag to the top of the stack. When you land and return to orbit, the ship will move slightly faster. After doing it about 10-15 times the ship moves far greater than the 0.1 speed that is set. I will include the html, js and css so you can run it to test.
Here is the whole code.
// Canvas Context's
var canvasMS = document.getElementById('MainScreen_cvs');
var ctxMain = canvasMS.getContext('2d');
var canvasShip = document.getElementById('Ship_cvs');
var ctxShip = canvasShip.getContext('2d');
var PlanetDiv = document.getElementById('PlanetDiv');
var OrbitReturn = document.getElementById('OrbitReturn');
var canvasPlanets = document.getElementById('Planets_cvs');
var ctxPlanets = canvasPlanets.getContext('2d');
var canvasHUD = document.getElementById('HUD_cvs');
var ctxHUD = canvasHUD.getContext('2d');
var canvasSurface = document.getElementById('Surface_cvs');
var ctxSurface = canvasSurface.getContext('2d');
// ----------------------------------End Canvas Context
var Player1;
var Planet1;
var planetClicked;
var gameWidth = canvasMS.width;
var gameHeight = canvasMS.height;
var mouseX = 10000;
var mouseY = 10000;
var SpaceMapX = 10;
var SpaceMapY = 10;
var SurfaceMap = 0;
var SurfaceMap2 = -1600;
var inSpace = true;
var onSurface = false;
var requestAnimFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame;
// Load Images
var imgMap = new Image();
imgMap.src = 'images/bg1.png';
var imgButtons = new Image();
imgButtons.src = 'images/button_sprite.png';
var imgBlueWindow = new Image();
imgBlueWindow.src = 'images/blue_window.png';
var imgSprite = new Image();
imgSprite.src = 'images/sprite.png';
var imgPlanets = new Image();
imgPlanets.src = 'images/earthlike_p1.png';
var imgBluesky1 = new Image();
imgBluesky1.src = 'images/bluesky1.png';
var imgBluesky2 = new Image();
imgBluesky2.src = 'images/bluesky2.png';
imgMap.addEventListener('load',init,false);
// ------------- End Loading Images
//-------------------- Create Game Objects ----------------
function CreateGameObjects(){
Player1 = new Ship();
Planet1 = new Planet();
};
//---------------END CREATING GAME OBJECTS------------------
function init(){ //----------------------------------------------- GAME INITIALIZATION
document.addEventListener('keydown',checkKeyDown,false);
document.addEventListener('keyup',checkKeyUp,false);
document.addEventListener("mousedown", checkMouseDown, false);
document.addEventListener("mouseup", checkMouseUp, false);
CreateGameObjects();
Loop();
};
function Loop() { // ---------------- Main Game Loop
clearCtx();
DrawGameObjects();
requestAnimFrame(Loop);
};
function planetSurface(){
if(onSurface){
clearCtx();
HUD();
Player1.draw();
if(mouseY < 21 && mouseX > 693){
ReturntoOrbit();
}
planetClicked.drawSurfaceImg();
var CloseButton = '<button style="float:right;" type="button">Return to Orbit</button>' ;
OrbitReturn.innerHTML = CloseButton;
requestAnimFrame(planetSurface);
}
};
function DrawGameObjects(){
Player1.draw();
Planet1.draw();
HUD();
};
function HUD(){
canvasHUD.style.zIndex = "100";
if (onSurface){
ctxHUD.fillStyle = "#000";
ctxHUD.fillText("locSurface: " + planetClicked.locSurface, 20,30);
}
if (inSpace)
ctxHUD.fillStyle = "#fff";
ctxHUD.fillText("Speed: " + Player1.speed, 60,60);
ctxHUD.fillText("drawX: " + Player1.drawX, 600,40);
ctxHUD.fillText("drawY: " + Player1.drawY, 600,30);
// ctxHUD.fillText("Planet Clicked: " + Planet1.isClicked, 600,50);
}
//----------------------------------------------------------- Objects
/************************************************************************************/
//--------------------------------- SPACE SHIP --------------------------------------
function Ship(){
this.srcX = 0;
this.srcY = 0;
this.srcW = 60;
this.srcH = 60;
this.drawX = 20 ;
this.drawY = 50 ;
this.speed = 0;
this.surfaceSpeed = 10;
this.drift = 0.45;
this.w = 16;
this.h = 16;
this.isUpKey = false;
this.isDownKey = false;
this.isLeftKey = false;
this.isRightKey = false;
this.isSpacebar = false;
this.direction = "n/a";
this.isMoving = false;
this.isClicked = false;
this.surfX = 350;
this.surfY = 200;
};
Ship.prototype.draw = function() {
if(inSpace)
ctxShip.drawImage(imgSprite,this.srcX,this.srcY,this.srcW,this.srcH,this.drawX,this.drawY,this.w,this.h);
if(onSurface)
ctxShip.drawImage(imgSprite,this.srcX,this.srcY,this.srcW,this.srcH,this.surfX,this.surfY,this.w,this.h);
this.checkPos(planetClicked);
};
Ship.prototype.checkPos = function (PlanetX){
if(inSpace){
this.srcY = 0;
this.srcW = 60;
this.w = 16;
this.h = 16;
this.speed = 0.1;
//----------------------------- Move Ship and Map based on the speed of the ship.
if(this.isLeftKey){
this.drawX -= this.speed;
if(SpaceMapX >= 1){
SpaceMapX -= this.speed;
}
}
if(this.isRightKey){
this.drawX += this.speed;
if(SpaceMapX <= 2190)SpaceMapX += this.speed;
}
if(this.isDownKey){
this.drawY += this.speed;
if(SpaceMapY <= 2490)SpaceMapY += this.speed;
}
if (this.isUpKey) {
this.drawY -= this.speed;
if(SpaceMapY >= 1){
SpaceMapY -= this.speed;
}
}
if (SpaceMapY < 0) {SpaceMapY = 0;}
if (SpaceMapX < 0 ) {SpaceMapX = 0}
//--------------------------------------------------------------------END
//-----------------------------------Change Ship Graphic based on direction and map boundaries.
if(this.isUpKey) this.srcX = 360;
if(this.isDownKey) this.srcX = 120;
if(this.isLeftKey) this.srcX = 240;
if(this.isRightKey) this.srcX = 0;
if(this.isUpKey && this.isLeftKey) this.srcX = 300;
if(this.isUpKey && this.isRightKey) this.srcX = 420;
if(this.isDownKey && this.isLeftKey) this.srcX = 180;
if(this.isDownKey && this.isRightKey) this.srcX = 60;
if (this.drawX <= 5) this.drawX = 5;
if (this.drawY <= 5) {this.drawY = 5};
if (this.drawY >= 480) {this.drawY = 480};
if (this.drawX >= 780) {this.drawX = 780};
//----------------------------------------------------------------END
ctxMain.drawImage(imgMap,SpaceMapX,SpaceMapY,gameWidth,gameHeight,0,0,gameWidth,gameHeight);
}
if (onSurface) {
this.srcY = 240;
this.srcW = 92;
this.w = 93;
this.h = 60;
if(this.isLeftKey){
PlanetX.locSurface -= this.surfaceSpeed;
SurfaceMap += this.surfaceSpeed;
SurfaceMap2 += this.surfaceSpeed;
PlanetX.MapDirection = -1;
this.srcX = 93;
}
if(this.isRightKey){
PlanetX.locSurface += this.surfaceSpeed;
SurfaceMap -= this.surfaceSpeed;
SurfaceMap2 -= this.surfaceSpeed;
PlanetX.MapDirection = 1;
this.srcX = 0;
}
}
};
//------------------------------END OF SPACE SHIP ------------------------------------
//----------------------------- PLANET OBJECT INFO ------------------------------------
function Planet(){
this.srcX = 0;
this.srcY = 0;
this.srcW = 100;
this.srcH = 100;
this.w = 50;
this.h = 50;
this.coordX = 100;
this.coordY = 100;
this.planetType = "Small Earthlike Planet."
this.drawX = this.coordX - SpaceMapX;
this.drawY = this.coordY - SpaceMapY;
this.surfaceIMG = imgBluesky1;
this.isClicked = false;
this.locSurface = 0;
};
Planet.prototype.draw = function(){
this.drawX = this.coordX - SpaceMapX;
this.drawY = this.coordY - SpaceMapY;
ifClicked(this);
if(this.isClicked){
PlanetDiv.style.display = "block";
var LandPlanetDivButton = '<button id="LandPlanetDivButton" type="button" onclick="landOnSurface();">Land On Surface</button>';
var ClosePlanetDivButton = '<button id="ClosePlanetDivButton" type="button" onclick="ClosePlanetDiv();">Close (x)</button><br/><p id="PlanetDivText">' ;
PlanetDiv.style.zIndex = "2";
HideCanvas();
planetClicked = this;
PlanetDiv.innerHTML = LandPlanetDivButton + ClosePlanetDivButton + this.planetType; + '</p>';
}
ctxPlanets.drawImage(imgPlanets,this.srcX,this.srcY,this.srcW,this.srcH,this.drawX,this.drawY,this.w,this.h);
};
Planet.prototype.drawSurfaceImg = function(){
if(SurfaceMap2 >= 0) SurfaceMap2 = -1600;
if(SurfaceMap2 < -1600) SurfaceMap2 = -1;
if(SurfaceMap >= 1600) SurfaceMap = 0;
if(SurfaceMap < 0) SurfaceMap = 1599;
ctxSurface.drawImage(this.surfaceIMG, 0, 0, 1600, gameHeight, SurfaceMap, 0, 1600, gameHeight);
ctxSurface.drawImage(this.surfaceIMG, 0, 0, 1600, gameHeight, SurfaceMap2, 0, 1600, gameHeight);
};
//----------------------------- END OF PLANET OBJECT -----------------------------------
//-----end Objects
function randomFromTo(from,to){
return Math.floor(Math.random()*(to-from+1)+from);
};
function closestNum(Num, a){
var num = Num + (gameWidth/2);
var closest = a[0];
var difference = Math.abs (num - closest);
for (var i = 0; i < a.length; i++) {
var difference2 = Math.abs (num - a[i]);
if (difference2 < difference) {
difference = difference2;
closest = a[i];
}
}
return closest;
};
function sortNum(a)
{
var swapped;
do{
swapped = false;
for (var i=0; i < a.length-1; i++) {
if (a[i] > a[i+1]) {
var temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
swapped = true;
}
}
}while (swapped);
};
function ifClicked(obj){
if(mouseX >= obj.drawX && mouseX <= obj.drawX + obj.w){
if(mouseY >= obj.drawY && mouseY <= obj.drawY + obj.h){
obj.isClicked = true;
}
}
else{
obj.isClicked = false;
}
};
function clearCtx() {
ctxMain.clearRect(0,0,gameWidth,gameHeight);
ctxShip.clearRect(0,0,gameWidth,gameHeight);
ctxPlanets.clearRect(0,0,gameWidth,gameHeight);
ctxHUD.clearRect(0,0,gameWidth,gameHeight);
ctxSurface.clearRect(0,0,gameWidth,gameHeight);
};
function checkKeyDown(e){
var keyID = e.keyCode || e.which;
if(keyID === 38 || keyID === 87){ // up arrow or W key
Player1.isUpKey = true;
Player1.direction = "North";
Player1.isMoving = true;
e.preventDefault();
}
if(keyID === 39|| keyID === 68){ // right arrow or D key
Player1.isRightKey = true;
Player1.direction = "East"
Player1.isMoving = true;
e.preventDefault();
}
if(keyID === 40 || keyID === 83){ // down arrow or S key
Player1.isDownKey = true;
Player1.direction = "South";
Player1.isMoving = true;
e.preventDefault();
}
if(keyID === 37 || keyID === 65){ // left arrow or A key
Player1.isLeftKey = true;
Player1.direction = "West";
Player1.isMoving = true;
e.preventDefault();
}
};
function checkKeyUp(e){
var keyID = e.keyCode || e.which;
if(keyID === 38 || keyID === 87){ // up arrow or W key
Player1.isUpKey = false;
Player1.isMoving = false;
e.preventDefault();
}
if(keyID === 39|| keyID === 68){ // right arrow or D key
Player1.isRightKey = false;
Player1.isMoving = false;
e.preventDefault();
}
if(keyID === 40 || keyID === 83){ // down arrow or S key
Player1.isDownKey = false;
Player1.isMoving = false;
e.preventDefault();
}
if(keyID === 37 || keyID === 65){ // left arrow or A key
Player1.isLeftKey = false;
Player1.isMoving = false;
e.preventDefault();
}
};
function clearMouse(){
mouseX = 10000;
mouseY = 10000;
};
function checkMouseDown(e) {
var mX = (e.clientX - (canvasMS.offsetLeft - canvasMS.scrollLeft));
var mY = (e.clientY - (canvasMS.offsetTop - canvasMS.scrollTop));
if(mX <= gameWidth && mX >= 0) mouseX = mX;
if(mY <= gameHeight && mY >= 0) mouseY = mY;
//mouseIsDown = true;
};
function checkMouseUp(e){
//mouseIsDown = false;
clearMouse();
};
function ClosePlanetDiv (){
PlanetDiv.style.zIndex = "-2";
PlanetDiv.innerHTML = "";
PlanetDiv.style.display = "none";
ShowCanvas();
};
function HideCanvas(){
canvasShip.style.marginTop = "-10000px";
canvasPlanets.style.marginTop = "-10000px";
};
function ShowCanvas(){
canvasShip.style.marginTop = "-500px";
canvasPlanets.style.marginTop = "-500px";
};
function landOnSurface(){
ClosePlanetDiv();
inSpace = false;
onSurface = true;
Player1.srcX = 0;
planetSurface();
canvasSurface.style.display = "block";
OrbitReturn.style.display = "block";
};
function ReturntoOrbit(){
OrbitReturn.style.display = "none";
canvasSurface.style.display = "none";
inSpace = true;
onSurface = false;
Loop();
};
<!doctype html>
<html lang='en'>
<head>
<meta charset="utf-8">
<title>Space Explorer</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="Functions.js"></script>
</head>
<body>
<canvas id="MainScreen_cvs" width="800" height="500"></canvas>
<div id="PlanetDiv"></div>
<canvas id="Surface_cvs" width="800" height="500"></canvas>
<canvas id="Ship_cvs" width="800" height="500"></canvas>
<canvas id="Planets_cvs" width="800" height="500"></canvas>
<canvas id="HUD_cvs" width="800" height="500"></canvas>
<div id="OrbitReturn"></div>
<div id="log">
<h1 style="color:blue;">Recent updates will be logged here when made live.</h1>
<hr />
<h3> Wednesday August 3, 2016 </h3>
<ul>
<li> HTML file completed. Working on getting JS files started.</li>
<li> JS files created. </li>
<li>Basic ship & flight functions in place. Basic star map initialized.</li>
</ul>
<hr />
</div>
<script type="text/javascript" src="game.js"></script>
</body>
</html>
body {
background: #303030;
}
#MainScreen_cvs {
position: relative;
display: block;
background: #777777 ;
margin: 30px auto 0px;
z-index: 1;
}
#Surface_cvs{
position: relative;
display: none;
z-index: 1;
margin: -500px auto 0px;
}
#Ship_cvs, #Planets_cvs, #HUD_cvs {
display: block;
position: relative;
margin: -500px auto 0px;
z-index: 1;
}
#log {
display: block;
position: absolute;
top: 560px;
left: 233px;
background: #ffffff;
overflow: scroll;
width: 800px;
height: 300px;
z-index: 3;
}
#OrbitReturn{
display: block;
position: relative;
width: 800px;
height: 500px;
z-index: 3;
margin: -500px auto 0px;
}
#PlanetDiv {
display: block;
position: relative;
width: 800px;
height: 500px;
background-image: url("images/Sky.jpg");
z-index: -2;
margin: -500px auto 0px;
}
#ClosePlanetDivButton{
float: right;
}
#LandPlanetDivButton{
position: absolute;
top: 400px;
left: 325px;
font-size: 20px;
}
#PlanetDivText{
text-indent: 50px;
font-size: 20px;
}
Something is happening with Ship.prototype.checkPos. Each time you land on the planet, it looks like the checking pauses, then starts up when you enter orbit. But this time he checkPos is getting called faster.
I could keep staring at it but you might be able to figure it out from there. I put a console.log('checkPos') at the top of that function and watched it pause and restart.
Ship.prototype.checkPos = function(PlanetX) {
console.log('checkPos');
if (inSpace) {
...
I think it might be here
function ReturntoOrbit() {
OrbitReturn.style.display = "none";
canvasSurface.style.display = "none";
inSpace = true;
onSurface = false;
//Loop(); <--- this little guy. Get rid of him.
};
I have somewhat of a baseball game, obviously there are not bases or hits. Its all stikes, balls and outs. The buttons work and the functionality of the inning (top and bottom as well as count) are working. I want this to ideally randomly throw a pitch on its own every few seconds. Basically to randomly "click" the ball or strike button. I am trying to use the setTimeout function with no success. Any help?
HTML:
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css" href="bullpen.css">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Bullpen</title>
</head>
</html>
<body>
<button id=buttons onclick="playBall()">Auto-Play</button>
<h2>Inning: <span id=inningHalf></span> <span id=inningNum></span></h2>
<div id=buttons>
<button onclick="throwBall(), newInning()">Ball</button>
<button onclick="throwStrike(), newInning()">Strike</button>
</div>
<h2>Count: <span id=ball>0</span> - <span id=strike>0</span></h2>
<h2>Outs: <span id=out>0</span></h2>
<h2>----------------</h2>
<h2>Walks: <span id=walks>0</span></h2>
<h2>Strikeouts: <span id=strikeout>0</span></h2>
<script src="bullpen.js"></script>
</body>
</html>
JS:
var ball = 0;
var strike = 0;
var out = 0;
var walks = 0;
var strikeout = 0;
//---------------------------------
var outPerInning = 0;
var inning = 1;
//---------------------------------
document.getElementById('inningNum').innerHTML = inning;
document.getElementById('inningHalf').innerHTML = '▲';
function throwBall(){
ball++;
document.getElementById('ball').innerHTML = ball;
if (ball == 4){
ball = 0;
strike = 0;
walks++;
document.getElementById('walks').innerHTML = walks;
document.getElementById('strike').innerHTML = 0;
document.getElementById('ball').innerHTML = 0;
}
};
function throwStrike(){
strike++;
document.getElementById('strike').innerHTML = strike;
if(strike == 3){
ball = 0;
strike = 0;
strikeout++;
out++;
outPerInning++;
document.getElementById('strikeout').innerHTML = strikeout;
document.getElementById('out').innerHTML = out;
document.getElementById('strike').innerHTML = 0;
document.getElementById('ball').innerHTML = 0;
}
};
function newInning(){
if(out == 3){
ball=0;
strike=0;
out=0;
document.getElementById('strike').innerHTML = 0;
document.getElementById('ball').innerHTML = 0;
document.getElementById('out').innerHTML = 0;
}
if(outPerInning == 3){
document.getElementById('inningHalf').innerHTML = '▼';
}
if(outPerInning == 6){
inning++;
document.getElementById('inningHalf').innerHTML = '▲';
outPerInning = 0;
document.getElementById('inningNum').innerHTML = inning;
}
};
function playBall(){
var play = Math.random;
if(play >= 0.4){
throwStrike();
newInning();
}
else{
throwBall();
newInning();
}
setTimeout(playBall, 5000);
};
CSS if needed:
h2{
margin-left: 50px;
font-size: 50px;
}
button{
font-size: 45px;
}
#buttons{
width: 227px;
margin-left:50px;
margin-top: 20px;
}
Perhaps this is the problem:
function playBall(){
var play = math.random;
if(play >= 0.4){
throwStrike;
newInning();
}
else{
throwBall;
newInning();
}
setTimeout(playBall, 5000);
};
Should be
function playBall(){
var play = Math.random();
if(play >= 0.4){
throwStrike(); //call the function
newInning();
}
else{
throwBall(); //call the function
newInning();
}
setTimeout(playBall, 5000);
};
You were not calling these functions!
Here is a working fiddle: https://jsfiddle.net/av6vsp7g/
After following two YouTube lessons, I now have a nice arrow widget that fades in, rotates to 180 degrees and fades out controlled from one button. I do not know how to make the arrow rotate back to 0 on the second click of this button.
Probably not the most elegant of code, but here we are:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Fade In and Out</title>
<style type="text/css">
div.contentbox {
width: 50px;
height: 50px;
padding: 20px;
opacity: 0;
}
</style>
<script type="text/javascript">
var fade_in_from = 0;
var fade_out_from = 10;
function fadeIn(element) {
var target = document.getElementById(element)
target.style.display = "block";
var newSetting = fade_in_from / 10;
target.style.opacity = newSetting;
fade_in_from++;
if(fade_in_from == 10) {
target.style.opacity = 1;
clearTimeout(loopTimer);
fade_in_from = 0;
return false;
}
var loopTimer = setTimeout('fadeIn(\''+element+'\')', 50);
}
function fadeOut(element) {
var target = document.getElementById(element)
var newSetting = fade_out_from / 10;
target.style.opacity = newSetting;
fade_out_from--;
if(fade_out_from == 0) {
target.style.opacity = 0;
clearTimeout(loopTimer);
fade_out_from = 10;
return false;
}
var loopTimer = setTimeout('fadeOut(\''+element+'\')', 50);
}
var looper;
var degrees = 0;
function rotateAnimation(el,speed)
{
var elem = document.getElementById(el);
if(navigator.userAgent.match("Chrome")){
elem.style.WebkitTransform = "rotate("+degrees+"deg)";
} else if(navigator.userAgent.match("Firefox")){
elem.style.MozTransform = "rotate("+degrees+"deg)";
} else if(navigator.userAgent.match("MSIE")){
elem.style.msTransform = "rotate("+degrees+"deg)";
} else if(navigator.userAgent.match("Opera")){
elem.style.OTransform = "rotate("+degrees+"deg)";
} else {
elem.style.transform = "rotate("+degrees+"deg)";
}
looper = setTimeout ('rotateAnimation(\''+el+'\','+speed+')',speed);
degrees++;
if(degrees > 179){
clearTimeout(looper)
}
}
</script>
</head>
<body>
<button onmouseover="fadeIn('arrow_box')": onmouseout="fadeOut('arrow_box')": onclick="rotateAnimation('arrow',5)">fade in/out</button>
<div id="arrow_box" class="contentbox"><img id="arrow" img src="images/Arrow.png" width="50" height="50" alt="Arrow" /></div>
</body>
</html>
Please help.
Create a new variable to remember the direction and then increment or decrement the degrees depending on which direction you want to go.
Here is a JSfiddle link of a working solution.
var looper;
var degrees = 0;
var direction = 0;
function rotateAnimation(el,speed){
var elem = document.getElementById(el);
if(navigator.userAgent.match("Chrome")){
elem.style.WebkitTransform = "rotate("+degrees+"deg)";
}else if(navigator.userAgent.match("Firefox")){
elem.style.MozTransform = "rotate("+degrees+"deg)";
}else if(navigator.userAgent.match("MSIE")){
elem.style.msTransform = "rotate("+degrees+"deg)";
}else if(navigator.userAgent.match("Opera")){
elem.style.OTransform = "rotate("+degrees+"deg)";
}else {
elem.style.transform = "rotate("+degrees+"deg)";
}
looper = setTimeout
('rotateAnimation(\''+el+'\','+speed+')',speed);
if(direction === 0){
degrees++;
if(degrees > 179){
direction = 1;
clearTimeout(looper);
}
}else {
degrees--;
if(degrees < 1){
direction = 0;
clearTimeout(looper);
}
}
}