Creating a browser RPG in javascript

10-16-08, 12:53 AM
|
|
Newbie Coder
|
|
Join Date: Apr 2008
Posts: 58
Thanks: 0
Thanked 0 Times in 0 Posts
|
|
By that I mean the title: Is it possible to create an RPG with mostly arrays?
|

10-16-08, 07:20 PM
|
|
Community VIP
|
|
Join Date: Sep 2003
Location: 404
Posts: 1,813
Thanks: 0
Thanked 0 Times in 0 Posts
|
|
I feel that's like asking if I can paint a rainbow with mostly blue. Arrays are just a small part of the language, you'll probably have to use them in some places but there are a lot of things you can't use them for, or where they are simply not needed.
Arrays act like variables which can hold more than one value. On their own they'll just sit there. To make something useful you need more code with algorithms actually accessing the arrays to get or set the data in them.
Why this focus on arrays?
|

10-17-08, 06:06 PM
|
|
Newbie Coder
|
|
Join Date: Apr 2008
Posts: 58
Thanks: 0
Thanked 0 Times in 0 Posts
|
|
I'm wondering if I can store all the 'data' (monsters, weapons, and such) completely within different arrays. Accesing the data is a different matter altogether, obviously.
Also, I'm wondering if this will all run smoothly or is there a generally 'more recommended style' for going about data without creating different files, such as xml, etc?
|

10-17-08, 07:05 PM
|
|
Community VIP
|
|
Join Date: Sep 2003
Location: 404
Posts: 1,813
Thanks: 0
Thanked 0 Times in 0 Posts
|
|
Ah now it makes more sense. Yes you could of course use arrays to store your data, no matter how complex it is, as long as you manage to keep track of it hehe.
You could also nest arrays (aka multidimensional arrays) to create a hierarchical structure of say all the items in your game with sub-arrays for all weapons, armor, food, gems, whatever.
However, dealing with just normal arrays, where data is indexed by integers can be a bit confusing. There is however a way to associate words, or even complete strings, with the data instead. This is possible because in JavaScript every Object (or object based on the base type Object, such as an Array) can be extended with new properties at runtime. Adding a new property to an Object is easy, simply assign a value to it, just like you do with Arrays and their indices:
JavaScript Code:
var anObject = new Object(); // anObject is now an empty JavaScript object alert(anObject); // Shows '[object Object]', indicating that anObject is an object of type Object. anObject.aProperty = 5; // anObject now has the property 'aProperty' with the value 5 alert(anObject.aProperty); // Shows 5 // properties of objects can also always be accessed using the same syntax used for Arrays, but if the key is a string instead of a number you'll need to use quotes. alert(anObject['aProperty']); // Shows 5 anObject.aSubObject = new Object(); // anObject now has a property which itself is an Object. alert(anObject.aSubObject); // Shows [object Object] as aSubObject is an object of type Object. // Add a anObject.aSubObject.anotherProperty = "It's a sub-object property!"; alert(anObject.aSubObject.anotherProperty); // Shows "It's a sub-object property!" // You can of course also create properties of the Array type. Arrays are really just Objects with a couple of extra nifty things like the dynamic .length property anObject.aSubArray = new Array(1, 2, 3); alert(anObject.aSubArray) // Shows "1, 2, 3" as Arrays have a property called .toString which is actually a function automatically called when printing out the value of an Object. // Now let's do two things at once: Add a function as a property (called a Method) and use the fact that a method named .toString is automatically called [if present] when a text-representation of an Object is needed. anObject.toString = function (){ return 'This is my Object! It now has many properties and sub-objects. One has the value '+this.aProperty; } alert(anObject); // Now shows "This is my Object! It now has many properties and sub-objects. One has the value 5" // There's also a short syntax for creating Objects, as with Arrays. This is known as the literal syntax, it has many advantages (one being smaller code) and only few disadvantages (variables can't be used to dynamically set which property name should be used. var anotherObject = {}; // Creates an empty object // We can set a bunch of properties at the same time as creating the Object, just like with Arrays. Note the : used instead of = while inside a literal Object/Array delcaration. Also note that quotes are not needed for the key when using literal declaration, this is why using variables as the key here won't work. var aThirdObject = { aProperty : 145, anotherProperty : 154, 'a property with a space must have quotes' : 876543, "a nested Array property" : ['a', 'b', 'c'], // Double quotes work fine too, as does using Array literal notation as data subObject : { 1 : 'A', 2 : 'B', 4 : 'C' }, AnotherProperty : 'some string value here' }
Those are just a few examples of how object hierarchies can be formed to suit your needs of structure in data storage.
Oh one more thing. Arrays can also hold data with string keys/properties instead of numerical indices, as an Array is an Object too. But properties and methods are not counted by the .length property. You would also need to use a for...in loop to find out which properties exist on an unknown Object/Arrray.
You can also make your own Object types using what's known as a constructor function, but I recommend you search for more info about that on the web. There's so much more to tell about all this, but it would just be a waste of time for me to repeat everything someone else has already said, proof-read and tested more thoroughly.
Edit: Forgot to mention performance and files. JavaScript has no native file support (allowing a web-page to access files on your local hard drive is not very popular), so using an xml file is usually not a good idea. The performance while reading the data from a file would be a lot less than when reading from memory once the script itself has been parsed. There's not really a point to using a file until you need to say save the progress of your character. Only Internet Explorer has a way to read/write files using JavaScript tho. It uses ActiveX controls, which are a part of one of Microsoft's frameworks, so it'll trigger a big warning (if even enabled) each time a file is accessed. Other browsers will simply not recognize the functions used to do that and throw an error.
This is the downside to JS, storing persistent data has to be done somewhere else, like on a server. But since anyone could just modify your script and send incorrect data to the server you'd get a lot of cheaters quickly. JavaScript is not designed to handle secure stuff as it has to expose everything it does to be as powerful as it needs to.
Last edited by TwoD; 10-17-08 at 07:13 PM.
|

