Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Thursday, 8 November 2012

A Simple Html Input For Text Adventures

A while back I was messing around attempting to get a simple HTML interface for a text adventure. You know the ones where you type in you input. These games have not really been in favour for quite some time and given they require text input nor are they going to be reinvented for mobile devices like pick your own adventures have been.

Still I find them fun to play from time to time. Perhaps one days I will get round to actually writing more than a toy one. In this entry I am just going to present a simple html interface for such game.

I initially attempted to use iscroll to provide some nice scrolling but hit problems when moving the input bar into the scroll area I just could not get it accept input so eventually I have settled on JScrollPane. As I am using JQuery anyway it was not really much of an issue to install this plug in.

The basic idea is to have an HTML unordered list to represent the game. The last list item is the input area. As the player enters commands the response can be displayed as a list element that we insert. We automatically scroll to the bottom after each response.

Lets start with the html code

<html>
  <head>
    <link rel="stylesheet" href="jquery.jscrollpane.css" type="text/css" media="screen" />
    <link rel="stylesheet" href="style.css" type="text/css" media="screen" />
    <script type="text/javascript" src="jquery-1.8.2.min.js"></script>
    <script type="text/javascript" src="jquery.mousewheel.js"></script>
    <script type="text/javascript" src="jquery.jscrollpane.min.js"></script>
    <script type="text/javascript" src="main.js"></script>
  </head>
  <body>
    <div id="container">
        <ul id="text-items">
          <li id='end-buffer' > <input type="text" id="text-input" name="" value="" /></li>
        </ul>
    </div>
  </body>
</html>

As you can see the html is pretty simple. We just create the container and the unordered list.

Our css file as also pretty simple as I comment on  this later.
#container{
    width:640px;
    margin-left: auto;
    margin-right: auto;
    height:400px;
}

#text-input {
    width:100%;
}

#container li{
   list-style-type:none;
}

Yep, we pretty much just centre up my elements and turn bullet points off for my list elements.

The JavaScript makes use of JQuery and of course JScrollPane a JQuery plug in.
function start(){
  var ti = $('#text-input');
  $('#container').jScrollPane();
  var scrollApi = $('#container').data('jsp');

  ti.on("keyup", function(evt) {
   if(evt.keyCode === 10 || evt.keyCode === 13){
     var li = $("<li/>").text(ti.val());
     $("#end-buffer").before(li);
      
      scrollApi.reinitialise();
      scrollApi.scrollToBottom();
     ti.val("");
   }
  });
};
We attach a callback to out input element to monitor when return is pressed. Create an element that just echoes back your input and then scroll down to the bottom so you can still see the input line. Of course in a real game you would have to do something other than just echo back the result...

You will notice I have not done any styling. The colours are pretty uninspiring and the overall it does not feel polished. A lot of this polish is partially determined by the type of game and partially by your own preferences how you think it should work.

A couple of obvious things is an input history so you can cursor though old commands and probably putting a limit on the maximum number of list items in the output display. Just remove the oldest one when adding a new one and there are more then say 100 list items.

The other thing I am not so keen on it having the text entry at the top when you first start. This may not be much of an issue if you have a back story to push the input down. I was also tempted to blat in a lot of empty list items to force it down the screen.

I could go on about the limitations but this is really on meant to be an example to show how simple it can be to get started.

Comments are welcome.

Tuesday, 6 November 2012

HTML5 Growing A Canvas To Fill The Window

A little while back I played a HTML5 game that included a button just below it to grow the canvas used for the game to fill the window the game is being played in. It is a pretty nice feature. I thought this is probably pretty easy to in something similar using JQuery.

Turns out it is, although I have not clone the features exactly.

First up we need a little html document.
<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="jquery-1.8.2.min.js"></script>
    <script type="text/javascript" src="main.js"></script>
    <link rel="stylesheet" href="style.css" type="text/css" media="screen" />
  </head>
<body>
  <div class='center-me'>
    <canvas id='my-canvas'></canvas>
  </div>
  <div id='toolbar' class="center-me">
    <button id='click-me'>Grow</button>    
  </div>

</body>
</html>

As you can see it is pretty basic. The layout is a centred canvas with a toolbar containing one button below it. When you click the button the canvas will grow to fill the window but still leave the toolbar visible. Click the button again and the canvas will shrink to its original size. In terms of css here is what we have in our style.css file.
body {
    width:100%;
    overflow:hidden;
    margin:0;
}

.center-me{    
    text-align:center;
}

