I cant make it so after 5 tries it counts as dead - javascript

I keep trying to make it work but it simply won't. Please help.
Btw I want it so that when you die it resets.
<!DOCTYPE html>
<html>
<head>
<style>
html,button{
font-family: monospace, monospace;
width:20%;
padding:0%;
margin:0%;
}
button{
text-align: left;
height:150px;
position:absolute;
background-color:transparent;
border:transparent;
outline:none;
}
div{
position:absolute;
transform:translate(20px,-40px);
}
</style>
<script>
var roll = 0;
function play(){//begin
var rep = Math.floor(Math.random() * 6);
if (rep == 0 && roll !== 6){
roll+=1
document.getElementById("hk").innerHTML = "._______<br>\\(#)----'<br>/ /\\<br>(_(<br>";
setTimeout(4000);
setTimeout(function(){
document.getElementById("hk").innerHTML = ",_______<br>\\(=)----*#<br>/ //<br>(_(<br> DEAD";
}, 500);
}else if (rep !== 0 || roll == 6){
document.getElementById("hk").innerHTML = "._______<br>\\(#)----'<br>/ /\\<br>(_(<br>";
setTimeout(function(){
document.getElementById("hk").innerHTML = ",_______<br>\\(=)----'<br>/ //<br>(_(<br>Click";
}, 500);
var roll = 0;
}
}//end
</script>
</head>
<body>
<h1>Russian<br>Roulette</h1>
<button onClick="play()">
<div id="hk">
,_______<br>
\(=)----'<br>
/ /\<br>
(_(<br>
</div>
</button>
<p>click the gun</p>
</body>
</html>
Please no jquery or anything like it.
The javascript and only the javascript do I need help with.
It doesn't let me post this without adding more text so I am currently adding more text so I can post this.

Related

How do I write a javascript with a for loop that repeats a word?

I'm self taught in javascript but I have been struggling to do this, I want to create a js where it has two functions, one works just for the "for loop". And the second one goes for the buttom which only will ask the user two questions with two prompts, one word, and how many times does the user would like to repeat it.
for example, if the user writes "Hello" in the first prompt and then writes "3" in the second prompt question, the outpur needs to be "HelloHelloHello"
I would really appreciate your help,
this is my html
<!DOCTYPE html>
<html>
<head>
<script src="practice1.js"></script>
<title>Repetition</title>
</head>
<body>
<h1> repetition of words </h1>
<p id="resultLoop"> ----- </p>
<button onclick="askUser()">Do the repetitions</button>
</body>
</html>
If you need to use a for loop, then there are a few ways to do this. One way would be to create an array and push the string they input an n number of times. Then join them together.
Example:
let result = [];
const n = 3;
const stringToRepeat = "hello";
for (let i = 0; i < n; i++) {
result.push(stringToRepeat);
}
result = result.join("");
console.log(result);
Output:
hellohellohello
Another way would be to simply concatenate the strings within each iteration of your for loop. Example:
let result = "";
const n = 3;
const stringToRepeat = "hello";
for (let i = 0; i < n; i++) {
result += stringToRepeat;
}
console.log(result);
Output:
hellohellohello
Although String.prototype.concat() also concatenates strings, they recommend using assignment operators for performance reasons.
If you didn't need to use a for loop, then String.prototype.repeat() does exactly what you want. Although, it is still not compatible with Internet Explorer.
Here's an example of what I mean:
//<![CDATA[
/* js/external.js */
let doc, htm, bod, nav, M, I, mobile, S, Q, hC, aC, rC, tC, allGood; // for reuse on other loads
addEventListener('load', ()=>{
doc = document; htm = doc.documentElement; bod = doc.body; nav = navigator; M = tag=>doc.createElement(tag); I = id=>doc.getElementById(id);
mobile = nav.userAgent.match(/Mobi/i) ? true : false;
S = (selector, within)=>{
let w = within || doc;
return w.querySelector(selector);
}
Q = (selector, within)=>{
let w = within || doc;
return w.querySelectorAll(selector);
}
hC = (node, className)=>{
return node.classList.contains(className);
}
aC = function(){
const a = [...arguments];
a.shift().classList.add(...a);
return aC;
}
rC = function(){
const a = [...arguments];
a.shift().classList.remove(...a);
return rC;
}
tC = function(){
const a = [...arguments];
a.shift().classList.toggle(...a);
return tC;
}
allGood = nodeArray=>{
for(let n of nodeArray){
if(!hC(n, 'good')){
return false;
}
}
return true;
}
// small library above - magic below can be put on another page using a load Event (except // end load line)
const rep_text = I('rep_text'), rep_x = I('rep_x'), rep_it = I('rep_it'), out = I('output'), goods = [rep_text, rep_x];
rep_text.oninput = function(){
let f = this.value.trim() === '' ? rC : aC; // remove or add class
f(this, 'good');
}
rep_x.oninput = function(){
let f = this.value.match(/^[1-9][0-9]*$/) ? aC : rC;
f(this, 'good');
}
rep_it.onclick = ()=>{
out.textContent = allGood(goods) ? rep_text.value.repeat(+rep_x.value) : '';
// out.scrollIntoView(); // use this but it's a Stack Overflow issue
}
}); // end load
//]]>
/* css/external.css */
*{
box-sizing:border-box; color:#fff; padding:0; margin:0; outline:none; -moz-user-select:none; -ms-user-select:none; -webkit-user-select:none; user-select:none; overflow:hidden;
}
html,body,.main{
width:100%; height:100%;
}
.main{
background:#333; padding:5px; overflow:auto;
}
.main *{
font:bold 22px Tahoma, Geneva, sans-serif;
}
label>span{
cursor:pointer; display:inline-block; height:27px; text-shadow:-1px 0 #000,0 1px #000,1px 0 #000,0 -1px #000; float:left;
}
input[type=text],input[type=number]{
width:100%; height:38px; background:#fff; color:#000; border-radius:3px; border:1px solid #c00; padding:5px; margin:3px 0; box-shadow:none; -moz-user-select:text; -ms-user-select:text; -webkit-user-select:text; user-select:text;
}
input[type=button],button{
cursor:pointer; width:100%; background:linear-gradient(#1b7bbb,#147); color:#fff; font:bold 28px Tahoma, Geneva, sans-serif; padding:5px; border:1px solid #007; border-radius:10px; margin-top:7px;
}
input.good{
border-color:#0c0;
}
#output{
color:#aaf; margin:5px 10px; text-overflow:ellipsis;
}
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1, user-scalable=no' />
<title>Title Here</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script src='js/external.js'></script>
</head>
<body>
<div class='main'>
<label><span>Text to Repeat</span><input id='rep_text' type='text' value='' /></label>
<label><span>Times to Repeat</span><input class='good' id='rep_x' type='number' value='1' min='1' /></label>
<input id='rep_it' type='button' value='REPEAT' />
<div id='output'></div>
</div>
</body>
</html>

How to prevent html buttons from moving back and forth when I adjust a range slider

When I adjust this range slider, the coresponding text to the right which indicates the video Playback rate, changes from a single digit (i.e. 1) to multiple digits (i.e 0.95). Everytime I do so it causes the buttons directly to the right of the text to move back and forth. I’m wondering how to prevent this movement from happening? I’ve tried adding some space, padding, margin, etc. between the text and buttons but I can’t seem to make it stop. I would defenitely like to keep all of the objects on the same line. Is there a way for example to make the default number of digits constant? For example when it’s set to 1, could it be 1.00 instead, and when it’s .8 can it be 0.80 isntead? I’m not sure if that would work since the playbackrate atribute seems to require a specific number of digits.
<!DOCTYPE html>
<html>
<head>
<style>
div#videoPlayerBox{ width:550px; background:#000; margin:0px auto;}
div#videoControlsBar{ background: #333; padding:10px; color:#CCC; font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;}
#pbr{ width:40%;}
div#PlaybackRateBox{ margin:left; width:28%; text-align:center; border: solid 3px #000; background:#FFF; padding:0px;}
</style>
<script>
var v,p,c;
function myFunction(){document.getElementById("myForm").reset();}
function setPlaySpeednormal(){ c.innerHTML = 1;v.playbackRate = 1;}
function restartVideo(){v.pause();v.currentTime = 0;v.play();}
window.onload = function() {
v = document.getElementById("myVideo");
p = document.getElementById("pbr");
c = document.getElementById("currentPbr");
p.addEventListener('input',function(){
c.innerHTML = p.value;
v.playbackRate = p.value;
},false);
};
</script>
</head>
<body>
<div id="videoPlayerBox">
<video id="myVideo" width="100%" poster="https://www.dropbox.com/s/8qbvpxvtedcs5lq/2016-07-30_Milonga%20Triste_Guillermo%20Garcia_Tango%20Atipico_San%20Francisco.jpg?raw=1" controls>
<source src="https://www.dropbox.com/s/5rjbtmantuow8vw/testvideo_hfd.mp4?raw=1"
type='video/mp4'/>
Your browser does not support HTML video.
</video>
<div id="videoControlsBar">
<form id= "myForm">
<input id="pbr" type="range" value="1" min="0.5" max="1.2" step="0.05" class="slider">
<span>Speed <span id="currentPbr">1</span>
<input type="button" value="Reset" onclick="myFunction();setPlaySpeednormal();">
<input type="button" value="Restart" onclick="restartVideo();">
</form>
</div>
</div>
</body>
</html>
Try adding this #currentPbr line to your style block as shown below (the last line). Adjust the width to your liking
<style>
div#videoPlayerBox{ width:550px; background:#000; margin:0px auto;}
div#videoControlsBar{ background: #333; padding:10px; color:#CCC; font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;}
#pbr{ width:40%;}
div#PlaybackRateBox{ margin:left; width:28%; text-align:center; border: solid 3px #000; background:#FFF; padding:0px;}
#currentPbr {display: inline-block; min-width: 80px;}
</style>
Here's a function that might help you:
parseNum = (num) => (num == 1 || num === 0) ? num + '.00' : (String(num).length == 3 ? num + '0' : num)
So, now you can call this function before giving value to c.innerHTML. Thus, instead of c.innerHTML = p.value, You can do:
var v,p,c;
function myFunction(){document.getElementById("myForm").reset();}
function setPlaySpeednormal(){ c.innerHTML = 1;v.playbackRate = 1;}
function restartVideo(){v.pause();v.currentTime = 0;v.play();}
const parseNum = (num) => (num == 1 || num === 0) ? num + '.00' : (String(num).length == 3 ? num + '0' : num)
window.onload = function() {
v = document.getElementById("myVideo");
p = document.getElementById("pbr");
c = document.getElementById("currentPbr");
p.addEventListener('input',function(){
c.innerHTML = parseNum(p.value);
v.playbackRate = p.value;
},false);
};
Here's a screenshot of the function in action:
PS Be sure not to use this function with every number. It just works for the domain of the volume.

Random card/Image using buttonjavascript

I want to create a card game using java script. Being a beginner at java script, I am finding great difficulty finding a suitable tutorial for what I am trying to do. When the 'start game' button is selected, I want the computer to produce a random card. I have tried many ways of doing this and have came to no avail. Here is my code.
<html>
<head>
<title> Christmas Assignment </title>
<link rel="stylesheet" type="text/css" href="xmasass_1.css">
<script type = "text/javascript">
function randomImg(){
var myimages= [];
myimages[1] = "cards/1.gif";
myimages[2] = "cards/2.gif";
myimages[3] = "cards/3.gif";
myimages[4] = "cards/4.gif";
myimages[5] = "cards/5.gif";
myimages[6] = "cards/6.gif";
myimages[7] = "cards/7.gif";
myimages[8] = "cards/8.gif";
myimages[9] = "cards/9.gif";
myimages[10] = "cards/10.gif";
myimages[11] = "cards/11.gif";
myimages[12] = "cards/12.gif";
myimages[13] = "cards/13.gif";
function oddTrivia(){
var randomImg = Math.floor(Math.random()*(oddtrivia.length));
document.getElementById('comp').InnerHTML=myimages[randomImg];
}
ar total = 0;
function randomImg(){
var x = Math.floor(Math.random()*13)+1;
document.getElementById('img1').src = 'die'+x+'.gif';
document.getElementById('img2').src = 'die'+y+'.gif';
document.getElementById('score').innerHTML = total;
}
var card1Image;
var card2Image;
var card3Image;
var card4Image;
var card5Image;
var card6Image;
function start(){
var button = document.getElementById("startButton");
button.addEventListener("click", pickCards, false);
card1Image = document.getElementById("1");
card2Image = document.getElementById("2");
card3Image = document.getElementById("3");
card4Image = document.getElementById("4");
card5Image = document.getElementById("5");
card6Image = document.getElementById("6");
}
function pickCards(){
setImage(card1Image);
setImage(card2Image);
setImage(card3Image);
setImage(card4Image);
setImage(card5Image);
setImage(card6Image);
}
function setImage(cardImg){
var cardValue = Math.floor(1 + Math.random() * 13);
cardImg.setAttribute("src", "C:Xmas Assignment/cards/" + cardValue + ".gif");
}
window.addEventListener("load", start, false);
</script>
</head>
<body>
<div id = "settings">
<img src = "settings_img.png" width = "60" height = "60">
</div>
<div id = "bodydiv">
<h1> Card Game</h1>
<div id = "computer">
<img src = " cards/back.gif">
</div>
<div id = "comp" > Computer </div>
<div id ="arrow">
<img src ="arrow2.png" width = "100" height="100">
</div>
<div id = "player">
<img src = " cards/back.gif">
</div>
<div id = "play"> Player </div>
<div id = "kittens">
<button id = "startButton" onclick ="randomImg" > Start Game </button>
<div id = "buttons_1">
<button id ="higher"> Higher
</button>
<button id = "equal"> Equal
</button>
<button id = "lower"> Lower
</button>
</div>
<button id = "draw"> Draw your Card
</button>
<div id = "resetscore"> Reset Score
</div>
</div>
<div id = "score">
</div>
</div>
</body>
</html>
body {
background:#66ccff;
}
h1 {
text-align:center;
}
#settings {
float:right;
margin-top:10px;
}
#bodydiv {
width: 800px;
height:600px;
margin-left:200px;
margin-top:40px;
margin-bottom:60px;
background:#ffccff;
border-radius: 10px;
}
#computer {
border-radius: 10px;
position: absolute;
left:35%;
top:27%;
}
#player {
border-radius: 10px;
position: absolute;
left:55%;
top:27%;
}
#start_game {
width :120px;
height: 55px;
margin-left: 350px;
margin-top:50px;
background:white;
border:1px solid black;
}
#buttons_1 {
text-align: center;
margin-top:20px;
}
#higher {
width:140px;
height:50px;
font-size: 15px;
border-radius:10px;
font-weight:bold;
}
#equal {
width:140px;
height:50px;
font-size: 15px;
border-radius:10px;
font-weight:bold;
}
#lower {
width:140px;
height:50px;
font-size: 15px;
border-radius:10px;
font-weight:bold;
}
#draw {
width:160px;
height:30px;
margin-left:325px;
margin-top: 30px;
border:1px solid black;
background:#FFFFCC;
}
#resetscore {
text-align: center;
margin-top: 40px;
}
#arrow {
margin-left:370px;
margin-top:-130px;
}
#comp {
margin-top:240px;
margin-left:265px;
}
#play{
margin-top:10px;
margin-left:540px;
}
You code is kind of hard to read.
You forgot to close the "{" of your main function.
You are declaring "randomImg" again in the body of the "randomImg" function(use a different name).
You wrote
ar total = 0;
I think you meant to write:
var total = 0;
oddtrivia in the function "OddTrivia" is not defined.
y in the inner randomImg function is not defined.
Having poked a little bit at the code, here is a few things:
Problem no 1: randomImg()
It's hard to know your intentions, but you should likely begin with removing the start of your first function randomImg(){.
Because 1) It does not have an end and 2) If it actually spans everything then this line window.addEventListener("load", start, false); will not load on startup (since it does not get executed until randomImg() gets executed, and by then the page has already loaded.)
Problem no 2: Cannot set property 'src' of null"
Now when the first problem is out of the way, you should see "Uncaught TypeError: Cannot set property 'src' of null" if you look in your console. Yes, USE YOUR CONSOLE. Click on the error to show what causes it. Here it is:
cardImg.setAttribute("src", "C:Xmas Assignment/cards/" + cardValue + ".gif");
This means that cardImg is null. We backtrack the first call of setImage() and find that the variable card1Image is passed in. So that must mean that card1Image also is null. You can check it yourself by adding a console.log('card1Image', card1Image); in your code. Or you add a breakpoint at that point. (Use the sources-tab in chrome dev tools, click at the line-numbering to add a break point. Refresh the page and it will stop at the break point. Now you can mouse-over variables to see their values.)
Let's look at where 'card1Image' is set.
card1Image = document.getElementById("1");
So why is this returning null? Do we even have a id="1" element in the html? That could be the reason. (It is.)
There are more problems, but I'll stop there, but when you have fixed this part AND have no errors please ask again. Always check your errors and if you ask a question here you should provide errors. And when you can also be more specific with your questions.
What might someone else have done differently?
When it comes to playing cards, why not an array of objects?
var cards = [
{ src : 'cards/1.gif', value: 1 },
{ src : 'cards/2.gif', value: 2 },
{ src : 'cards/3.gif', value: 3 },
{ src : 'cards/4.gif', value: 4 }
]; // (You can of course use code to generate it.)
// Then a function to put cards in the player's hand.
var playerHand = _.sample(cards, 2);
console.log(playerHand);
Here I assume lodash, a lightweight library for when you don't want to re-invent the wheel.

