css word-spacing with mutiple characters - javascript

I want all the numbers to be in the center of the boxes ,I am curently using word-spacing but that dont work beacuse the numbers with 2 characters take up more space then the rest of the numbers. I have tried to add a space to the numbers with 1 character ("1 ") ("11") so it looks like that, but that dont work either.
$(document).ready(function () {
$("#roll").click(function () {
document.getElementById("roll").disabled = true;
document.getElementById("re").disabled = true;
document.getElementById("bl").disabled = true;
document.getElementById("winner").innerHTML = "";
var arr = [];
var r = Math.floor(Math.random() * 17) + 1
var moveTime;
if (r == '4') { //4 red
moveTime = 8390;
} else if (r == '15') { //0 green
moveTime = 8265;
} else if (r == '11') { //11 red
moveTime = 8140;
} else if (r == '5' || r == '16') { //5 black
moveTime = 8015;
r = 5;
} else if (r == '10') { //10 red
moveTime = 7890;
} else if (r == '6') { //6 black
moveTime = 7765;
} else if (r == '9') { //9 red
moveTime = 7640;
} else if (r == '7') { //7 black
moveTime = 7515;
} else if (r == '8') { //8 red
moveTime = 7390;
} else if (r == '1' || r == '17') { //1 black
moveTime = 7265;
r = 1;
} else if (r == '14') { //14 red
moveTime = 7140;
} else if (r == '2') { //2 black
moveTime = 7015;
} else if (r == '13') { //13 red
moveTime = 6890;
} else if (r == '3') { //3 black
moveTime = 6765;
} else if (r == '12') { //12 red
moveTime = 6640;
}
var slowDown = 10000000;
var $div = $('div').css('left', 0);
while (moveTime > 0) {
slowDown--;
arr.push($('div').animate({
left: moveTime + "px"
}, 3000).promise());
({
}, 3000);
if (slowDown > 0) {
slowDown--;
moveTime = 0;
}
slowDown--;
moveTime--;
}
Promise.all(arr).then(function () {
if (r == '1' || r == '3' || r == '2' || r == '7' || r == '6' || r == '5') {
var g = document.getElementById("prev").innerHTML;
var h = document.getElementById("prevnum").innerHTML;
g = g.substr(15);
document.getElementById("winner").innerHTML = "Black" + r + " won!";
var betcol = document.getElementById("betc").innerHTML;
if (betcol == "black") {
var betamount = document.getElementById("betamount").value;
var balance = document.getElementById("balance").innerHTML;
balance = balance.substr(9);
var sum = +balance + +betamount;
document.getElementById("balance").innerHTML = "Balance: " + sum;
} else {
var betamount = document.getElementById("betamount").value;
var balance = document.getElementById("balance").innerHTML;
balance = balance.substr(9);
var sum = +balance - +betamount;
document.getElementById("balance").innerHTML = "Balance: " + sum;
}
//document.getElementById("prev").innerHTML = "Previous rolls:" + " <img src=http://319scholes.org/wp-content/uploads/2012/01/jeremiah1.jpg> " + g;
if (r < 10){
//r = '<span class="black">'r'</span>'
}
document.getElementById("prevnum").innerHTML = '<span class="black">'+ r + '</span>' + " " + h;
} else if (r == '4'|| r == '11' || r == '10' || r == '9' || r == '8' || r == '14' || r == '12' || r == '13') {
var g = document.getElementById("prev").innerHTML;
var h = document.getElementById("prevnum").innerHTML;
g = g.substr(15);
document.getElementById("winner").innerHTML = "Red" + r + " won!";
var betcol = document.getElementById("betc").innerHTML;
if (betcol == "red") {
var betamount = document.getElementById("betamount").value;
var balance = document.getElementById("balance").innerHTML;
balance = balance.substr(9);
var sum = +balance + +betamount;
document.getElementById("balance").innerHTML = "Balance: " + sum;
} else {
var betamount = document.getElementById("betamount").value;
var balance = document.getElementById("balance").innerHTML;
balance = balance.substr(9);
var sum = +balance - +betamount;
document.getElementById("balance").innerHTML = "Balance: " + sum;
}
// document.getElementById("prev").innerHTML = "Previous rolls:" + " <img src=http://www.clker.com/cliparts/X/C/L/8/R/Z/red-box-hi.png> " + g;
if (r < 10){
// r = '<span class="red">'r'</span>'
}
document.getElementById("prevnum").innerHTML = '<span class="red">'+ r + '</span>' + " " + h;
}
document.getElementById("roll").disabled = false;
document.getElementById("re").disabled = false;
document.getElementById("bl").disabled = false;
});
});
});
$(document).ready(function () {
$("#re").click(function () {
document.getElementById("betc").innerHTML = "red";
});
});
$(document).ready(function () {
$("#bl").click(function () {
document.getElementById("betc").innerHTML = "black";
});
});
#game {
position: absolute;
float: left;
margin: 170px 0 0 -8400px;
width: 10000px;
height: 125px;
background: repeating-linear-gradient(90deg, #DF0000, #DF0000 125px, #000000 125px, #000000 250px);
}
#game h3{
text-align: center;
position: absolute;
margin: 27px 50px 0 -12px;
/* padding: 0 0 0 0; */
width: 10000px;
font-size: 60px;
color: white;
overflow: visible;
word-spacing: 70px;
}
span.green {
background-size: 125px 125px;
background-color: #2dde2d;
}
h1 {
text-align: center;
margin: 130px 0 0 0;
font-size: 90px;
}
#arr{
position: absolute;
margin: 130px -28px 0 48.2%;
transform: rotate(90deg);
}
h2 {
text-align: center;
font-size: 60px;
margin: 500px 0 0 0;
}
h3 {
font-size: 40px;
}
body {
overflow-x: hidden;
background-image: url(http://www.casino-capers.org/wp/wp-content/uploads/2015/01/Casino-Capers-Web-Background-2015.jpg);
}
button {
width: 300px;
height: 100px;
font-size: 20px;
margin: 350px 0 0 40%;
position: absolute;
}
#re {
width: 100px;
height: 100px;
font-size: 20px;
margin: 350px 0 0 30%;
background-color: red;
position: absolute;
}
#bl {
width: 100px;
height: 100px;
font-size: 20px;
margin: 350px 0 0 62%;
background-color: black;
color: white;
position: absolute;
}
#balance{
font-size: 50px;
margin: 80px 0 0 1%;
position: absolute;
}
#betc{
height: 0px;
width: 0px;
position: absolute;
font-size: 0px;
}
#betamount{
font-size: 25px;
margin: 0 0 0 10%;
position: absolute;
width: 60px;
}
h6{
font-size: 25px;
margin: 0 0 0 1%;
position: absolute;
}
#prevnum{
position: absolute;
margin: -91px 0 0 248px;
font-size: 23PX;
float: left;
color: white;
word-spacing: 30.5px;
width: 400px;
overflow: hidden;
height: 65px;
}
img {
height: 40px;
width: 40px;
border-radius: 50%;
display: inline-block;
}
.black {
background-color: black;
float: left;
width: 50px;
line-height: 50px;
border-radius: 50%;
color: white;
text-align: center;
margin: 5px;
}
.red {
background-color: red;
float: left;
width: 50px;
line-height: 50px;
border-radius: 50%;
color: white;
text-align: center;
margin: 5px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h3 id="prev">Previous rolls:</h3>
<h3 id="prevnum"></h3>
<h6>Bet amount:</h6>
<input id="betamount" type="text" betamount="betamount">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="roll">Roll</button>
<div id="game">
<h3>1 14 2 13 3 12 4 <span class="green">0</span> 11 5 10 6 9 7 8 1 14 2 13 3 12 4 <span class="green">0</span> 11 5 10 6 9 7 8 1 14 2 13 3 12 4 <span class="green">0</span> 11 5 10 6 9 7 8 1 14 2 13 3 12 4 <span class="green">0</span> 11 5 10 6 9 7 8 1 14 2 13 3 12 4 <span class="green">0</span> 11 5 10 6 9 7 8 1 14 2 13 3 </h3></div>
<img id="arr" src="http://flaviar.com/gui/site/img/post_arrow.png">
<button id="re">Red</button>
<button id="bl">Black</button>
<h2 id="balance">Balance: 1000</h2>
<h2 id="winner"></h2>
<p id="betc"></p>
</body>
</html>

I'm not sure if there is a reason for the current approach but I would suggest not trying to center the numbers to a background image and instead, I would put the numbers in a list.
You can center the text within the li and also give the li a set width. This way your numbers will always be in the center. Giving the ul a list-type of non will remove the bullets and setting the li to inline-block will put them all in one row. Using the nth-of-type pseudo-class you can then set every other li to have a different background. More info on nth-of-type
Here is a quick codepen I made to demonstrate: http://codepen.io/LukeBailey/pen/dOjPZY
Note: I've commented out the whitespace between each li so they touch. This is a qwerk of inline-block, where if the elements have whitespace in the markup it separate them. Article: 'Fighting the Space Between Inline Block Elements'

Related

Build a multiplication table

I am having trouble with coding a calculator that asks the user to enter the starting and ending values. The program must use nested for loops. Including row and column labels.
This is what the final table will look like. I will greatly appreciate a link to a relating video or a hint to solve this problem. For example, the output from 1 to 3 might look like this:
1 2 3
1 1 2 3
2 2 4 6
3 3 6 9
The output from 3 to 5 might look like this:
3 4 5
3 9 12 15
4 12 16 20
5 15 20 25
The multipliers should appear on top and to the left of the table.
There is one example that I tried to modify for my task.
var result = 'x ';
for (var i = 0; i < 11; i++) {
for (var j = 0; j < 11; j++) {
if(i == 0 && j > 0){
result += '[' + j + ']';
}
else if(j == 0 && i>0){
result += '[' + i + '] ';
}
else if(i>0 && j>0){
result += (i*j) + ' ';
}
}
result += '\n'
}
console.log(result);
Output:
x [1][2][3][4][5][6][7][8][9][10]
[1] 1 2 3 4 5 6 7 8 9 10
[2] 2 4 6 8 10 12 14 16 18 20
[3] 3 6 9 12 15 18 21 24 27 30
[4] 4 8 12 16 20 24 28 32 36 40
[5] 5 10 15 20 25 30 35 40 45 50
[6] 6 12 18 24 30 36 42 48 54 60
[7] 7 14 21 28 35 42 49 56 63 70
[8] 8 16 24 32 40 48 56 64 72 80
[9] 9 18 27 36 45 54 63 72 81 90
[10] 10 20 30 40 50 60 70 80 90 100
I noticed the multipliers are in brackets and the X appears in the top left corner. Is it achieved by using if statements? In my assignment, there must be an empty cell instead of the X. This is what I came up with:
let result = "x";
for(let row = number1; row <= number2; row++){
result += row + "<tr>";
for( let column = number1; column <= number2; column++){
result += "<td>" + row * column +"</td>";
}
result += "<br>"
result += "</tr>"
}
document.getElementById("output").innerHTML = result;
}
My program generates a testing table with a start value equal to 2 and an end value equal to 5, and looks like this:
x 4 6 8 10
6 9 12 15
8 12 16 20
10 15 20 25
It is clear that some logic in the formula within the code isn't right.
I am attempting to use a document.getElementById() to output the result table. That is one of the requirements. Having some comments explaining the use of table element tags is greatly appreciated.
The program must take start and end values, not just from 1 to 10.
I appreciate everyone's answers. Some comments within the code that explain what does what and what I am doing wrong are also welcome.
p.s.
I made some corrections to my code. Now it displays ok. One thing is not right. It starts calculation with a number greater than the start number by 1 (eg for input values 2 to 6 it will display 3 to 6). Any ideas?
function displayExpressions(){
let number1 = getNumber();
// console.log(number1)
let number2 = getExpressionsNumber();
// console.log(number2)
if (number1 ==0 || number2 == 0){
document.getElementById("error").innerText = "Enter a number!"
}
else{
let result = " "
for(let row = number1; row <= number2; row++) {
result += "<tr>";
for( let column = number1; column <= number2; column++){
if( row == number1 && column > number1){
result += "<th>" + column + "</th>";
}
else if(column == number1 && row > number1){
result += "<th>" + row + "</th>";
}
else if (row == number1 && column == number1){
result = "<td>" + "x" + "</td>";
}
else{
result += "<td>" + row * column +"</td>";
document.getElementById("output").innerHTML = result;
}
}
result += "</tr>";
}
document.getElementById("output").innerHTML = result;
}
}
I thank everyone who helped. Here is a working example.
'use strict';
window.addEventListener('load', function () {
document.getElementById('number1').addEventListener('focus', inputFocus);
document.getElementById('number2').addEventListener('focus', inputFocus);
document.getElementById('btn').addEventListener('click', main);
document.getElementById('number1').focus();
});
function inputFocus() {
document.activeElement.select();
document.getElementById('error').innerText =
'Enter ' + document.activeElement.id + ' value.';
}
function getNumber() {
let multiplier = document.getElementById('number1').value;
multiplier = Number(multiplier);
return multiplier;
}
function getExpressionsNumber() {
let expressionsNumber = document.getElementById('number2').value;
expressionsNumber = Number(expressionsNumber);
return expressionsNumber;
}
// I have a good feeling that checkInput() does not work at all and is most likely redundant.
function checkInput() {
let number = document.activeElement.value;
console.log(number);
if (isNaN(number) || number.trim().lenght == 0) {
document.getElementById('error').innerText = 'Enter a number!';
return false;
}
return true;
}
function main() {
console.log('Main is called...'); // testing to see if this function is being called.
console.log(checkInput()); // testing if this function returns true...
if (checkInput()) {
document.getElementById('error').innerText = ''; // set the error message to emptry string... good.
displayExpressions(); // call the function to display the output...
}
}
function multiplication(number, expressionsNumber) {
let result = number * expressionsNumber;
return result;
}
function displayExpressions(){
let number1 = getNumber();
// console.log(number1)
let number2 = getExpressionsNumber();
// console.log(number2)
if (number1 <=0 || number2 <= 0){
document.getElementById("error").innerText = "Enter a natural number!"
}
else if(number1 >= number2 ){
document.getElementById("error").innerText = "End value must be grater than Start value!"
}
else{
let result = " "
for(let row = number1; row <= number2 + 1; row++) {
result += "<tr>";
for( let column = number1; column <= number2 + 1; column++){
if( row == number1 && column > number1){
result += "<th>" + (column-1) + "</th>";
}
else if(column == number1 && row > number1){
result += "<th>" + (row - 1) + "</th>";
}
else if (row == number1 && column == number1){
result = "<th>" + "x" + "</th>";
}
else{
result += "<td>" + (row - 1) * (column-1) +"</td>";
document.getElementById("output").innerHTML = result;
}
}
result += "</tr>";
}
document.getElementById("output").innerHTML = result;
}
}
*{
box-sizing: border-box;
}
.fcontainer{
display: flex;
}
div.fcontainer{
justify-content: space-between;
flex-basis: 50%;
margin: 15px;
}
body {
margin: 40px;
background-color: rgb(230, 255, 247);
font-family: 'Roboto', sans-serif;
font-size: calc(10px + (24 - 10) * (100vw - 300px) / (1600 - 300));
}
h1, h2 {
text-align: center;
}
img {
display: block;
width: 300px;
margin: 0 auto;
}
a {
text-decoration: none;
}
p {
margin: 10px 0px;
}
button {
margin: 10px 0px;
}
div.calc {
margin: 0 auto;
display: block;
width: 600px;
background-color: rgb(33, 209, 150);
padding: 20px;
border-radius: 5px;
text-align: center;
}
div.calc p {
text-align: left;
margin-left: 55px;
}
.calc input {
width: 80%;
text-align: right;
border-radius: 3px;
border: none;
}
div.cal h2,
h3 {
text-align: center;
}
#assignment6 div{
margin-top: 10px;
}
div.calc div input,
div.calc div label{
width: 45%;
display: inline-block;
text-align: right;
}
.calc button {
margin-left: 355px;
border-radius: 5px;
border:2px solid #008CBA;
color: black;
padding: 16px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
transition-duration: 0.4s;
cursor: pointer;
}
.calc button:hover {
background-color: #008CBA;
color: white;
}
.calc button:active {
transform: scale(0.98);
/* Scaling button to 0.98 to its original size */
box-shadow: 3px 2px 22px 1px rgba(0, 0, 0, 0.24);
/* Lowering the shadow */
}
/* Assignment Listings Page start */
#mainPage{
background-image: url(../images/keyboard.jpg);
background-repeat: no-repeat;
background-position: center;
background-size: cover;
height: 350px;
}
#header{
flex-direction: column;
background-color: #9b9ea1;
color: #fff;
max-width: 50%;
margin: 0 auto;
align-self: center;
}
#header h1{
margin: 1em;
}
#main div{
padding: 10px;
background-color: #9b9ea1;
margin: 15px;
width: fit-content;
}
#main a{
padding: 5px;
margin: 5px;
color: #fff;
}
/* Assignment Listings Page end */
/* assignment 3 */
section.fcontainer{
display: flex;
flex-wrap: wrap;
justify-content: space-around;
flex-direction: row;
align-items: stretch;
margin: 0 auto;
max-width: 2600px;
padding: 10px;
border: 1 solid black;
}
section.fcontainer div{
background-color: blanchedalmond;
flex-basis: 45%;
padding: 15px;
margin: 0 15px;
}
/* Assignment Events. Activity 4. Shape area calculator Start*/
body>div{
background-color: gray;
padding: 10px;
color: #fff;
}
div.formulaImage {
flex-basis: 33%;
padding-right: 10px;
}
div.inputForm{
flex-basis: 33%;
display: flex;
flex-direction: column;
justify-content: space-between;
margin-left: 10px;
margin-right: -10px;
}
.inputForm div{
padding-bottom: 5px;
text-align:left;
}
.formulaImage img{
object-fit: cover;
width: 100%;
}
.fcontainer label{
display: inline-block;
width: 50%;
vertical-align: top;
}
.fcontainer input{
display: inline-block;
width: 33%;
text-align: right;
height: 1.2em;
}
.fcontainer output{
display: inline-block;
width: 33%;
text-align: center;
}
#buttonRight{
text-align: end;
margin-right: 80px;
}
#weeklyWageCalculatorButton{
margin-left: 19.5em;
}
/* assignment 5 */
div.formulaImage{
flex-basis: 50%;
}
#assignment5_4{
justify-content: space-evenly;
}
#inputFields div{
padding-top: 5px;
}
#media (max-width: 800px) {
.fcontainer {
flex-direction: column;
}
section.fcontainer div {
flex-basis: 100%;
margin:15px 15px;
width: 100%;
}
div.inputForm{
margin-top: 20px;
}
div.calc {
width: 250px;
}
#weeklyWageCalculatorButton{
margin-left: 0em;
}
#mainPage{
justify-content: center;
}
#header{
max-width: 65%;
}
#btn{
margin: 0;
}
}
#yards{
margin-right: 0;
}
#error{
font-size: smaller;
color: red;
}
/* activity 2, lesson 7 table styles */
table{
border: 1px solid white;
border-collapse: collapse;
}
td{
padding: 10px;
text-align: center;
border: 1px solid white;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="../css/styles.css">
<script defer src="./activity2.js"></script>
<style>
table{
border: 1px solid black;
margin: 0 auto;
}
td, th{
width: 50px;
height: 50px;
border: 1px solid black;
}
th{
border: 2px solid black;
}
</style>
</head>
<body>
<div class="calc" id="assignment6">
<h2>Multiplication Table</h2>
<div>
<label for="number1">Start</label>
<input type="number" name="number1" id="number1" min="0" placeholder="0" onchange="">
</div>
<div>
<label for="number2">End</label>
<input type="number" name="number2" id="number2" min="0" placeholder="0" onchange="">
</div>
<p id="error"></p>
<table id="output"></table>
<p><button id="btn">Calculate</button></p>
</div>
</body>
</html>
if you are building a table, then this is MUCH easier with ".insertRow" and ".insertCell"
function buildit(number1, number2) {
let tbody = document.querySelector('tbody');
let result = '';
let row = tbody.insertRow();
row.insertCell().textContent = 'X';
for (let y = number1; y <= number2; y++) {
// first Row, add the "X" numbers
if (y === number1) {
for (let x = number1; x <= number2; x++) {
row.insertCell().textContent = x;
}
}
// create new Row
row = tbody.insertRow();
// and add the "Y" number first
row.insertCell().textContent = y;
for (let x = number1; x <= number2; x++) {
row.insertCell().textContent = x * y;
}
}
}
buildit(3, 6);
th,
td {
text-align: right;
}
tbody tr:first-child,
tbody tr td:first-child {
color:red;
}
<table>
<tbody>
</tbody>
</table>
Although the example can handle different dimensions, for the sake of simplicity we are making a 10 x 10 table in this explanation.
Use 2 for loops -- the outer loop makes one row then the inner loop makes 10 cells.
Note that the loops start at 0 index so the iterations are at 10+1 to compensate.
Inside of each cell is the product of the current row index and the current cell index.
If the product of row and cell index is 0 then no cell is made.
Go back to the outer loop once the row has 10 cells and start the next row.
Repeat this process until there are 10 rows.
Details are commented in example below
// Reference the <table>
const table = document.querySelector('table');
/**
* Renders a given htmlString to a
* given DOM object.
* #param {object<DOM>} node - The tag
* to render HTML to
* #param {string<HTML>} html - The string
* that will be rendered as HTML
*/
const xHTML = (node, html) => {
node.insertAdjacentHTML('beforeEnd', html);
};
/**
* Renders a table with a given number
* of rows and columns. Each cell's
* contents are a product of row and
* column indexes.
* #param {number} rQty - Number of rows
* #param {number} cQty - Number of columns
*/
const mTable = (rQty, cQty) => {
// Make one <tr>...
for (let r = 0; r < rQty + 1; r++) {
xHTML(table, `<tr></tr>`);
/*
If the product of r and c is 0 ?
make nothing :
otherwise make a <td>(r x c)</td>
*/ // Do this >cQty< times
for (let c = 0; c < cQty + 1; c++) {
let cell = r * c === 0 ? '' : `<td>${r*c}</td>`;
xHTML(table.rows[r], cell);
}
/* Once there is >cQty< cells in
row, go to the outer loop to
make next row and so on */
}
};
mTable(10, 10);
html {
font: 2ch/1 Consolas
}
table {
table-layout: fixed;
border-collapse: collapse;
}
td {
width: 10%;
border: 0.5px solid #000;
text-align: center
}
<table></table>

Need a timer or delay function for a small card game

I made a game in JavaScript and it seems to run pretty well. The rules are: There are 2 players who take turns. Draw cards to get points. You can draw multiple cards per turn. You don't get points until you press the End Turn button. If you draw a 2, 5, or 9 then you lose all points for that turn.
Everything works, however, when you draw a 2, 5, or 9 the turn changes before you even get to see the card. So you wouldn't even know if you drew that card.
I want to add a timer or delay function so that when you draw a 2, 5, or 9 it displays that card for a second or two.
And also I want to disable any clicking so you don't accidentally click for the next player.
Here's the link to the page:
https://tneilson08.github.io/cardgame/
var scores, roundScore, activePlayer, gamePlaying;
gamePlaying = true;
init();
// Create the deck
const deck = ["2C", "2S", "2H", "2D", "3C", "3S", "3H", "3D", "4C", "4S", "4H", "4D", "5C", "5S", "5H", "5D", "6C", "6S", "6H", "6D", "7C", "7S", "7H", "7D", "8C", "8S", "8H", "8D", "9C", "9S", "9H", "9D", "10C", "10S", "10H", "10D", "JC", "JS", "JH", "JD", "QC", "QS", "QH", "QD", "KC", "KS", "KH", "KD", "AC", "AS", "AH", "AD"];
// const deck = ["two-club", "two-spade", "two-heart", "two-dia", "three-club", "three-spade", "three-heart", "three-dia"];
// Shuffle the deck
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
shuffleArray(deck);
// Draw cards
function drawCard() {
if (gamePlaying) {
// 1. Draw from the deck and remove with shift()
var card = deck.shift();
// 2. Display the card
var cardDOM = document.querySelector('.card');
cardDOM.style.display = 'block'; // card becomes visible
cardDOM.src = 'img/' + card + '.png'; // determines card drawn
// 3. Determine card value
if (card == "2C" || card == "2S" || card == "2H" || card == "2D") {
card = 2;
} else if (card == "3C" || card == "3S" || card == "3H" || card == "3D") {
card = 3;
} else if (card == "4C" || card == "4S" || card == "4H" || card == "4D") {
card = 4;
} else if (card == "5C" || card == "5S" || card == "5H" || card == "5D") {
card = 5;
} else if (card == "6C" || card == "6S" || card == "6H" || card == "6D") {
card = 6;
} else if (card == "7C" || card == "7S" || card == "7H" || card == "7D") {
card = 7;
} else if (card == "8C" || card == "8S" || card == "8H" || card == "8D") {
card = 8;
} else if (card == "9C" || card == "9C" || card == "9H" || card == "9D") {
card = 9;
} else {
card = 10;
}
// 4. Update the round score IF the card drawn was NOT a 4 or a 9
if (card !== 2 && card !== 5 && card !== 9) {
// add score
roundScore += card;
document.querySelector('#current-' + activePlayer).textContent = roundScore;
} else {
// next player
nextPlayer();
}
// if (card === 5) {
// // add score
// setTimeout(nextPlayer, 2000);
// }
//
// if (card === 9) {
// // add score
// setTimeout(nextPlayer, 2000);
// }
// 5. If deck array runs out, replace all cards in deck ///MAYBE CHANGE THIS SO GAME ENDS AND PLAYER WITH HIGHEST DECK WINS
if (deck.length === 0) {
deck.push("2C", "2S", "2H", "2D", "3C", "3S", "3H", "3D", "4C", "4S", "4H", "4D", "5C", "5S", "5H", "5D", "6C", "6S", "6H", "6D", "7C", "7S", "7H", "7D", "8C", "8S", "8H", "8D", "9C", "9S", "9H", "9D", "10C", "10S", "10H", "10D", "JC", "JS", "JH", "JD", "QC", "QS", "QH", "QD", "KC", "KS", "KH", "KD", "AC", "AS", "AH", "AD");
// deck.push("two-club", "two-spade", "two-heart", "two-dia", "three-club", "three-spade", "three-heart", "three-dia");
shuffleArray(deck);
}
}
}
document.querySelector('.btn-draw').addEventListener('click', function() {
drawCard();
});
function endTurn() {
if (gamePlaying) {
// Add CURRENT score to GLOBAL score
scores[activePlayer] += roundScore;
// Update the UI
document.querySelector('#score-' + activePlayer).textContent = scores[activePlayer];
// Check if player won the game
if (scores[activePlayer] >= 200) {
document.querySelector('#name-' + activePlayer).textContent = 'Winner!';
document.querySelector('.card').style.display = 'none';
document.querySelector('.player-' + activePlayer + '-panel').classList.add('winner');
document.querySelector('.player-' + activePlayer + '-panel').classList.remove('active');
gamePlaying = false;
} else {
// Next Player
nextPlayer();
}
}
}
document.querySelector('.btn-endturn').addEventListener('click', function() {
endTurn();
});
function nextPlayer() {
activePlayer === 0 ? activePlayer = 1 : activePlayer = 0;
roundScore = 0;
document.getElementById('current-0').textContent = '0';
document.getElementById('current-1').textContent = '0';
document.querySelector('.player-0-panel').classList.toggle('active');
document.querySelector('.player-1-panel').classList.toggle('active');
document.querySelector('.card').style.display = 'none';
}
document.querySelector('.btn-new').addEventListener('click', init);
function init() {
scores = [0, 0];
roundScore = 0;
activePlayer = 0;
gamePlaying = true;
document.querySelector('.card').style.display = 'none';
document.getElementById('score-0').textContent = '0';
document.getElementById('score-1').textContent = '0';
document.getElementById('current-0').textContent = '0';
document.getElementById('current-1').textContent = '0';
document.getElementById('name-0').textContent = 'Player 1';
document.getElementById('name-1').textContent = 'Player 2';
document.querySelector('.player-0-panel').classList.remove('winner');
document.querySelector('.player-1-panel').classList.remove('winner');
document.querySelector('.player-0-panel').classList.remove('active');
document.querySelector('.player-1-panel').classList.remove('active');
document.querySelector('.player-0-panel').classList.add('active');
}
#import url('https://fonts.googleapis.com/css2?family=Open+Sans+Condensed:wght#300;700&display=swap');
.final-score {
position: absolute;
left: 50%;
transform: translateX(-50%);
top: 520px;
color: #555;
font-size: 18px;
font-family: 'Open Sans Condensed', sans-serif;
text-align: center;
padding: 10px;
width: 160px;
text-transform: uppercase;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.clearfix::after {
content: "";
display: table;
clear: both;
}
body {
background-image: url("img/bg.gif");
background-size: cover;
background-position: center;
font-family: 'Open Sans Condensed', sans-serif;
font-weight: 300;
position: relative;
height: 100vh;
color: #161624;
}
.wrapper {
width: 1000px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: #400000;
box-shadow: 0px 10px 50px rgba(0, 0, 0, 1);
overflow: hidden;
color: white;
}
.player-0-panel,
.player-1-panel {
width: 50%;
float: left;
height: 600px;
padding: 100px;
}
/**********************************************
*** PLAYERS
**********************************************/
.player-name {
font-size: 40px;
text-align: center;
text-transform: uppercase;
letter-spacing: 2px;
font-weight: 100;
margin-top: 20px;
margin-bottom: 10px;
position: relative;
}
.player-score {
text-align: center;
font-size: 80px;
font-weight: 200;
color: white;
margin-bottom: 130px;
}
.active {
background-color: rgb(255, 0, 0, .1);
}
.active .player-name {
font-weight: 700;
}
.active .player-score {
font-weight: 700;
}
.player-current-box {
background-color: #EB4D4D;
color: #fff;
width: 40%;
margin: 0 auto;
padding: 12px;
text-align: center;
}
.player-current-label {
text-transform: uppercase;
margin-bottom: 10px;
font-size: 20px;
color: #fff;
}
.player-current-score {
font-size: 40px;
}
button {
position: absolute;
width: 200px;
left: 50%;
transform: translateX(-50%);
color: #555;
background: none;
border: none;
font-family: 'Open Sans Condensed', sans-serif;
font-size: 30px;
text-transform: uppercase;
cursor: pointer;
font-weight: 300;
transition: background-color 0.3s, color 0.3s;
}
button:hover {
font-weight: 600;
border: 1px solid white;
}
button:focus {
outline: none;
}
/* i {
color: #EB4D4D;
display: inline-block;
margin-right: 15px;
font-size: 32px;
line-height: 1;
vertical-align: text-top;
margin-top: -4px;
transition: margin 0.3s;
} */
.btn-new {
top: 45px;
color: white;
border: 2px solid white;
transition: 0.25s;
}
.btn-draw {
top: 403px;
color: white;
border: 2px solid white;
transition: 0.25s;
}
.btn-endturn {
top: 467px;
color: white;
border: 2px solid white;
transition: 0.25s;
}
.card {
position: absolute;
left: 50%;
top: 178px;
transform: translateX(-50%);
height: 200px;
}
.back-card {
position: absolute;
left: 50%;
top: 178px;
transform: translateX(-50%);
height: 200px;
}
.winner {
background-color: #b00000;
}
.winner .player-name {
font-weight: 700;
color: #ff7878;
}
.winner .player-score {
font-weight: 700;
color: #ff7878;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="styles.css">
<title>Card Game</title>
</head>
<body>
<div class="wrapper clearfix">
<div class="player-0-panel active">
<div class="player-name" id="name-0">Player 1</div>
<div class="player-score" id="score-0">43</div>
<div class="player-current-box">
<div class="player-current-label">Current</div>
<div class="player-current-score" id="current-0">11</div>
</div>
</div>
<div class="player-1-panel">
<div class="player-name" id="name-1">Player 2</div>
<div class="player-score" id="score-1">72</div>
<div class="player-current-box">
<div class="player-current-label">Current</div>
<div class="player-current-score" id="current-1">0</div>
</div>
</div>
<button class="btn-new"><i class="ion-ios-plus-outline"></i>New game</button>
<button class="btn-draw"><i class="ion-ios-loop"></i>Draw Card</button>
<button class="btn-endturn"><i class="ion-ios-download-outline"></i>End Turn</button>
<img src="img/back-card.png" alt="Back of Card" class="back-card">
<img src="card-5.png" alt="Card" class="card">
</div>
<script src="script.js"></script>
</body>
</html>
I think you already have the answer using setTimeout. But where? Based on your rules I would say you should use on the else, like so:
// 4. Update the round score IF the card drawn was NOT a 4 or a 9
if (card !== 2 && card !== 5 && card !== 9) {
// add score
roundScore += card;
document.querySelector('#current-' + activePlayer).textContent = roundScore;
} else {
// next player
setTimeout(() => {
nextPlayer();
}, 2000);
}
But you should freeze the buttons, before you schedule this setTimeout. Because the user would continue playing.
I'd would put something, like so:
freezeButtons();
// next player
setTimeout(() => {
nextPlayer();
}, 2000);
So finally it should work like so:
// 4. Update the round score IF the card drawn was NOT a 4 or a 9
if (card !== 2 && card !== 5 && card !== 9) {
// add score
roundScore += card;
document.querySelector('#current-' + activePlayer).textContent = roundScore;
} else {
const buttons = document.querySelectorAll('button');
for(const button of buttons) {
button.disabled = true;
}
// next player
setTimeout(() => {
nextPlayer();
for(const button of buttons) {
button.disabled = false;
}
}, 2000);
}

Detect collision (video game js)

I am building a video game where fireballs drop from the top screen. The spaceship, moved by controllers, must avoid those fireballs in order win. My issue is that I do not know how to detect when the spaceship collides into fireballs. However, I found this link: Detect if animated object touched another object in DOM. I analysed this code and it seems it only works for his issue particularly. Do you guys know how to do this?
Code for image spaceship and fireball:
<img src="Photo/fireball.png" id="fireball">
<img src="Photo/Spaceship1.png" id="icon-p">
Code for spaceship:
let rect = icon
let pos = {top: 1000, left: 570}
const keys = {}
window.addEventListener("keydown", function(e) {keys[e.keyCode] = true})
window.addEventListener("keyup", function(e) {keys[e.keyCode] = false})
const loop = function() {
if (keys[37] || keys[81]) {pos.left -= 10}
if (keys[39] || keys[68]) {pos.left += 10}
if (keys[38] || keys[90]) {pos.top -= 10}
if (keys[40] || keys[83]) {pos.top += 10}
var owidth = display.offsetWidth
var oheight = display.offsetHeight
var iwidth = rect.offsetWidth
var iheight = rect.offsetHeight
if (pos.left < 0) pos.left = -10
if (pos.top < 0) pos.top = -10
if (pos.left + iwidth >= owidth) pos.left = owidth-iwidth
if (pos.top + iheight >= oheight) pos.top= oheight-iheight
rect.setAttribute("data", owidth + ":" + oheight)
rect.style.left = pos.left + "px"; rect.style.top = pos.top + "px"}
let sens = setInterval(loop, 1000 / 60)
Code for fireball:
function fFireball(offset) {
return Math.floor(Math.random() * (window.innerWidth - offset))}
let fireballElement = document.querySelector("#fireball");
let fireball = {x: fFireball(fireballElement.offsetWidth), y: 0}
const fireLoop = function() {
fireball.y += 2
fireballElement.style.top = fireball.y + 'px'
if (fireball.y > window.innerHeight) {
fireball.x = fFireball(fireballElement.offsetWidth)
fireballElement.style.left = fireball.x + 'px'; fireball.y = 0}}
fireballElement.style.left = fireball.x + 'px'
let fireInterval = setInterval(fireLoop, 1000 / 100)
Thanks!
here I've integrated collision detection for your game. The most notable thing is in this function:
function checkCollision() {
var elem = document.getElementById("icon");
var elem2 = document.getElementById("fireball");
if ( detectOverlap(elem, elem2) && elem2.getAttribute('hit')=='false' ){
hits++; // detect hit and increase
elem2.setAttribute('hit', true); // set attribute to not have flooding
console.log( hits ); // console it just to see it
}
setTimeout( checkCollision, 20);
}
In lower window you can test demo that I've built for you without images but some random boxes as images :)
Good luck with game man, cool
//////////
"use strict"
//Stay on focus
function stayOnFocus() {
setTimeout(function() {
alert("Do not exit window or game progression will be lost!")
}, 1000)
}
let hits = 0
//"A" keypress plays Music
document.addEventListener('keydown', function(e) {
if (e.keyCode !== 173) {
//document.getElementById('audio').play()
}
})
//Input Validation
let icon = document.getElementById("icon")
let fireballElement = document.querySelector("#fireball")
var input = document.getElementById("input")
input.addEventListener("keydown", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("begin-timer").click()
}
})
//CountDown (3...2...1)
var count = 3
function countDown() {
function preventCountFast() {
document.getElementById("count").innerHTML = count
if (count > 0) {
count--
} else {
clearInterval(ncount);
document.getElementById("count").style.display = "none"
}
}
var ncount = setInterval(preventCountFast, 1000)
}
//Name displayed + space(switch between images) + parameter icon displayed
function Username(field) {
field = input.value
if (field == "") {
alert("Complete blanks");
return false
}
document.getElementById("askName").style.display = "none"
setTimeout(function() {
document.getElementById("name").innerHTML = "Player: " + field
icon.style.display = 'block';
fireballElement.style.display = "block"
const images = ["https://placehold.it/30x30", "https://placehold.it/90x90",
"https://placehold.it/120x40", "https://placehold.it/100x100"
]
document.body.onkeyup = function(e) {
if (e.keyCode === 32) {
hits++;
icon.src = images[hits % 5]
}
}
checkCollision();
}, 4000)
}
//Spaceship moves into space + prevent going out borders
let display = document.getElementById("body");
let rect = icon
let pos = {
top: 1000,
left: 570
}
const keys = {}
window.addEventListener("keydown", function(e) {
keys[e.keyCode] = true
})
window.addEventListener("keyup", function(e) {
keys[e.keyCode] = false
})
const loop = function() {
if (keys[37] || keys[81]) {
pos.left -= 10
}
if (keys[39] || keys[68]) {
pos.left += 10
}
if (keys[38] || keys[90]) {
pos.top -= 10
}
if (keys[40] || keys[83]) {
pos.top += 10
}
var owidth = display.offsetWidth
var oheight = display.offsetHeight
var iwidth = rect.offsetWidth
var iheight = rect.offsetHeight
if (pos.left < 0) pos.left = -10
if (pos.top < 0) pos.top = -10
if (pos.left + iwidth >= owidth) pos.left = owidth - iwidth
if (pos.top + iheight >= oheight) pos.top = oheight - iheight
rect.setAttribute("data", owidth + ":" + oheight)
rect.style.left = pos.left + "px";
rect.style.top = pos.top + "px"
}
let sens = setInterval(loop, 1000 / 60)
//Parameter Sensibility
let param = document.getElementById("parameters")
let b2 = document.getElementById("body2")
document.getElementById("general").addEventListener("click", function() {
param.style.display = "block";
b2.style.display = "none"
})
function validateSens() {
b2.style.display = "block";
param.style.display = "none";
clearInterval(sens)
let sensibilty = parseFloat(document.getElementById("sensibilty").value)
switch (sensibilty) {
case 1:
sens = setInterval(loop, 1000 / 40);
break;
case 2:
sens = setInterval(loop, 1000 / 60);
break;
case 3:
sens = setInterval(loop, 1000 / 80);
break;
default:
alert("Sorry, a bug occured")
}
}
//Fireball script
function fFireball(offset) {
return Math.floor(Math.random() * (window.innerWidth - offset))
}
let fireball = {
x: fFireball(fireballElement.offsetWidth),
y: 0
}
const fireLoop = function() {
fireball.y += 2;
fireballElement.style.top = fireball.y + 'px'
if (fireball.y > window.innerHeight) {
fireball.x = fFireball(fireballElement.offsetWidth)
fireballElement.style.left = fireball.x + 'px';
fireball.y = 0;
fireballElement.setAttribute('hit', false );
}
}
fireballElement.style.left = fireball.x + 'px'
let fireInterval = setInterval(fireLoop, 1000 / 100)
function checkCollision() {
var elem = document.getElementById("icon");
var elem2 = document.getElementById("fireball");
if (detectOverlap(elem, elem2) && elem2.getAttribute('hit')=='false' ){
hits++; // detect hit
elem2.setAttribute('hit', true);
aler("hi")
}
setTimeout( checkCollision, 20);
}
// detect fn
var detectOverlap = (function() {
function getPositions(elem) {
var pos = elem.getBoundingClientRect();
return [
[pos.left, pos.right],
[pos.top, pos.bottom]
];
}
function comparePositions(p1, p2) {
var r1, r2;
r1 = p1[0] < p2[0] ? p1 : p2;
r2 = p1[0] < p2[0] ? p2 : p1;
return r1[1] > r2[0] || r1[0] === r2[0];
}
return function(a, b) {
var pos1 = getPositions(a),
pos2 = getPositions(b);
return comparePositions(pos1[0], pos2[0]) && comparePositions(pos1[1], pos2[1]);
};
})();
body {
user-select: none;
margin: 0px;
height: 100vh;
padding: 0;
width: 100%;
background-image: url(Photo/bg.jpg);
background-repeat: no-repeat;
background-attachment: fixed;
animation: intro-fade 3s;
background-size: cover;
overflow: hidden;
}
#askName {
display: block;
z-index: 1;
margin-left: auto;
margin-top: 12%;
margin-right: auto;
width: 400px;
text-align: center;
background-color: #737373;
opacity: 0.8;
border-radius: 15px;
padding: 40px 50px 40px 50px;
}
#askName:hover {
opacity: 0.9
}
#askName>label {
text-align: center;
font-size: 150%;
font-weight: lighter;
text-align: center;
}
#askName>input {
display: block;
font-size: 100%;
margin: 30px auto 20px auto;
border: none;
border-radius: 10px;
padding: 10px 20px 10px 20px;
}
#askName>button {
background-color: #e6e6e6;
cursor: pointer;
padding: 10px 20px 10px 20px;
border: none;
border-radius: 10px;
}
#count {
margin-top: 13%;
animation: count-down 16s;
font-weight: lighter;
font-family: cursive;
text-align: center;
color: black;
font-size: 200px;
}
h6 {
margin-right: 20px;
padding-top: 5px;
font-weight: normal;
font-family: sans-serif;
margin-top: 0px;
color: white;
text-align: center;
font-size: 190%;
cursor: default;
}
h6:hover {
font-size: 210%
}
#icon {
position: absolute;
top: 0;
left: 0;
cursor: none;
width: 9%;
}
#general {
position: absolute;
cursor: pointer;
min-width: 4%;
top: 10px;
width: 4%;
right: 10px;
}
#general:hover {
transform: rotate(-100deg)
}
#parameters {
text-align: center;
display: none;
animation: intro-fade 3s;
height: auto;
border: none;
background-color: #d9d9d9;
color: black;
position: absolute;
padding: 0px 60px 20px 60px;
left: 50%;
width: auto;
min-width: 200px;
top: 50%;
transform: translate(-50%, -50%);
border-radius: 13px;
}
h3 {
color: black;
font-weight: normal;
font-size: 150%;
}
#sensibilty {
display: block;
margin-right: auto;
margin-left: auto;
}
#validateSens {
margin-top: 20px;
border: none;
padding: 10px;
border-radius: 5px;
cursor: pointer;
}
#keyframes intro-fade {
from {
opacity: 0
}
to {
opacity: 1
}
}
#keyframes count-down {
from {
transform: scale(0)
}
to {
transform: scale(1)
}
}
<body id="body" onload="stayOnFocus()">
<img src="https://placehold.it/350x350" id="general">
<section id="parameters">
<h3> Choose your sensibility </h3>
<input type="range" id="sensibilty" min="1" max="3" value="2">
<button id="validateSens" onclick="validateSens()"> Submit </button>
</section>
<main id="body2">
<form id="askName" title="Write your name"> <label> Enter your username: </label>
<input id="input" type="text" maxlength="10" autofocus>
<button type="button" onclick="countDown(); return Username()" id="begin-timer"> Submit </button>
</form>
<h6 id="name"></h6>
<h2 id="count"></h2>
<img src="https://placehold.it/50x52" id="fireball" style="display:none; width:3%; position:absolute; cursor:none">
<img src="https://placehold.it/80x40" id="icon" style="display:none">
</main>