#my-canvas{
    width:300px;
    height:300px;
    border-width:1px;
    border-style:solid;
}

#click-me {
    margin-bottom:10px;
}
Apart from the centreing bits we have added a little bit of a margin to the button otherwise it seemed to get a little bit cut off when we expand. I am not sure why this is so if anyone has any ideas?

We also turn off scrollbar as the dynamic appearance (when needed) in both chrome and FireFox complicates things some what. An alternative is to always have them visible using overflow-y: scroll; in the css for the html element. That way you could push the tool bar off the screen to gain some vertical space in return for loosing some horizontal space. Depending on your trade-offs one me be preferable to the other.

Finally we are onto the javascript. Here is my main.js file
var start_up = function(){
  var ctx = $('#my-canvas')[0].getContext('2d');

  // draw some random stuff.
  ctx.fillRect(50,50,50,50);
  ctx.fillStyle='#cc3333';
  ctx.fillRect(50,10,80,30);

  var fullWindow = false;

  $('#click-me').on('click', function(){
    var width;
    var height;

    if(fullWindow){
      height= 300;
      width = 300;
    }else{
      width = $(window).width();
      height= $(window).height()-$('#toolbar').outerHeight(true);
    }
    fullWindow = !fullWindow; // toggle the flag.

    $('#my-canvas').animate({
      width:width,
      height:height
    }, 2000);

    $('#click-me').text( fullWindow ? 'Shrink' : 'Grow');
  });
};

$(start_up);
So I dip into my canvas element and draw a few rects. After that we hook up the on click callback for the grow/shrink button such that we animate the size of the canvas. Note the use of outerHeight along with the true flag to get the full height including the margin.

An important thing to note is we are changing the width and height that the canvas is drawn at not the internal dimensions. If you try out my example code you will see the image stretched. This may or may not be what you wanted.

If you are happy to stretch you image it is probable you will want to keep the aspect ratio rather than growing to fill as much space as possible. However if you are taking the approach of want to draw as much of a map as possible then you will probably want to set the width and height of the canvas object once the animation stops.

Perhaps sounds a bit odd if you have not encountered this before but it does make quite a bit of sense when thought on for a while.

Anyway that just about wraps it up.

Saturday, 20 October 2012

Simple Convex Hull Generation in JavaScript.

I stumbled across this page and decided it would be fun to convert it to run in JavaScript.

Ok it is not the best method for finding the convex hull but given it is really simple idea that results in a small amount of code it can be quite useful.

The basic idea is you find the left most point from the collection of points. If two are equal you take the lowest y value.

Set this to be the end point of the lines that form the convex hull

Then we loop round all the points attempting to find a line segment from the end point to another point that has all the other points to the left of it. This forms the next point of the convex hull and we add it to our convex hull collection as well as setting it as the end point.

Just keep going until the end point that we find is the equal to the first point in our convex hull collection.

Code is often clearer than a written description of it so here's the code.
// Gift wrap method
function convex_hull(pnts){
    var out = [];

    var startIdx = findLeftMostLowestPoint(pnts); 
    var hull = startIdx;
  
    var npts = pnts.length;
    var endpt = 0; 
    do 
    { 
	out.push(pnts[hull]); 
	endpt = 0; 
	for (var j = 1; j < npts; ++j) 
	{
	    if (hull == endpt || isToLeft(pnts[hull], pnts[endpt], pnts[j]))
		endpt = j; 
	}
	hull = endpt; 
    } while (endpt != startIdx); 
    
    out.push(pnts[endpt]); // close the poly
    return out;
}

and here are the helper functions you need.
function findLeftMostLowestPoint(pnts){
  var idx = 0;
  var npts = pnts.length;
  for (var i = 1; i < npts; ++i) 
  {
    var a = pnts[i];
    var b = pnts[idx];
    if(a.x < b.x || (a.x == b.x && a.y < b.y))
      idx = i;
  }
  return idx;
}

function isToLeft(a, b, c){  
    var u1 = b.x - a.x; 
    var v1 = b.y - a.y; 
    var u2 = c.x - a.x; 
    var v2 = c.y - a.y; 
    return u1 * v2 - v1 * u2 < 0; 
} 
That is all you really need.

Friday, 19 October 2012

YaSnippets, JavaScript and Emacs 24



If you are trying to get yasnippets and JavaScript working together in Emacs 24 you might like to know that the JavaScript mode is called js-mode. This means when you download the JavaScript snippets the directory that contains them needs to be called js-mode rather than javascript-mode.

