I am tring to create "Sinking ships" using jQuery - javascript

So far I am tring to make functions for placing ships on board and I have some problems with function for checking is some field available. My basic idea is to have one method which will be called on button click:
$("#dodaj1x1").click(function(){
var raspolozivo=parseInt($("#raspolozivo1x1").text());
if(raspolozivo>0){
generisi1x1();//call for function that generate random field
var novoRaspolozivo= raspolozivo-1;
$("#raspolozivo1x1").html(novoRaspolozivo);
}
else{
alert("Rasporedjeni svi raspolozivi brodovi ovog tipa!");
}
});
and it will call function to generate random field:
function generisi1x1(){
var minR = 0;
var maxR = 9;
var minK = 0;
var maxK = 9;
randRed=Math.floor(Math.random() * (maxR - minR + 1)) + minR;
randKol=Math.floor(Math.random() * (maxK - minK + 1)) + minK;
proveri1x1(randRed,randKol);//call to function to check is field available
}
than function generisi1x1() calls function that checks is that field available:
function proveri1x1(randRed,randKol){
for(i=randRed-1;i<randRed+2;i++){
for(j=randKol-1;j<randKol+2;j++){
if($(".red"+i+".kolona"+j+"").hasClass('deoBroda')){
alert("red:"+" "+i+" kolona:"+j);
generisi1x1();
}
else { postavi1x1(randRed,randKol);}
}
}
}
And my problem is that sometimes this work great(at least it looks that work great,maybe pure luck), and sometimes it generate only 3 ships 1x1(there should be 4) , sometimes it show me message about problem and generate 5 ships(4 on right places, 1 on bad) etc.
Printscreen of bad case: Added ship 1x1 on position 5,3 right next to ship 4x1
Here is live demo of entire code: Live demo
So far I made available to insert ships 4x1 and 1x1, and doing check only for 1x1, plan is to do the same for all ships, any help would be great.

You will find it easier to understand if proveri1x1() performs the checks and returns true or false, and generisi1x1() performs the postavi1x1() action;
function generisi1x1() {
var minR = 0, maxR = 9, minK = 0, maxK = 9;
randRed = Math.floor(Math.random() * (maxR - minR + 1)) + minR;
randKol = Math.floor(Math.random() * (maxK - minK + 1)) + minK;
if(proveri1x1(randRed, randKol)) { //call to function to check is field available
postavi1x1(randRed,randKol);//set
} else {
generisi1x1();//try again
}
}
function proveri1x1(randRed, randKol) {
for(var i=randRed-1; i<randRed+2; i++) {
for(var j=randKol-1; j<randKol+2; j++) {
if($(".red" + i + ".kolona" + j).hasClass('deoBroda')) {
return false;
}
}
}
return true;//<<<< note the position of this return statement
}

Related

Calling a function to change an objects position in an array (JavaScript)