how to make a div return to starting point when the div slides to end

I'm trying to make am image scroll that uses control button and also slides automatically, my problem now is I need to know how to return the div to starting point when the div hit end on left side or on right side, what I could get so far is to know when the div hit an end but don't know how to return it to starting point in case of automatic sliding.
var n = 3; //total number of slides to be display at once
var totalDeal = 9; //total deals to be display
var sliderTotalWidth = 100; //in percentage append % later
var z = (100 / totalDeal) + '%'; //ddslides width
var x = totalDeal / n;
var counter = 1;
$(".dialyDealSlider").css('width', x + '00%');
//$(".ddslides").css('width', ddslidesWidth);
fillDailyDeal(totalDeal, z);
function fillDailyDeal(totalDeal, z) {
var imgUrl = '{$img}';
var ext = '.jpg';
var width = "width:" + z
for (var i = 1; i <= totalDeal; i++) {
var myDiv = $(
"<div class='ddslides' style='" + width + "' >" +
'<div class="dddesc">' +
'<div class="ddtitle">' +
'The is the title of the item it\'s a long title' +
'</div>' +
"<div class='ddprice'>$"+i+"00</div>" +
'<button class="ddview" title="View Item">view item</button>' +
'</div>' +
'<div class="ddimg">' +
'</div>' +
'<div class="vDivider"></div>' +
'<div class="ddSaleBadge">sold 44%</div>' +
'</div>');
$("#dialyDealSlider").append(myDiv);
}
}
$("#prev, #next").click(function() {
if (this.id == "next") {
counter++;
} else {
counter--;
}
//console.log(counter);
if (counter == x) {
alert('rigth end');
//$("#dialyDealSlider").css('left', '0px');
}
if (counter == 1) {
alert('left end');
}
var ddslidesWidth = $(".ddslides").width();
var dir = this.id == "next" ? '-=' : '+=';
var width = ddslidesWidth * n;
//alert(leftpos);
$("#dialyDealSlider").animate({
left: dir + width
}, 800);
});
my code is here JSFIDDLE: https://jsfiddle.net/sammyzeal/LqpL1n2g/
As we can see in the above fiddle, when we slide the div and the price is between $700 and $900 we hit an end then there's an alert, on this point if a user keeps on clicking this next button how do I scroll to the starting point which is between price $100 and $300, I hope my question is cleared and thanks in advance for any help
I just saw that you updated the code as i said , good work. So i wont hesitate to help now, you should make a separate slideNow() function that slides next or previous and you should increment/decrement the counter after checking the current or previous slides, if it is the last slide create a function separate to goToStart() to move to the first slide and if it is th first slide just return from there and do nothing, you can use the following script and test it with various combinations like, first going to the last slide by clicking and then on the last slide click next and see if it goes to the first on and then try clicking left from the first slide and verify if it goes left or stays still.
See a demo below
var n = 3; //total number of slides to be display at once
var totalDeal = 9; //total deals to be display
var sliderTotalWidth = 100; //in percentage append % later
var z = (100 / totalDeal) + '%'; //ddslides width
var x = totalDeal / n;
var counter = 1;
$(".dialyDealSlider").css('width', x + '00%');
//$(".ddslides").css('width', ddslidesWidth);
fillDailyDeal(totalDeal, z);
function fillDailyDeal(totalDeal, z) {
var imgUrl = '{$img}';
var ext = '.jpg';
var width = "width:" + z
for (var i = 1; i <= totalDeal; i++) {
var myDiv = $(
"<div class='ddslides' style='" + width + "' >" +
'<div class="dddesc">' +
'<div class="ddtitle">' +
'The is the title of the item it\'s a long title' +
'</div>' +
"<div class='ddprice'>$" + i + "00</div>" +
'<button class="ddview" title="View Item">view item</button>' +
'</div>' +
'<div class="ddimg">' +
'</div>' +
'<div class="vDivider"></div>' +
'<div class="ddSaleBadge">sold 44%</div>' +
'</div>');
$("#dialyDealSlider").append(myDiv);
}
}
$("#prev, #next").click(function() {
var target = this.id;
//console.log(counter);
if (counter == x && target == "next") {
counter = 1;
goToStart();
return;
}
if (counter == 1 && target == "prev") {
return;
}
if (target == "next") {
counter++;
} else {
counter--;
}
//slide the slides
slideNow(target, n);
});
function goToStart() {
$("#dialyDealSlider").animate({
left: 0
}, 800);
}
function slideNow(target, n) {
var ddslidesWidth = $(".ddslides").width();
var dir = target == "next" ? '-=' : '+=';
var width = ddslidesWidth * n;
//alert(leftpos);
$("#dialyDealSlider").animate({
left: dir + width
}, 800);
}
.dailyDeal {
height: 150px;
width: 100%;
margin-top: 15px;
padding: 0 !important;
}
.dialyDealBox {
float: left;
height: 150px;
padding: 0 !important;
overflow: hidden;
}
.dialyDealSlider {
width: 100%;
height: 150px;
position: absolute;
border: 1px solid #ddd;
}
.ddslides {
height: 150px;
width: 2%;
float: left;
background-color: #fff;
position: relative;
padding: 10px 0;
}
#media only screen and (max-width: 768px) {
.ddslides {
width: 16.66%;
}
}
#media (max-width:320px) {
.ddslides {
width: 33.33%;
}
}
.ddimg {
float: left;
margin: auto;
height: 100%;
width: 32%;
margin-right: 4px;
}
.ddimg>a>img {
height: 100%;
width: 100%;
}
.dddesc {
float: left;
margin: auto;
height: 100%;
width: 65%;
padding: 0 10px 0 15px;
}
.ddSaleBadge {
position: absolute;
top: 5px;
right: 5px;
width: 37px;
height: 38px;
padding: 5px 2px 4px 3px;
overflow: hidden;
background: url("/trobay/img/icon/label.png") no-repeat 50% 50%;
line-height: 14px;
text-align: center;
color: #fff;
}
.ddtitle {
margin-bottom: 10px;
}
.ddtitle>a {
font-size: 14px;
color: #666666;
text-decoration: none;
}
.ddtitle>a:hover {
color: #e4393c;
text-decoration: none;
}
.ddprice {
color: #e4393c;
font-size: 16px;
margin-bottom: 10px;
}
.ddview {
color: #fff;
background-color: #e4393c;
font-size: 14px;
border: 0;
outline: 0;
padding: 4px;
font-weight: bold;
}
.ddslider-prev {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
margin-top: -22px;
padding: 5px;
color: #666666;
font-weight: bold;
font-size: 18px;
transition: 0.6s ease;
left: 0;
z-index: 10;
background-color: rgba(221, 221, 221, 1);
display: block;
}
.ddslider-next {
cursor: pointer;
position: absolute;
right: 0;
top: 50%;
width: auto;
margin-top: -22px;
padding: 5px;
color: #666666;
font-weight: bold;
font-size: 18px;
transition: 0.6s ease;
z-index: 10;
background-color: rgba(221, 221, 221, 1);
display: block;
}
.vDivider {
height: 130px;
border-right: 1px dotted #666;
position: absolute;
top: 10px;
;
right: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
<div class="dailyDeal col-md-12">
<div class="dialyDealBox col-xs-10" id="dialyDealBox">
<div class="dialyDealSlider" id="dialyDealSlider">
</div>
<div class="ddslider-prev" id="prev">❮</div>
<div class="ddslider-next" id="next">❯</div>
</div>
</div>
</div>

How do I make my jquery game's gameboard responsive?

I'm trying to create a game using Jquery however I have an issue when trying to make the webpage responsive. The issue is that I'm unable to make my game-board "spelplan" responsive, I know the reason this happens is because parts of my script is connected to the "width" of the game-board so when I remove the "width" and replace it with <div id="spelplan" class="col-6 col-m-6"> these parts get completely messed up. So what I need help with is how I make my game-board "spelplan" responsive, I would really appreciate any help I can get with this.
function updateClock() {
var currentTime = new Date();
var currentHours = currentTime.getHours();
var currentMinutes = currentTime.getMinutes();
var currentSeconds = currentTime.getSeconds();
currentMinutes = (currentMinutes < 10 ? "0" : "") + currentMinutes;
currentSeconds = (currentSeconds < 10 ? "0" : "") + currentSeconds;
var timeOfDay = (currentHours < 12) ? "AM" : "PM";
currentHours = (currentHours > 12) ? currentHours - 12 : currentHours;
currentHours = (currentHours == 0) ? 12 : currentHours;
var currentTimeString = currentHours + ":" + currentMinutes + ":" + currentSeconds + " " + timeOfDay;
document.getElementById("clock").firstChild.nodeValue = currentTimeString;
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
background-color: black;
}
header {
position: absolute;
top: 50px;
color: white;
text-align: center;
}
#clock {
font-size: 25px;
position: absolute;
color: white;
}
#rand_pos {
position: absolute;
top: 20%;
left: 30%;
z-index: 10;
}
.player {
background-color: red;
height: 50px;
width: 50px;
position: absolute;
top: 100px;
left: 100px;
z-index: 100;
}
p {
position: relative;
left: 10px;
color: white;
}
#spelplan {
position: relative;
left: 35%;
top: 200px;
height: 600px;
width: 600px;
background-color: blue;
border-style: double;
border-radius: 40px;
}
.rand {
background-color: green;
height: 15px;
width: 15px;
position: absolute;
left: 30%;
top: 150px;
z-index: 3;
}
.new_pos {
background: #ccc;
border: 1px solid #000;
padding: 5px;
box-shadow: 0 0 20px #555;
-webkit-transition: all .2s ease-in;
transition: all .2s ease-in;
}
.new_pos:hover {
background: #bbb;
box-shadow: 0 0 20px #222;
}
.new_pos:active {
box-shadow: 0 0 20px #000;
background: #aaa;
}
*:focus {
outline: none;
}
.new_pos {
position: fixed;
left: 0;
bottom: 0;
cursor: pointer;
}
#footer {
position: absolute;
top: 80vh;
color: white;
text-align: center;
}
/* For mobile phones: */
[class*="col-"] {
width: 100%;
}
#media only screen and (min-width: 600px) {
/* For tablets: */
.col-m-1 {
width: 8.33%;
}
.col-m-2 {
width: 16.66%;
}
.col-m-3 {
width: 25%;
}
.col-m-4 {
width: 33.33%;
}
.col-m-5 {
width: 41.66%;
}
.col-m-6 {
width: 50%;
}
.col-m-7 {
width: 58.33%;
}
.col-m-8 {
width: 66.66%;
}
.col-m-9 {
width: 75%;
}
.col-m-10 {
width: 83.33%;
}
.col-m-11 {
width: 91.66%;
}
.col-m-12 {
width: 100%;
}
img {
width: 80%;
height: auto;
}
}
#media only screen and (min-width: 768px) {
/* For desktop: */
.col-1 {
width: 8.33%;
}
.col-2 {
width: 16.66%;
}
.col-3 {
width: 25%;
}
.col-4 {
width: 33.33%;
}
.col-5 {
width: 41.66%;
}
.col-6 {
width: 50%;
}
.col-7 {
width: 58.33%;
}
.col-8 {
width: 66.66%;
}
.col-9 {
width: 75%;
}
.col-10 {
width: 83.33%;
}
.col-11 {
width: 91.66%;
}
.col-12 {
width: 100%;
}
img {
width: 100%;
height: auto;
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="style20.css">
<script type='text/javascript' src='eventjavascript6.js'></script>
<title>Jquery spel</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
var sprites = [];
var enemies = [];
var game = $("#spelplan");
var score = 0;
var el_score = $("#score")
function SCORE(pts) {
score += pts
el_score.text(score);
}
function RND(min, max) {
return parseInt(Math.random() * (max - min) + min);
}
var sprite = function(id, x, y, w, h, _class, view, collisionDetect, options) {
this.view = view;
this.id = id
this.x = x + "px";
this.y = y + "px";
this.width = w;
this.height = h;
this.options = options;
this.el = $("<div id='" + this.id + "' class='" + _class + "'></div>").css('left', this.x).css('top', this.y);
view.append(this.el);
this.x = function() {
return this.el.position().left;
}
this.y = function() {
return this.el.position().top;
}
this.up = function() {
if (this.y() > 0) {
this.el.animate({
top: '-=25px'
}, 0);
if (collisionDetect) collisionDetect(this);
}
};
this.down = function() {
if (this.y() < this.view.height() - this.height) {
this.el.animate({
top: '+=25px'
}, 0);
if (collisionDetect) collisionDetect(this);
}
};
this.left = function() {
if (this.x() > 0) {
this.el.animate({
left: '-=25px'
}, 0);
if (collisionDetect) collisionDetect(this);
}
};
this.right = function() {
if (this.x() + this.width < this.view.width()) {
this.el.animate({
left: '+=25px'
}, 0);
if (collisionDetect) collisionDetect(this);
}
this.destroy = function() {
this.el.remove();
for (var i = 0; i < sprites.length; i++) {
if (data[i].id == this.id) {
sprites.splice(i, 1);
break;
}
}
}
};
this.getPos = function() {
var pos, width, height;
pos = this.el.position();
width = this.el.width();
height = this.el.height();
return [
[pos.left, pos.left + width],
[pos.top, pos.top + height]
];
};
this.comparePos = function(p1, p2) {
var r1, r2;
r1 = p1[0] < p2[0] ? p1 : p2;
r2 = p1[0] < p2[0] ? p2 : p1;
return r1[1] > r2[0] || r1[0] === r2[0];
};
this.collidesWith = function(sprite) {
if (sprite.destroyed === true) return;
var pos1 = this.getPos(),
pos2 = sprite.getPos();
return this.comparePos(pos1[0], pos2[0]) && this.comparePos(pos1[1], pos2[1]);
};
if (this.options && this.options.init) this.options.init(this);
sprites.push(this);
};
function spawnrand() {
if (sprites.length > 100) return
var points = [50, 100, 200, 300, 400, 500];
var spelplanWidth = game.width();
var spelplanHeight = game.height();
var randPosY = Math.floor((Math.random() * spelplanHeight));
var randPosX = Math.floor((Math.random() * spelplanWidth));
var enemy = new sprite("enemy" + sprites.length + 1, randPosY, randPosX, 15, 15, "rand", game, null, {
PTS: points[RND(0, 5)],
init: function(sprite) {
sprite.selfDestruct = setTimeout(function() {
sprite.el.fadeOut(1000, function() {});
}, 5000);
}
});
enemies.push(enemy);
}
SCORE(0);
var player = new sprite("box1", 200, 200, 50, 50, "player", game,
function(sprite) {
sprites.forEach(function(sprite) {
if (sprite.id !== "box1" && player.collidesWith(sprite)) {
sprite.destroyed = true;
clearTimeout(sprite.selfDestruct);
sprite.el.fadeOut(100, function() {});
SCORE(sprite.options.PTS);
}
})
});
setInterval(spawnrand, 250);
$(document).keydown(function(e) {
if (e.keyCode == 37) {
player.left();
} else if (e.keyCode == 39) {
player.right();
} else if (e.keyCode == 38) {
player.up();
} else if (e.keyCode == 40) {
player.down();
}
});
});
</script>
</head>
<body onload="updateClock(); setInterval('updateClock()', 1000 )">
<span id="clock"> </span>
<header class="col-12 col-m-12">
<h1>Samla så mycket poäng du hinner genom att ta de gröna bollarna innan de försvinner</h1>
</header>
<div id="spelplan" class="col-6 col-m-6">
<div>
<p>Score:<span id="score"></span></p>
</div>
</div>
<section id="footer" class="col-12 col-m-12">
<h1>Använd piltangenterna för att styra den röda kuben </h1>
</section>
</body>
</html>
So again what I need help with is making the game-board "spelplan" responsive, any help is appreciated!

Categories

Resources