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

Saturday, December 08, 2018

A little RPG in React Native


I built a little role-playing game in React Native. I tried to build the type of game I like playing, with quests and interactions with non-playing characters, while learning some mobile UI programming tricks.  These are some of the main points that I took away:

  • The initial setup was a bit involved, probably because I'm not used to develop JavaScript applications. Getting the right code to properly do the plumbing between React, Redux,  React Navigation, tests, etc. was a bit of a hassle. Obviously this has to be done once and then you can concentrate on writing the functional code. As I noted recently, then upgrading to newer versions of your dependencies can be a hassle!
  • I was happy with my declarative approach to the game world. I don't think it would be manageable to do otherwise.  I define as JavaScript structures the world itself: the different places and how they communicate, the items they contain, etc., the non-playing characters and the possible interactions you can have with them, items and their characteristics, monsters and spells. This gives me an immutable representation of the start world, and the state of an actual game just has to store the modifications from that initial state
  • This of course could mean that I (or somebody else) could reuse the game mechanics for a totally different adventure!
  • I of course used of Redux to manage state. The state is only modified by Redux reducers, so everything the player does in the UI just becomes actions, not explicit state management operations. I combine several reducers, each reducer being responsible for modifying one section of the global state, which makes each reducer simpler, but fragment the code. For example when the player takes an item from a room, one reducer adds the item to the inventory, another removes the item from the room, so maybe there's some potential for bugs there
  • I found the integration between React and Redux easy to use: you simply define the mapping between the state and components properties, and between component interactions and Redux actions.
  • I abused a little bit Redux to implement combat: combat holds a kind a mini state for each fighting round, and then the result of a fighting round both is represented in the UI ("the rats bite you for 2 damage"), and impacts the global world.
  • I didn't spend too much time on the UI, just using basic React Native components. I found some of the layout hard to do correctly, and styling components is not intuitive when you're not a CSS expert. Maybe I should take a CSS/Design course, because you can tell from my UI designs that I'm a programmer :-)
  • All in all, writing in modern JavaScript was nicer than expected, even though I think using a stronger typed language would be better. If I had to do another similar project I would probably try to use Typescript. I liked especially the object spreads to update parts of structures and the use of consts.
  • I used Expo to test on a tablet, I didn't try to actually generate a final application outside of Expo, I haven't looked at all on how to distribute the game as an app.

All in all, if was an enjoyable experience, but of course designing a full game instead of just a prologue you can do in 5 minutes would be a different type of endeavor...




Tuesday, December 04, 2018

Fun with NPM and Expo

Some time ago, I wrote a little game using React-Native so I could play around in Javascript with React, Mobile development and Redux. Yesterday I checked this project again on Github, and saw that there was a security issue Github detected and warned me about: the "merge" library had a vulnerability, reported in CVE-2018-16469. OK, time for action!
Of course, my project doesn't reference merge directly. It's a transitive dependency of jest. A quick check on the web showed that since I created the project, a lot of things have happened, so my project dependencies are lagging behind. So hopefully upgrading should solve my security issue.
I find instructions at https://stackoverflow.com/questions/16073603/how-do-i-update-each-dependency-in-package-json-to-the-latest-version, so I run npm outdated, which indeed confirms a lot of my dependencies are old.
I install npm-check-updates:
npm i -g npm-check-updates
ncu -u
As indicated, and I get:
Hmmmmm... this is taking a long time. Your console is telling me to wait for input on stdin, but maybe that is not what you want.
Try specifying a package file explicitly with --packageFile package.json.
See https://github.com/tjunnone/npm-check-updates/issues/136#issuecomment-155721102

OK, then:
ncu -u --packageFile package.json

This updates everything, and then my app doesn't start anymore. Turns out a lot more changes have happened when I wasn't looking, and the react native starter app I created has now changed to use expo-cli. I find some instructions on how to change the npm scripts, but it doesn't solve everthing, I still get an error in the react-native-scripts main file, because the main entry also needs to be changed (thanks https://docs.expo.io/versions/latest/sdk/register-root-component#i-created-my-project-before-sdk-18). Then it stills fails because the babel module has been renamed, thanks to https://forums.expo.io/t/problem-upgrading-to-sdk-31-cannot-find-babel-plugin-transform-react-jsx-source/16246. And then on my expo client I get a Javascript mismatch error, that https://stackoverflow.com/questions/47763824/react-native-version-mismatch helped me solve...

OK, now my game starts again, I suppose I need to test it thoroughly because something may again decide to break... I did enjoy developing the game, but certainly managing the NPM vulnerabilities and the Javascript ecosystem pace of change can be challenging. I know this isn't an original thought, but experiencing it first hand is definitely an eye-opener!


Friday, August 28, 2015

A Reddit clone (very basic) using Local Storage and no server side storage

