Reputation: 11221
It is possible to read line by line txt file from my HTML5 game resources? (Resources = one of folders in my game project) I keep in this file informations about levels in my game. I found only examples using PHP, Ajax, but all of this requires server, but I want to run my game on servers or offline mode. Thanks in advance.
Upvotes: 1
Views: 276
Reputation: 86260
One technique used often by templates and preprocessing languages (like LESS or CoffeeScript) is to use a script tag with a type
attribute not recognized by browsers. This causes it to be ignored by the browser and search engines, but be accessible by JavaScript.
<script type="text/mygamelevel" id="level1">
0010011001111011
0011011100010
10101110111101101
</script>
<script type="text/javascript">
var level = document.getElementById("level1").text;
var lines = level.split("\n");
for (var i=0; i<lines.length; i++) {
var line = lines[i];
if (!line.trim()) continue;
alert(line);
}
</script>
If a file is preferred, you can dynamically request it. This is an example using jQuery's get function.
$.get('levels/level1.txt', function(level) {
var lines = level.split("\n");
for (var i=0; i<lines.length; i++) {
var line = lines[i];
if (!line.trim()) continue;
alert(line);
}
});
No guarantee is made that the code in the callback will be executed at any given time, so I suggest putting some start-new-level code in there, as opposed to anywhere else in the code. Otherwise, you don't know if you have the level information downloaded yet or not. This problem is averted by inlining the data as shown in the first snippet of this answer.
Upvotes: 2
Reputation: 11728
Browser's JavaScript do not, and should not, have direct access to local file system.
Upvotes: 1