Yes this caught me out for a while :)

Tuesday, 4 January 2011

A Tiny Pick Your Own Adventure Engine.

Last night I finished off writing the outline for the little choose your own adventure I am working on. I then ran it through the python script for parsing the mark up language I use and generated a JavaScript data file to run in the engine I am going to create.

A while ago I started work on this engine but only got as far as create the storage for the state required to play the game. Obviously the engine does absolutely nothing to do with the displaying of the game, it is just for handling the actual game. Tonight I finished it off. Before I started it I was expecting it to be small but the total lines of code came in at 106 lines and a few of them were utility functions that may exist in JavaScript but I am unaware of them.

That is about half to a quarter the size of the code I was expecting. It is very sub optimal code in the sense there is lots of look ups where I could cache things. Given text based games are not exactly performance driven I am attempting to write concise clear code and avoiding anything that can interfere with that like the extra state that comes with caching things. If I want something I look it up. This sort of programming really goes against all the programming mind set I have developed over the years it does make the code look very nice and it is good to try out different things.

While I have not tested this code anywhere near enough yet, it is nice to see JavaScript producing a very clear and concise piece of code.

I plan to work on actually getting a game working, that is making the UI next before fleshing out the text.

Monday, 29 November 2010

A Little Text Adventure.

Edit: Oops appears it is not working in firefox, will have to figure that out.

At last another bit of content on marblemice.com. Yes it is retro, it is a clone of a text adventure from 1984. I decide to knock this up after attempting to make a command line interface in a web page. You can now relive the thrill of playing a text adventure on the web that you once had to type in on a probably coffee stained keyboard. Here is a direct link

Ok, in terms of game play it is not great and falls into to the simple to play text adventure catagory. If you get stuck just do Ctrl-U to look at the source I have not minified it. Browsing the text should tell you all you need to know to solve the game.

I actually quite enjoyed creating the game. I learned a bit more about HTML/CSS/JQuery, threw around five hundred odd lines of code and ended with a ok looking code for my experience level with JavaScript. As there were no graphics in the game all that was required was a bit of imagination (I slightly adapted the original design) and coding skills.

Coding wise I was learning towards a data driven design but for some many specific commands such as give and shoot and well everything to do with the one NPC was coded in place. It was just not worth going the extra mile when there is only one NPC and I seriously doubt I will code up another text adventure.

Having said that I am pondering a "Choose you own adventure", a format that is more suited to the web where devices may not have a keyboard. It would be a nice progression up from a text adventure and this time the adventure would be an original if probably a little derivative in terms of story. Perhaps I will hack together a prototype at some point.

Over the past couple of weeks I have gradually comming to the conclusion that for turn based story driven games  HTML/CSS/JQuery actually provides quite a nice environment to develop them. That is assuming I target Firefox and Chrome. I have no idea how well IE handles the stuff I am making.

Wednesday, 3 November 2010

Early Nov 2010 update


I appear to have two strands going on at the moment in programming. Both are web based and involve JavaScript. Ok I also went on a 4 day Stag do plus travel time so the past couple of weeks have not be the most productive in terms of get code produced.

The first little project is a little game (Hamla) using JavaScript and HTML5 canvas. In all honesty the game is more about developing some technology to write other games in. The game is actually finished in terms of game play and features but I want to add at least a little bit of polish to it. So I have started to write a little SVG loader/render to allow then them to be drawn on the canvas. I am not planning on implementing the full SVG spec just the bits I need to load some sprites.

Given my lack of experience in JavaScript it feels like it is actually going quite well. At some point I will publish it a website somewhere.

My synth app may look like it has ground to a halt but that is not the truth. So far I have just been adding features without much concent for code quality and that is gradually going to have to change. Part of this work was getting a very simple graph library put together so I can handle gradually work toward users being able to add nodes and links. 

As this was an independant bit of code I have designed it as such. It means the minimal requirements for what I need and is a simple as it can possibly be. The means it is hugely ineffiecient but is back up by a reasonable number of unit tests so should performance ever become an issue I can fix that. Of course if the profiler never highlight this module as being a problem I won't have wasted time. I expect the graphs to be pretty small so simple, bug free, code is currently prefered.

Sunday, 17 October 2010

Iteration 22, setting the frequency of the tone.

Seems like a productive weekend here. I got another evening of coding in. Tonight I sorted out the rendering of nodes so they update with the change of wave form.