Some weeks ago there was a bit of a tussle over at Reddit, with subreddits going private in protest, talk of censorship, etc. This was interesting to see, from a distance. It got me thinking about trying to replicate Reddit, a site where people can share stuff and have discussions, but without having the server control all the data. So I've developed a very basic Reddit clone, where you can post links and stories and comment on them. You can also upvote stories and comments, and downvote what you upvoted (cancel your upvote). But there's a catch: the site has no database. Things are kept in memory, and on the users machine, via the HTML 5 LocalStorage. That's all!

Everytime you upload or upvote something, it gets saved to your LocalStorage for the site. Once something gets downvoted to zero, it disappear. When you go to the site, whatever is in your LocalStorage gets uploaded and upvoted again. So stories can come and go as users connect and disconnect, and only the most popular stories will always be visible on the site (since at least one connected user needs to have uploaded or upvoted a story for it to be visible).

Of course, there is still a server, that could decide to censor stories, modify text, but at least you can always check that what you have on YOUR machine is the data you wanted. you can always copy that data elsewhere easily for safe keeping (browser developer tools let you inspect your LocalStorage content).

All in all, this was probably only an excuse for me to play with Javascript and Java (I did the server side in Java, since it was both easy to build and deploy) and Heroku. I've deployed the app at https://fivemegs.herokuapp.com  and the source code can be found at https://github.com/JPMoresmau/5megs. Any feedback welcome!

Monday, April 18, 2011

Pirates 0.2: fixes and a chat interface

I released a little update to my Pirates Yesod/Canvas game. Nothing too dramatic, but the new version, still at http://pirates.dyndns-free.com boasts:

  • Fixes in the collision detection code
  • A chat interface, so you can talk to the other ship you're fighting with. Stock up on pirates insults!
  • Fixes in handling of games when a ship leaves the game before it's finished
