...

View Full Version : Need some help with functions (homework)



sparhavk
06-29-2010, 05:30 AM
Hello all,
I’ve got a homework to do and I'm stuck, as you can see i have done all the function's (i think they are ok but not shure) with a main program I'm stuck don’t know even where to begin :/ could anyone please please help a bit?

best regards


<HTML>
<HEAD>
<TITLE>
The game of 21
</TITLE>

<SCRIPT LANGUAGE = "JavaScript">

//FUNCTIONS
/*
*removes a given number of sticks
*
*function takes one argument numberToRemove that represents the number of sticks to be removed
* if numberToRemove is more than numberOfSticks, reduces numberOfSticks to 0
* otherwise reduces numberOfSticks by numberToRemove
*function returns no value
*/
function removeSticks(numberToRemove)
{
if (numberOfSticks< numberToRemove)
{
numberOfSticks =0
}
else
{
(numberOfSticks = numberOfSticks - numberToRemove);
}

}

/*
*switches current player
*
*function takes no argument
* if current player is 1, sets current player to 2
* otherwise sets current player to 1
*function returns no value
*/

function switchCurrentPlayer()
{
if (currentPlayer ==1)
{
return currentPlayer = 2;
}
{
return currentPlayer = 1;
}
}

/*
*gets a number from a prompt dialogue
*
*function takes no argument
* prompts the current player for a number of sticks to remove, with a suitable message
*function returns the number the player enters
*/

function getChosenNumber()
{
ChosenNumber = window.prompt('Player ' + currentPlayer + ': Please enter either 1, 2 OR 3.');
return ChosenNumber;
}


//VARIABLES -- do not change this section
var numberOfSticks = 21;//number of matchsticks, initially 21
var currentPlayer = 1;//player whose turn it is, Player 1 goes first
var numberChosen;//variable used to hold the number the current player chooses

//MAIN PROGRAM
The players take turns to choose how many matches to remove, as long as there are still matches left. After each go the program outputs the number of matches that still remain and if this number is zero a message is displayed to say the current player is the winner. The turn then passes to the other player.


</SCRIPT>

</HEAD>
<BODY>
</BODY>
</HTML>

Beagle
06-29-2010, 06:48 AM
OK, so we don't like doing homework for others, but let me try to get you started. You need a way for the users to control the flow of the program.

Start by creating some element that someone wants to click, like <button>Click!</button>.

Then you need to attach an event handler to the button that fires when the "click" event happens. You can do this in 3 ways. I will give you the most basic way, called DOM Level 0. It is the least desirable way to do it, but I will leave it to you to research DOM Level 1 and DOM Level 2 so you can learn at your own pace.

<button onclick="getChosenNumber();">Click!</button>

Hopefully, this breaks your mental block and gets you rolling. Have fun!

Dormilich
06-29-2010, 06:53 AM
I will give you the most basic way, called DOM Level 0. It is the least desirable way to do it, but I will leave it to you to research DOM Level 1 and DOM Level 2 so you can learn at your own pace.

there is no DOM Level 1 Event Handling. It is only addressed in levels 0, 2 & 3.

sparhavk
06-29-2010, 06:55 AM
Thanx mate, how to display a prompt window isn't the problem, my problem is ho to put the variable var numberChosen witch we can get from window prompt defined by function getChosenNumber(), but how to get the numberChosen into
function removeSticks(numberToRemove). But still thanks I will look into DOM

Dormilich
06-29-2010, 07:08 AM
my problem with this homework is the setup. personally, I’d code it as an object. that keeps the sticks, the players and the actions neatly together. but the setup requires you to use global variables (something you usually try to avoid as much as possible).


a possible setup I’d go for:

function Game()
{
this.player1 = true;
var sticks = 21; // private (= inaccessible from outside (no cheating))
this.remove = function (x) { /* … */ ) }; // mutator for sticks
this.sticks = function () { /* … */ ) }; // accessor for sticks
}

Game.prototype.choose = function () { /* … */ ) }; // getChosenNumber()