I also added the ability to change the frequency of the tone generated. that does lead to the question should I also display the frequency in the glyph. The name of the wave form is in some way redundant as the shape of the wave form tells you that information. It would be better to display the frequency as that is important information.

After that I am not sure what is on the list next. Part of me want to flesh out the Wave Form generator with more forms, like a pulse, triangle and so on but on the other hand that feels like I am heading deep into one type of node when I should be working towards allowing others. I also have not yet added a proper event system and without one of them having an undo command is going to be quite a bit of work, adding one in not trivial once the code base grows.

Saturday, 16 October 2010

Iteration 19 adding some different wave forms

Instead of trying to think of catchy titles I have just decided to put the iteration number and the thing I have added this iteration. Iterations are small so not much will be added each iteration.

So the main feature for this iteration is you can now set the wave form of the signal generated. To do this click on the Wave form icon and use the drop down menu that appears to change the wave form from to either a saw tooth or a square wave.

I don't yet update the icon to reflect the changes. A task for another night and as the is just a play thing at the moment I don't mind publishing it when this is going on.

I also fixed a bug where pages did no load the first time. It was a school boy python typing mistake and strangely I did not notice until a few days ago.

I am also not going to link to the app in each blog entry instead I plan to add it to the side bar, just over there I think :)

Saturday, 9 October 2010

Synth stuff, iteration 17 published

Yes I have been silent for a while. It seems for the past two weeks I have been pretty busy and not had that much time for coding.

In the small amount of time I have had I have tried to put it to good use. So what have I been up to.

Well first of all I have rewritten the app to use javascript rather than GWT. I am use JQuery to make my life a little bit better. The reasons for this are not at all technical and may seem a little bit of an odd way to make these sorts of decisions, I will eventually get round to writing about them in a blog entry. I spent about 3 evening recoding the synth app to javascript.

That was pretty quick but then but not a vindication of JavaScript being a more productive language more just I knew what I was doing this time! I also dropped Java on the server side and moved to python. Well if you are going to go for dynamic languages you may as well go the whole hog. This took a couple of hours to get set up nothing more as all I am doing is serving some static pages.

I should now be able to start to iterate again at a reasonable pace even if I am well behind where I hoped to be in October. The latest iteration is functionally equivalent to what was published previously - I hope.

Wednesday, 15 September 2010

JavaScript and so on.

I took a few days off from coding. I managed to run a half marathon and took the children up a welsh mountain on the same day. Ok partially up a small one and I have been suffering ever since, I then spent some time chilling and building up my energy for the next couple of weeks of iterations of the synth app.

For once this entry is not about the gradually growing synth app. It is about clojure and javascript.

A bit of background to give you some context for my thoughts. A couple of weeks ago I decided to focus on making a web based synth app. To do this I decided to dive into GWT and the google app-engine.

As I am thinking on this as a little start up experiment that I intend to develop for an extended period rather than hack at it for a few weeks I knew I needed a way to handle my distractions. I have a tendency to enjoy fiddling with technology and I did not want this to get in the way of the synth development.

I decided the best course of action was to allow a small amount of time to fiddle with other stuff. This would usually be done over lunch hours or during evenings when my brain is not up to deep thought.

Enough background stuff. After watching the 1984 lisp videos on youtube (Structure and interpretation of computer programs) and thinking wow that are great I decided to have another go at learning a lisp language. I started with scheme but in the end decided I liked the deployment prospects of the JVM better and switched to clojure. I enjoyed clojure but was a little put off by the lack of a good path to get my code working on Android. I was also finding clojure quite a departure from scheme. I found it a little big, for want of a better word, and because I was spending an hour here and there playing with it I was struggling to get fluent in it. Basically I needed to devote a reasonable amount of time to get over the learning curve and that was not something I wanted to commit too.

Enter javascript. Before clojure I toyed with JavaScript. Watched a few videos and then got put off and the videos all seemed to talk about avoiding the bad bits. Not a great way to sell a language to someone. Howerver in my synth project I had to use some javascript (to support the canvas element in gwt) and found it to not be that bad. I am no expert on it but it feels quite a small language and when combined with the canvas element a good language for messing around it. It has lambda which is a requirement for a mess around language and the prototype style of OO is starting to make sense.

Of course deployment of javascript is pretty easy. Just make a webpage! It does of course have issues but none that I should hit with "figuring stuff out" code I want to write with it.

So now you know the reason why you might get some Javascript related posts on this blog and not too many clojure ones from now on.