how can I dynamically resize an html textbox to avoid overflowing?

I would like to know how to resize a textbox to prevent text nearby it from overflowing.
I have 3 elements in a row, a label, a text box, and a button. the label however, can have words of varying lengths. if the word is too long it will move the text input too far to the side and the button will overflow onto the next line. to preserve the style of the page, I would prefer that the button stays on the same line as the other 2 elements.
I am trying to get the text box to shrink only as much as necessary to allow room for the other elements.
can I do this with JQuery?
Edit: here's the JFiddle thing:
http://jsfiddle.net/425ve/2/
and here's the main code:
<html>
<head>
<style>
body{
background-color:#000000;
color:#cccccc;
}
#chatbox{
width:100%;
height:85%;
border-style:solid;
border-color:#000000;
overflow:auto;
}
#mainchat{
width:82%;
float:left;
margin:0;
}
#sidebar{
float:left;
height:97%;
width:17%;
border-style:dashed;
border-width:1px;
border-color:#AAAAAA;
border-right:0;
border-top:0;
border-bottom:0;
overflow:auto;
}
#topbar{
border-style:dashed;
border-width:1px;
border-color:#AAAAAA;
border-left: 0;
border-top: 0;
float:left;
width:82%;
}
a{
color:#cccccc;
text-decoration:none;
}
a:hover{
color:#CCCCEE;
background-color:111122;
}
#topbarname{
float:right;
}
#message{
width: 90%;
background-color:#000000;
border-color:#CCCCCC;
border-style:solid;
border-width: 1px;
color:CCCCCC;
}
#submitbutton{
background-color:#000000;
border-color:#CCCCCC;
border-style:solid;
border-width: 1px;
color:#CCCCCC;
}
</style>
<script>
function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
}
else
{
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
}
return unescape(dc.substring(begin + prefix.length, end));
}
function doSomething() {
var myCookie = getCookie("IceID");
if (myCookie == null) {
window.location="login.php"
}
else {
// do cookie exists stuff
}
}
doSomething();
</script>
</head>
<body>
<div id="topbar">
| Information | Logs | characters | Profile | Private logs | Messages | Logout |
</div>
<div id="mainchat">
<div id="chatbox">
<?php
include("getpost.php");
//improve this with AJAX!
?>
</div>
<div id="input">
<form id="inputchat">
<b id="name">
<?php
echo $_COOKIE['IceID'];
?>
</b>
<input type="text" name="message" id="message"></input>
<input type="submit" id="submitbutton" value="say"></input>
</form>
</div>
<div id="utools">
</div>
</div>
<div id="sidebar">
<div id="title">
A
</div>
<div id="list">
</div>
</div>
</body>
</html>
Edit:to clarify, the name doesn't actively change while the page is being used(only right before being displayed), but it will be different depending on who loads the page. their username fits into that label.
You don't need jQuery. jQuery could make it much simpler though. I prefer vanilla.
var left = document.getElementById('name')
var resizable = document.getElementById('message')
var right = document.getElementById('submitbutton')
realign()
window.addEventListener('resize', realign)
function realign() {
resizable.style.width = '0'
var extraWidth = getWidth(resizable) // Measure the border and padding on it's own.
resizable.style.width = getWidth(resizable.parentNode) - getWidth(left) - getWidth(right)
function getWidth(element) { // Superior to offsetWidth because it measures fractions of a pixel which is even more relevant when using the browser zoom feature.
var rect = element.getBoundingClientRect() // A accurate way to measure location on the screen.
return rect.right - rec.left // The accurate width.
}
}
The only adjustment you need would be to fix my typo(s) if I made any and then if you want to support older versions of IE, you need to use the alternative to addEventListener, Google it.