I'm trying to figure out how I can use a function to change the array index value of an object when a function is called and I can't figure out how to do it. Here's what I have so far:
var direction = ["North","East","South","West"];
var car = function() {
/* Class Constructor */
this.cardinal = 0;
this.currentDirection = direction[this.cardinal];
this.showDirection = compass;
this.turnRight = rightTurn;
function compass()
{
document.write("<li>" + this.name + " is going " + this.direction + ".</li>");
}
function rightTurn()
{
if (this.cardinal < 4) {
this.cardinal = this.cardinal + 1;
this.showDirection();
} else {
this.cardinal = 0;
this.showDirection();
}
}
} // end car constructor
pontiac = new car();
Later I call the function buy using this
pontiac.turnRight();
The object does have a bit more to it but I removed that section to make it easier to read. I can add the additional bits if needed but I don't think it's really relevant to this. I know I'm doing the rightTurn() function incorrectly. I used the if else loop because I need it to go back to North if the car is on West (since it's the last position of the array)
Any help is appreciated!
When this.cardinal is 3,
if (this.cardinal < 4) {
this.cardinal = this.cardinal + 1;
lets it become 4, indexing out of the array (valid indices are 0, 1, 2 and 3).
So you need 3 in the comparison:
if (this.cardinal < 3) {
this.cardinal = this.cardinal + 1;
Hope this can help you
var car = function() {
/* Class Constructor */
this.directions = ["North","East","South","West"];
this.currentIndex = 0;
this.showDirection = compass;
this.turnRight = rightTurn;
this.name = "car"
function compass()
{
document.write("<li>" + this.name + " is going " + this.directions[this.currentIndex] + ".</li>");
}
function rightTurn()
{
if (this.currentIndex == (this.directions.length-1)) {
this.currentIndex = 0;
this.showDirection();
} else {
this.currentIndex++;
this.showDirection();
}
}
} // end car constructor
pontiac = new car();
pontiac.turnRight()
every time you call pontiac.turnRight() you will set the current direction to right element beside, and when you get to "west" yo will go back to "North".
Remember that this.direction needs to be this.direction everywhere inside your class. If I were you I'd change the name of your your array from direction to cardinals or something, so you don't confuse yourself.

Attempting to make a repeat function in java that will repeat a function 'x' times and will then proceed to load another function after 'x' times

I'm working on trying to create a random image generator that will show a random image in Javascript. I've been able to make it show a random image via the Javascript math and using random variables. But sadly I'm still yet to be eligible to make my code repeat itself.
I know its probably very simplistic but as you know, we all start from somewhere. I've tried my best to compact my code and I have looked at other stackoverflow recourses but im still in no luck.
A quick overview of what happens, you are meant to be able to press a button and then, a selected random image is replaced by the current one.
What I want: to be able to press a button and then it will proceed to cycle through the random images 'x' times.
My code:
function imgRandom() {
var myImages1 = new Array();
myImages1[1] = "images/Random/Icon1.png";
myImages1[2] = "images/Random/Icon2.png";
myImages1[3] = "images/Random/Icon3.png";
myImages1[4] = "images/Random/Icon4.png";
myImages1[5] = "images/Random/Icon5.png";
myImages1[6] = "images/Random/Icon6.png";
myImages1[7] = "images/Random/Icon7.png";
myImages1[8] = "images/Random/Icon8.png";
myImages1[9] = "images/Random/Icon9.png";
myImages1[10] = "images/Random/Icon10.png";
myImages1[11] = "images/Random/Icon11.png";
myImages1[12] = "images/Random/Icon12.png";
myImages1[13] = "images/Random/Icon13.png";
myImages1[14] = "images/Random/Icon14.png";
myImages1[15] = "images/Random/Icon15.png";
myImages1[16] = "images/Random/Icon16.png";
myImages1[17] = "images/Random/Icon17.png";
myImages1[18] = "images/Random/Icon18.png";
myImages1[19] = "images/Random/Icon19.png";
myImages1[20] = "images/Random/Icon20.png";
myImages1[21] = "images/Random/Icon21.png";
myImages1[22] = "images/Random/Icon22.png";
myImages1[23] = "images/Random/Icon23.png";
var rnd = Math.floor(Math.random() * myImages1.length);
if (rnd == 0) {
rnd = 1;
}
document.getElementById("gen-img").src = myImages1[rnd];
}
<center>
<p>
<img id="gen-img" class="character-image" src="images/QuestionMark.png" style="width:180px;height:310px;">
</p>
<p>
<input type="button" class="button" value="Choose" onclick="setTimeout(imgRandom, 3000);" />
</p>
</center>
I hope this isn't too confusing, i'll be active for a long time if you're able to help! Thanks,
David.
I refactored your code a bit with an possible approach Here's the fiddle: https://jsfiddle.net/mrlew/d2py2jvb/
I commented with some explanations.
/* some flags you can set */
var timesTocycle = 10;
var totalImagesToCreate = 23;
var timeBetweenCycle = 3000;
/* global variables */
var allMyImages = [];
var timesCycled = 0;
/*
function to create your images path.
Called once when you load your page.
*/
function createMyImages(total) {
for (var i=0; i<total;i++) {
var imageNumber = i+1;
var path = getImagePath(imageNumber);
allMyImages.push(path);
}
}
/* separated your path getter */
function getImagePath(imageNumber) {
return "images/Random/Icon" + imageNumber + ".png";
}
/* this is the function called when you press the button and when one cycle ends */
function triggerRandomImage() {
if (timesCycled >= timesTocycle) return;
setTimeout(displayRandomImage, timeBetweenCycle);
}
/* random integer javascript function */
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
/* function called on setTimeout */
function displayRandomImage() {
var rnd = getRandomInt(0,allMyImages.length-1);
var imageToDisplayPath = allMyImages[rnd];
document.getElementById("gen-img").src = imageToDisplayPath;
timesCycled++;
triggerRandomImage();
/* debug info */
document.getElementById('info').innerText = "(showing: " + imageToDisplayPath + ", cycle: " + timesCycled + ", max: " + timesTocycle + ")";
}
/* call this function to populate the allMyImages array */
createMyImages(totalImagesToCreate);
I believe what you want is for loop. Let me demonstrate with your code:
var count = 10; //number of times to run the for loop
for (i = 0; i < count; i++){
var rnd = Math.floor(Math.random() * myImages1.length);
if (rnd == 0) {
rnd = 1;
}
document.getElementById("gen-img").src = myImages1[rnd];
}
The above code would run the randomizing bit 10 times (= 10 images). Now, I have not tested it yet, but I believe that the images would flash by really quickly. Also, unrelated to the question you may want to read about Javascript arrays.

Select Random Images, check if in specific range and display accordingly

I need to draw 5 cards, and check whether these are of the same type (Heart, Spade etc.)
I given them names from 1-52 (where 1-13 are hearts, etc.)
Now I need to create a JavaScript function that selects 5 cards from these 52 checks if these are of same type (eg. spade)
If it's true, than show those cards in a table, otherwise, repeat loop till successful and I need to show how many times the loop repeated.
I tried some approaches, but since I don't know much about JavaScript, I'm stuck. Could someone please help me with this?
Here is what I've tried :
function flush() {
for (var picked_card = 0; picked_card < 6; picked_card++) {
var picked_card = Math.floor(Math.random() * 52) + 1;
document.write(
'<table>'
'<tr>'
'<td>'
'<img src="' + picked_card + '" '.jpg />'
'</td>'
);
}
}
Here you go:
var hand = [];
var loopCount = 0;
while (hand.length < 5) {
var picked_card = Math.floor(Math.random() * 52) + 1;
var handEmpty = hand.length == 0;
if (handEmpty) {
hand.push(picked_card);
}
else {
var cardInHand = hand.indexOf(picked_card) != -1;
var handColor = Math.floor((hand[0] - 1) / 13);
var cardColor = Math.floor((picked_card - 1) / 13);
if (!cardInHand && cardColor == handColor) {
hand.push(picked_card);
}
else {
loopCount++;
}
}
}
And to display:
document.write('<table><tbody><tr>');
for(i in hand) {
document.write('<td><img src="' + hand[i] + '.jpg" /></td>');
}
document.write('</tr></tbody></table>');
To find the card-type make an integer-division by 13 of the 'card name', using names of 0..51. for 0..12 you'll get 0: Heart, for 13..25 1: Spade, etc. Than draw while picking cards of the same type; re-try on the first card of another type. When you got 5 cards together, you're done.
function drawFlush() {
for(var count = 0;; count++) {
var type = -1;
var picked_cards = [];
while(picked_cards.length < 5) {
var card;
do {
card = Math.floor(Math.random() * 52);
} while( -1 != picked_cards.indexOf(card));
var card_type = Math.floor( card / 13);
if( -1 == type) {
type = card_type;
} else {
if(card_type != type) {
break;
}
}
picked_cards.push(card);
}
}
return {
number_of_tries : count,
picked_cards : picked_cards
}
}
#Samy: right, not pick a card twice ;-)
Note: Here it is counted how many times a complete hand of 5 cards must be drawn until the first 'flush' appears. In theory, this should average on 1 * (12/51) * (11/50) * (10/49) * (9/48), for each draw as the number of 'positive' possible choices out of the number of remaining cards, if you're interested in this.

For Loop MovieClip Grid not showing on stage

So I'm a newbie and should obviously spend time in the tuts, but I'm looking for a quick answer. Basically, I've created a grid of movie clips with AS3. When I 'preview' the flash (as a flash or HTML) it shows up fine. Success. Yet, the stage remains empty.
Q1) Will the stage remain empty as I have used AS3 to dynamically 'draw' the grid of mc's? Or is there a slit of code I am missing to make this baby show up on the stage?
Q2) I've managed to use alpha to make the MC's 'fade' on hover - but I want to make them change color (to red) when hovered over. I've searched everywhere and can't seem to find the right script.
Here is my code:
var stage = new createjs.Stage("canvas");
var image = new createjs.Bitmap("images/square.png");
stage.addChild(image);
createjs.Ticker.addEventListener("tick", handleTick);
function handleTick(event) {
image.x += 10;
stage.update();
}
var x0:Number = 0;
var y0:Number = 0;
var nt:Number = 72;
var nc = 10;
var vd:Number = 12;
var hd:Number = 12;
for (var i = 1; i <= nt; i++) {
var mc = this.attachMovie("square", "square" + i, i);
var aprox = Math.floor((i - 1) / nc);
mc._x = x0 + hd * ((i - aprox * nc) - 1);
mc._y = y0 + aprox * vd;
mc.useHandCursor = true;
// fade in
mc.onRollOver = function()
{
this.onEnterFrame = function()
{
if (this._alpha > 0) {
this._alpha -= 10;
} else {
this._alpha = 0;
delete this.onEnterFrame;
}
};
};
// fade out
mc.onRollOut = function()
{
this.onEnterFrame = function()
{
if (this._alpha < 100) {
this._alpha += 10;
} else {
this._alpha = 100;
delete this.onEnterFrame;
}
};
};
}
Thanks in advance - sorry I am a noob.
This will never work. 1/3 of your code is in AS3, 2/3 in AS2. Considering you haven't been thrown any error, I assume you exported it as AS2.