As I said, nothing too fancy, but I find that polishing off bugs and adding unplanned features is often a good exercise, especially for personal projects where the temptation is great to just move to something else when it kinda works. The chat interface was interesting: the server side code was done in a few minutes, using the same event system as the rest, but I struggled longer with the HTML to get the right positions for everything, as usual... Now it's on the right hand side, outside of the canvas area, which makes the full game area much bigger than the original 800x600, but I don't think I get a lot of mobile users anyways (-;.

I could probably make the game more appealing long term by having a bigger area where more than 2 ships could battle, and have more of a RPG feel to it (maybe be able to log in and out so you keep your ship, be able to repair it in harbours, etc...). I'll see what I have time to do. Any suggestions welcome!

Wednesday, May 16, 2007

Javascript and Hibernate, hand in hand

Some time ago I had written a little prototype that was quite interesting, but I never pursued it. Maybe I should try to get some people interested and develop it further...
The idea was to use Rhino to have a Javascript-based framework on the server, thus using the same language on the server and on the client, like ASP did in the good old days. I was also thinking of having the source code for custom applications stored in the database, instead of having it in source files, but that's another story. That explains why the examples below are about "applications" and "components"
The first component is Hibernate connectivity. My framework lets you:
1. Dynamically configure Hibernate mapping for Javascript defined classes. For example, if you wanted to define a Web Application with several attributes and a reference to the components that it defines:

function Application(){
this.displayName='';
this.urlName='';
this.defaultUrl='';
this.id=-1;
this.components=[];
}


Application.storage(
{
id:
{name:'id',column:'ID',type:'long'},
properties:
[
{name:'displayName','not-null':true},
{name:'urlName','not-null':true,unique:true,'unique-key':'APPLICATION_URL'},
{name:'defaultUrl'}
],
references:
[
{'list':
{name:'components',table:'APPLICATION_COMPONENT',
details:[
{'key':{column:'APPLICATIONID'}},
{'list-index':{column:'idx',base:'0'}},
{'many-to-many':{'column':'COMPONENTID','class':'Component'}}
]
}
}
]
}
);

Note that storage() is a function of the Function object which takes a Javascript structure that mimicks the Hibernate XML.

2. Access Hibernate functionality through a "hibernate" host object. For example, a JSUnit method testing the addition of a new "Application" object:

var appId;
var appUrlName;

function testAdd(){
assertNotUndefined(hibernate);
var app=new Application();
assertNotUndefined(app);
app.displayName="TestAppJS"+new Date();
app.urlName=app.displayName;
appUrlName=app.urlName;
hibernate.save(app);
hibernate.commit();
assertNotNaN(app.id);
assertTrue(app.id>0);
appId=app.id;
}

The hibernate object lets you list objects, get a particular object, modify or create instances, etc. I have implemented a Hibernate EntityTuplizer and an subclass of Rhino's NativeArray that encapsulate a PersistentList, so that multiples references can be seen as Javascript arrays.

3. Query the database either through the HQL language:

var apps=hibernate.query("from Application where urlName=?",["TestAppJS"]);

or through a pure Javascript function based mechanism:

var apps=hibernate.query("Application",function(app){
return app.urlName=="TestAppJS";}
);

That I think is very cool. In Rhino I can access the source code of the function that is passed as the second argument to query, and transform it into HQL. I haven't implemented as much as I could, of course, but it works with simple queries. At least there is no other syntax to learn to do a query, it's basically the equivalent of a filter function in functional language.

Then I had started to develop a web framework (probably the millioneth Java web framework by now) with Javascript objects to generate HTML and a mapping between urls and javascript functions, and where one URL could chain several functions, but I haven't gone very far.

Now if somebody feels there's some value in any of that I can sure post the code and we can move it forward. Anything that can show that Javascript is a cool language to run in a JVM in a worthwhile enterprise (-:

Friday, May 11, 2007

Poor man's JavaFX Script is, er... Javascript

Sun has release its own RIA framework called Java FX. It provide JavaFX Script, which is a language based on Java whose goal is to develop quickly graphical applications with the power of Java. Is it touted as competition to Flex that I have mentioned before. It is safe to say that it hasn't been received with a great deal of enthusiasm. The fact is, I don't want to learn another language again to do my Web 2.0 application. And I do believe that Fielding has a point when he reflects that applets break visibility and raise the barrier of entry for web developers. Also, I'm usually all in favor of static typing and compilation, but for GUIs I'm not too sure. When you want to tweak your borders or your layouts you probably happy enough with a quick cycle of change code/refresh page. So why don't we use Javascript and Java Applets together instead of inventing yet another technology?
Ok, it's time you get over your irrational distrust of Javascript. A multi paradigm (object, functional) language available for free in every browser!! And no, I don't suggest we go on using the HTML DOM or things like that. That's why we need applets.
Applets? I must be mad! Applets have not worked on the web. But what I suggest is not to develop one applet for each RIA application, but only develop one Applet that everybody could use, much like a plugin, that would bridge the gap between the JavaScript world and the Java/Swing world. If it has been done, please let me know. As for me, I've put together a prototype in an hour that works fine:
  1. The JavaScript code constructs an object tree that represents the GUI.
  2. The object tree is serialized to JSON and passed on to the applet
  3. The applet deserializes the JSON and constructs a Swing GUI by translating the object tree
  4. The object tree can contain handlers that are the names of Javascript functions
  5. The applet calls the javascript functions on Swing events
  6. The JavaScript event handlers update the GUI tree and notify the applet with the changes.
A very simple example:


<html>
<head><title>JSApplet</title>

<script language="Javascript">

var helloButton={type:"button","id":"helloButton","text":"hello","action":onClickHello}
var frame={"contents":
[
helloButton
]
};


function onClickHello(){
helloButton.text=helloButton.text.toUpperCase();
updateJS([helloButton])
}

function startJS(){
var msg=document.getElementById("JSApplet").setContent(toJSON(frame));
if (msg){
alert(msg);
}
}

function updateJS(objs){
var msg=document.getElementById("JSApplet").updateContent(toJSON(objs));
if (msg){
alert(msg);
}
}


toJSON=function(arg) {

switch (typeof arg) {
case 'object':
if (arg) {
if (arg.constructor == Array) {
var o = '';
for (var i = 0; i < arg.length; ++i) {
var v = toJSON(arg[i]);
if (o) {
o += ',';
}
if (v != null) {
o += v;
} else {
o += 'null,';
}
}
return '[' + o + ']';
} else if (typeof arg.toString != 'undefined') {
var o = '';
for (var i in arg) {
var v = toJSON(arg[i]);
if (v != null) {
if (o) {
o += ',';
}
o += toJSON(i) + ':' + v;
}
}
return '{' + o + '}';
} else {
return;
}
}
return 'null';
case 'unknown':
case 'undefined':
case 'function':
return arg.name;
case 'string':
return '"' + arg.replace(/(["\\])/g, '\\$1') + '"';
default:
return String(arg);
}
}

</script>
</head>
<body onload="startJS();">
<applet id="JSApplet" alt="JSApplet" code="fr/moresmau/jp/jsapplet/JSApplet.class" codebase="bin" mayscript="mayscript" height="100" width="100"></applet>



</body>
</html>


This web page creates a simple "Hello" button that when clicked changed its text to upperCase(). It demonstrate the two ways communication between the Javascript code and the applet (note how the function is serialized in JSON just with its name, that's the only thing we need). So the Javascript can deal with a model that is a slightly abstracted Swing model (no more hair pulling between different browsers). I stress again, the applet is a generic applet that deals with the link between the JSON objects and the Swing layer. Of course the applet could offer other services: simple API to call back the server (AJAX from the applet), etc...
Then the applet could be packaged with a cut down version of the JRE (only the classes really needed) as a plugin to do rich Swing application from JavaScript...
And voilĂ ! A scriptable RIA platform!