Game.prototype.toggle = function () { /* … */ ) }; // switchCurrentPlayer()

Game.prototype.win = function () { /* … */ ) };

sparhavk
06-29-2010, 07:15 AM
Don't ask me I'm just trying to get it sorted, but it took almost 3 hours and i have only managed to add some pieces and they even work's

Dormilich
06-29-2010, 07:20 AM
I guess you need a main function, that controls the other functions.

sparhavk
06-29-2010, 07:26 AM
as a main program i have got something like
getChosenNumber();
removeSticks(numberChosen);
if (numberOfSticks = 0)
{
document.write ('Player ' + currentPlayer + ' wins')
}
else
{
document.write ('Number of sticks left ' + numberOfSticks)
getChosenNumber;
}

but unfortunatly I'm ending up with Number of sticks 0

:/

Dormilich
06-29-2010, 07:30 AM
you mustn’t use document.write(). that will wipe your page. rather set the value of a text field.

some general idea for the main function (this might be implemented recursively or in a loop)

if/while (sticks available) {
choose sticks
test for winning
}
you lost

sparhavk
06-29-2010, 08:03 AM
the problem is that i have to use it :(
"After each go the program outputs the number of matches that still remain and if this number is zero a message is displayed to say the current player is the winner."

It's almost working but the loop doesn't work any ideas??

getChosenNumber()
if (numberOfSticks != 0)
{
removeSticks(numberChosen);
document.write ('Number of sticks left ' + numberOfSticks + '<BR>')
switchCurrentPlayer()
}
else
{
document.write ('The winner is Player '+currentPlayer )
}

Beagle
06-29-2010, 08:07 AM
Right, my mistake, DOM level 1 doesn't change how event handling works. Thanks for the clarification.

You're using global variables. We're not going to get into trying to teach OOP right now when you need to get your basic programming completed in a way that makes sense to you, and it seems that procedural + global variables is a way that makes sense to you.

So, plan your program on paper. How does it work?

1) What is your initial state?
2) What is the first input that occurs?
3) What happens after that first input?

There are hundreds of ways to do what you want to do. But they all start with understanding what you're actually going to do from a logical standpoint.

Sounds to me like you've got a classic game loop.



while (winConditionNotMet) {
display Info
take input
process input
display result
}


That's pseudo-code. Display info can be alert() whatever message you want.

The win condition is numberOfMatches <= 0, so winConditionNotMet should be numberOfMatches > 0

And then get user input is call that function.

A process user input is simply a subtraction: numberofSticks = numberOfSticks - chosenNumberOfSticks;

Take a crack and paste your code and we'll review.

sparhavk
06-29-2010, 08:24 AM
Ok thats what ive come to :/ o know it's crap :( but thats how they teach us to do ... it does most of the things i want but loop doesnt work :(

<HTML>
<HEAD>
<TITLE>
The game of 21
</TITLE>

<SCRIPT LANGUAGE = "JavaScript">

//FUNCTIONS
/*
*removes a given number of sticks
*
*function takes one argument numberToRemove that represents the number of sticks to be removed
* if numberToRemove is more than numberOfSticks, reduces numberOfSticks to 0
* otherwise reduces numberOfSticks by numberToRemove
*function returns no value
*/
function removeSticks(numberToRemove)
{
if (numberOfSticks< numberToRemove)
{
numberOfSticks = 0
}
else
{
(numberOfSticks = numberOfSticks - numberToRemove);
}

}

/*
*switches current player
*
*function takes no argument
* if current player is 1, sets current player to 2
* otherwise sets current player to 1
*function returns no value
*/

function switchCurrentPlayer()
{
if (currentPlayer ==1)
{
return currentPlayer = 2;
}
{
return currentPlayer = 1;
}
}

/*
*gets a number from a prompt dialogue
*
*function takes no argument
* prompts the current player for a number of sticks to remove, with a suitable message
*function returns the number the player enters
*/

function getChosenNumber()
{
numberChosen = window.prompt('Player ' + currentPlayer + ': Please enter either 1, 2 OR 3.');
return numberChosen;
}