HTML Canvas Scratcher, reveal a div when percentage of image is scratched

I'm using this script I found for a scratch card type effect (from http://beej.us/blog/data/html-canvas-scratcher-2/). What code would I need to add, in order to show a hidden div once a certain percentage (say 70%) of the image is "scratched out".
Thanks.
**
* This file controls the page logic
*
* depends on jQuery>=1.7
*/
(function() {
/**
* Returns true if this browser supports canvas
*
* From http://diveintohtml5.info/
*/
function supportsCanvas() {
return !!document.createElement('canvas').getContext;
};
/**
* Handle scratch event on a scratcher
*/
function scratcher1Changed(ev) {
// Test every pixel. Very accurate, but might be slow on large
// canvases on underpowered devices:
//var pct = (scratcher.fullAmount() * 100)|0;
// Only test every 32nd pixel. 32x faster, but might lead to
// inaccuracy:
var pct = (this.fullAmount(32) * 100)|0;
$('#scratcher1Pct').html('' + pct + '%');
};
/**
* Reset all scratchers
*/
function onResetClicked(scratchers) {
var i;
for (i = 0; i < scratchers.length; i++) {
scratchers[i].reset();
}
return false;
};
/**
* Assuming canvas works here, do all initial page setup
*/
function initPage() {
var scratcherLoadedCount = 0;
var scratchers = [];
var i, i1;
// called each time a scratcher loads
function onScratcherLoaded(ev) {
scratcherLoadedCount++;
if (scratcherLoadedCount == scratchers.length) {
// all scratchers loaded!
// bind the reset button to reset all scratchers
$('#resetbutton').on('click', function() {
onResetClicked(scratchers);
});
// hide loading text, show instructions text
$('#loading-text').hide();
$('#inst-text').show();
}
};
// create new scratchers
var scratchers = new Array(1);
for (i = 0; i < scratchers.length; i++) {
i1 = i + 1;
scratchers[i] = new Scratcher('scratcher' + i1);
// set up this listener before calling setImages():
scratchers[i].addEventListener('imagesloaded', onScratcherLoaded);
scratchers[i].setImages('images/s' + i1 + 'bg.jpg',
'images/s' + i1 + 'fg.gif');
}
// get notifications of this scratcher changing
// (These aren't "real" event listeners; they're implemented on top
// of Scratcher.)
scratchers[0].addEventListener('reset', scratcher1Changed);
scratchers[0].addEventListener('scratch', scratcher1Changed);
// Or if you didn't want to do it every scratch (to save CPU), you
// can just do it on 'scratchesended' instead of 'scratch':
//scratchers[2].addEventListener('scratchesended', scratcher3Changed);
};
/**
* Handle page load
*/
$(function() {
if (supportsCanvas()) {
initPage();
} else {
$('#scratcher-box').hide();
$('#lamebrowser').show();
}
});
})();
http://jsfiddle.net/MT4nK/11/
You already had this:
<div class="hidden" id="show">This div to appear after 40% scracthed</div>
I added this to your CSS:
.show{
display:block;
}
And this to your javascript:
function scratcher1Changed(ev) {
// Test every pixel. Very accurate, but might be slow on large
// canvases on underpowered devices:
//var pct = (scratcher.fullAmount() * 100)|0;
// Only test every 32nd pixel. 32x faster, but might lead to
// inaccuracy:
var pct = (this.fullAmount(32) * 100) | 0;
$('#scratcher1Pct').html('' + pct + '%');
//*******************
if(pct >= 40){
$('#show').addClass( "show" )
}
//*************** Added This...
};
EDIT**
You'll also need to set the class back to hidden when you reset FYI.

Categories

Resources