10-19-08, 07:24 PM
|
|
Newbie Coder
|
|
Join Date: Apr 2008
Posts: 58
Thanks: 0
Thanked 0 Times in 0 Posts
|
|
Something I self wrote, testing the idea of storing info in arrays (but not the statements).
How would I get this to work correctly?
|

10-20-08, 12:23 AM
|
|
Newbie Coder
|
|
Join Date: Apr 2008
Posts: 58
Thanks: 0
Thanked 0 Times in 0 Posts
|
|
Here's the updated code:
JavaScript Code:
<html> <head> <script language="javascript"> function v() { npcaction=new Array() { []lunges []leaps []charges []barrels []ambles } npcweapon=new Array() { []hand and half sword []long sword []short sword []hand axe []battle axe []pike []long spear []great sword []great axe } monstervar=new Array() { []orc []hobgoblin []green goblin []blue goblin []black orc } var mvar = monstervar[Math.floor(Math.random*monstervar.length)] var npca = npcaction[Math.floor(Math.random*npcaction.length)] var npcw = npcweapon[Math.floor(Math.random*npcweapon.length)] var myDivElement = document.getElementById('myDiv); var myDivElement0 = document.getElementById('myDiv'); var myDivElement1 = document.getElementById('myDiv'); myDivElement.innerHTML="<b>"+monstervar+"</b>" myDivElement0.innerHTML="<b>"+npcaction+"</b>" myDivElement1.innerHTML="<b>"+npcweapon+"</b>" } function x() { document.innerHTML="<b>You encounter " + monstervar + "which " + npcaction + "at you with " + npcweapon + "!</b>"); } </script> </head> <body> <form><input type="button" onClick="x()" value="Encounter"></form> <div=mydiv> </div> </body>
And it still doesn't work.
Last edited by TwoD; 10-20-08 at 02:58 PM.
|

10-20-08, 03:27 PM
|
|
Community VIP
|
|
Join Date: Sep 2003
Location: 404
Posts: 1,813
Thanks: 0
Thanked 0 Times in 0 Posts
|
|
Your array syntax is way off. You need to pay a bit more attention to the examples given in the thread, as well as look it up in reference manuals/tutorials. Like on MSDN or W3Schools. Are you using an editor with syntax highlighting for HTML/JavaScript?
I changed the code block in your post to an highlight=JavaScript block. As you can see, the first portions of it are black, as the highlighter can't understand the syntax. Nor will the JavaScript interpreter.
I'm not sure what you're trying to do in the v function (longer function names would possibly make it a bit clearer). I'm guessing you're trying to generate a randomized monster attack, and then show it on screen when the button is clicked.
There are a few problems here - Array/string syntax needs a major change. See code below.
- The call to Math.random() is missing parenthesis.
- Using Math.floor() together with the .length property to generate a random index is not reliable. If Math.random() is exactly 1 (which is extremely rare in this case because of Math.floor()) the index will be one more than the highest index used. Math.floor() also gives a greater chance to get lower values. Replace with Math.round(Math.random()*(array.length-1)) to get a better distribution of indices, while staying inside the bounds.
- The variables you write the randomly chosen strings to are declared with var, making them local to the function v(). Once v() stops, those variables are destroyed. Let's move their declarations to the global scope to allow for x() to use them later.
- You get three references to the same div (myDiv) and then write three different strings to it. Only the last one will show as all references point to the same element, and all writes replace the previous ones because you used = instead of +=. You can either use three divs, or just use one reference to write all strings to the same div but append instead of replace.
- You are writing the entire arrays to the div element, not just the randomly selected strings.
- When x() runs it will assign a string to document.innerHTML which does not exist. Thus it will be created, but never have any effect on anything. There is an property named document.body.innerHTML, but if you write to that, you will replace everything inside the <body> tag unless you use += instead of =.
- Here you also print out the entire contents of the arrays, instead of the randomly selected values.
- The function v() is never called, meaning that the mvar, npca and npcw variables will be empty, and the array variables will never exist.
Here I've made the changes mentioned above:
JavaScript Code:
var mvar, npca, npcw; // Globally declared so both functions can use it // Make these global too just in case some other function needs them as well var npcaction = [ "lunges", "leaps", "charges", "barrels", "ambles"]; var npcweapon=[ "hand and half sword", "long sword", "short sword", "hand axe", "battle axe", "pike", "long spear", "great sword", "great axe"]; var monstervar=[ "orc", "hobgoblin", "green goblin", "blue goblin", "black orc"]; function createEncounter() { mvar = monstervar[Math.round(Math.random()*(monstervar.length-1))] npca = npcaction[Math.round(Math.random()*(npcaction.length-1))] npcw = npcweapon[Math.round(Math.random()*(npcweapon.length-1))] } function showEncounter() { createEncounter(); var myDivElement = document.getElementById('myDiv); myDivElement.innerHTML = "<b>You encounter " + mvar + "which " + npca + "at you with " + npcw + "!</b>"); }
|
|
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
|
|
|
| Thread Tools |
|
|
| Display Modes |
Linear Mode
|
Posting Rules
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
HTML code is Off
|
|
|
|