JavaScript for loop not changing link text

I have a nested for loop inside a for loop that is supposed to change the link text to a random number between 1 and 5. The ID of the links are "aX_Y", X and Y being numbers. The links are arranged in a 4x3 square. The problem is that the random numbers for the link text is only displayed for the last row:
<!DOCTYPE html>
<html>
<head>
<title>RISK</title>
<style type="text/css" media="screen">
a:link, a:visited {color: #eee;border:3px solid #ccc;text-decoration:none;padding:20px;}
.one {background: #7B3B3B;}
.two {background: #547980;}
#status {color: #eee;padding:1px;text-align:center}
.current {border:3px solid #000;}
</style>
<script type="text/javascript" charset="utf-8">
var xTurn = true;
var gameOver = false;
var numMoves = 0;
function newgame()
{
var status = document.getElementById('status');
numMoves = 0;
gameOver = false;
xTurn = true;
status.innerHTML = 'Player One\'s turn';
for(var x = 0; x < 4; x++)
{
for(var y = 0; y < 3; y++)
{
document.getElementById('a' + x + '_' + y).innerHTML = Math.floor(Math.random()*5 + 1);
console.log('a' + x + '_' + y);
}
}
}
function current(selected)
{
var status = document.getElementById('status');
var value = selected.value;
}
//document.getElementById("status").setAttribute("class", "two");
</script>
<meta name="viewport" content="user-scalable=no, width=device-width" />
</head>
<body onload='newgame();'>
<p id="status" class="one">Player One's turn</p>
<br />
<br />
<br />
<br /><br />
<p><input type="button" id="newgame" value="New Game" onclick="newgame();" /></p>
</body>
</html>
Here is a direct link to it:
https://dl.dropbox.com/u/750932/iPhone/risk.html
This change to your CSS fixes the issue:
a:link, a:visited
{
color: #eee;
border:3px solid #ccc;
text-decoration:none;
display:inline-block;
padding:20px;
}
(Tested in Firefox)
Your Javascript code is fine; all of the grid squares are getting populated with random numbers. What I am seeing instead is that each row of links is overlapping the previous row, so the numbers in the previous row are being hidden.
Is the overlapping intentional?
All the random numbers are being generated correctly. The top 2 rows are just hidden due to your CSS rules. You can prove this by making the following CSS change:
Change the line that looks like this:
a:link, a:visited {color: #eee;border:3px solid #ccc;text-decoration:none;padding:20px;}
to this:
a:link, a:visited {color: #eee;border:3px solid #ccc;text-decoration:none;}
And voila, it's all working beautifully.
Heh, I'm pretty sure it is working...the other boxes are just overlapped by the ones in front and you can't see them. Firebug shows values inside all the boxes.
a {
display:block;
float:left;
}
br {
clear:both;
}
...though actually those top-level elements shouldn't be restyled like that necessarily, I'd put it all in a <div id="game"></div> and make them .game a and .game br.

Categories

Resources