//VARIABLES -- do not change this section
var numberOfSticks = 21;//number of matchsticks, initially 21
var currentPlayer = 1;//player whose turn it is, Player 1 goes first
var numberChosen;//variable used to hold the number the current player chooses

//MAIN PROGRAM
//Part (iii)(b)
//Complete the main program following the description given in the question and the structured
//English you have written in (iii)(a).
if (numberOfSticks == 0)
{
document.write ('The winner is Player '+currentPlayer )
}
else
{
getChosenNumber()
removeSticks(numberChosen)
document.write ('Number of sticks left ' + numberOfSticks + '<BR>')
switchCurrentPlayer();
}


</SCRIPT>

</HEAD>
<BODY>
</BODY>
</HTML>

Beagle
06-29-2010, 08:26 AM
You don't have a loop. You need a while loop. And don't use document.write. Use alert(). Even if you eventually change it back. Don't use document.write for now, it will trip you up while you're trying to solve this problem.

while (condition) {
do stuff
}

follow my pseudo-code in my previous post.

sparhavk
06-29-2010, 08:32 AM
ok changed it into

while ( numberOfSticks== 0)
{
getChosenNumber()
removeSticks(numberChosen)
alert ('Number of sticks left ' + numberOfSticks + '<BR>')
switchCurrentPlayer();
}
else
{
alert ('The winner is Player '+currentPlayer )
}

but now program doesn't display prompt window :(

Beagle
06-29-2010, 08:35 AM
Right, that's not the correct syntax for a while loop. There's no "else" block in a while loop.

Also, a while loop only works if the condition is met. Since you start with numbeOfSticks at some number other than 0, the while loop never starts.

Try numberOfSticks > 0.

Also, use the return value of getChosenNumberOfSticks. Don't just call it, use the return value in your loop.

To display success, just put your win code after the loop. The loop ends when the win condition is met.

sparhavk
06-29-2010, 08:37 AM
Beagle you are great It works, I owe you few beer's :)

Beagle
06-29-2010, 08:42 AM
Glad to be of service. Good luck on your journey and if you're ever in NYC, PM me.

sparhavk
06-29-2010, 09:43 AM
how to ?? modify this line to
Modify the function getChosenNumber()so that whenever a player enters anything at all different from the three permitted choices an alert is displayed reminding them of the rules, and they are prompted again for input. If they repeatedly enter an incorrect value they should go on being reprompted until they have made a legal choice.


function getChosenNumber()
{
numberChosen = window.prompt('Player ' + currentPlayer + ': Please enter either 1, 2 OR 3.');
}
return numberChosen

}

Philip M
06-29-2010, 10:50 AM
for (var i=1; i<2; i++) {
var ans = parseInt(prompt ("Player " + currentPlayer + " Enter a number, either 1,2 or 3", ""));
if ((isNaN(ans)) || (ans == "") || (ans <1) || (ans >3)) {
alert ("You must enter a number in range 1-3!! ");
i -- ;
}
}

Hyp3r
07-10-2010, 08:42 PM
Hi all. Sorry to bump the thread but I did not want to make another thread when there is already a thread relating to some of my issues.

here is my code below, for some reason the program is stepping through the code but is not running correctly.

Is there something obvious I am missing?

Thanks


<HTML>
<HEAD>
<TITLE>
The game of 21
</TITLE>

<SCRIPT LANGUAGE = "JavaScript">

//FUNCTIONS
/*
*removes a given number of sticks
*
*function takes one argument numberToRemove that represents the number of sticks to be removed
* if numberToRemove is more than numberOfSticks, reduces numberOfSticks to 0
* otherwise reduces numberOfSticks by numberToRemove
*function returns no value
*/
function removeSticks(numberToRemove)
{
if (numberOfSticks< numberToRemove)
{
numberOfSticks = 0
}
else
{
(numberOfSticks = numberOfSticks - numberToRemove);
}

}

/*
*switches current player
*
*function takes no argument
* if current player is 1, sets current player to 2
* otherwise sets current player to 1
*function returns no value
*/

function switchCurrentPlayer()
{
if (currentPlayer ==1)
{
return currentPlayer = 2;
}
{
return currentPlayer = 1;
}
}

/*
*gets a number from a prompt dialogue
*
*function takes no argument
* prompts the current player for a number of sticks to remove, with a suitable message
*function returns the number the player enters
*/
function getChosenNumber()
{
for (var i=1; i<2; i++)
{
var ans = parseInt(prompt ("Player " + currentPlayer + " Enter a number, either 1,2 or 3", ""));
if ((isNaN(ans)) || (ans == "") || (ans <1) || (ans >3))
{
alert ("You must enter a number in range 1-3!! ");
i -- ;
}
}
}
//VARIABLES -- do not change this section
var numberOfSticks = 21;//number of matchsticks, initially 21
var currentPlayer = 1;//player whose turn it is, Player 1 goes first
var numberChosen;//variable used to hold the number the current player chooses

//MAIN PROGRAM
//Part (iii)(b)
//Complete the main program following the description given in the question and the structured
//English you have written in (iii)(a).

if (numberOfSticks > 0)
{
{
alert ('The winner is Player '+currentPlayer )
}

{
getChosenNumber()
removeSticks(numberChosen)
alert ('Number of sticks left ' + numberOfSticks + '<BR>')
switchCurrentPlayer();
}
}
</SCRIPT>

</HEAD>
<BODY>
</BODY>
</HTML>

Philip M
07-11-2010, 08:26 AM
Move your variable declarations to the top of the script.
Because you have copied blindly from Post #19 you are using a variable named "ans" instead of "numberChosen".
There are quite a few other problems. This has (I think) put them right. Study and learn from it - if you just copy blindly you will learn nothing.




<HTML>
<HEAD>
<TITLE>
The game of 21
</TITLE>

<script type = "text/javascript">

var numberOfSticks = 21; //number of matchsticks, initially 21
var currentPlayer = 1; //player whose turn it is, Player 1 goes first
var ans; //variable used to hold the number the current player chooses

function removeSticks(numberToRemove) {
if (numberOfSticks< numberToRemove) {
numberOfSticks = 0;
}
else {
numberOfSticks = numberOfSticks - numberToRemove;
}
}

function switchCurrentPlayer() {
if (currentPlayer ==1) {
return currentPlayer = 2;
}
else {
return currentPlayer = 1;
}
}

function getChosenNumber() {
for (var i=1; i<2; i++) {
var ans = parseInt(prompt ("Player " + currentPlayer + " Enter a number, either 1,2 or 3", ""));
if ((isNaN(ans)) || (ans == "") || (ans <1) || (ans >3)) {
alert ("You must enter a number in range 1-3!! ");
i -- ;
}
}

removeSticks(ans);
alert ('Number of sticks left ' + numberOfSticks );
if (numberOfSticks == 0) {
switchCurrentPlayer(); // the other player is the winner if the one to take the last match loses!
alert ('The winner is Player '+currentPlayer );
return false; // end game
}

switchCurrentPlayer();
getChosenNumber();
}

getChosenNumber(); // start game
</script>

</HEAD>
<BODY>
</BODY>
</HTML>

<script language=javascript> is long deprecated and obsolete. Use <script type = "text/javascript"> instead.

For reasons to do with automatic semi-colon insertion which are too advanced for you to understand at this stage, you should place an opening brace { on the same line of code and not on a separate (the next) line. Disregard books/teachers that tell you otherwise. And always end a statement with a semi-colon. Although semi-colons are normally optional (and added automatically) it is good practice to include them explicitly.

I heard him then, for I had just
Completed my design
To keep the Menai Bridge from rust
By boiling it in wine.
- Lewis Carroll

Hyp3r
07-11-2010, 09:16 PM
I agree with you, out of interest how many years coding experience do you have?

Is it worth buying any coding related books per subject of current choice/interest.

To me it seems things get outdated too quickly.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum