Pages

Friday, August 14, 2015

Master of Orion II: Alkari

See Master of Orion II: every race for introduction and links to games with other stock races.

So, I've decided to play Master of Orion II with stock races and first race on the list are Alkari. They are also literally first on the race list in game (which is incidentally sorted alphabetically) and I never actually played with similar race.

Alkari are one of the many races MoO II inherited from MoO I. They are birdlike creatures who excel at piloting ships and hate catlike Mrrshans. In MoO I they had +3 to ship defense (roughly +30% to evade beams and missiles) and 40% discount to propulsion technologies, meaning they could improve ship speed, range and evasion faster.

In MoO II they have "+50 ship defense" and "artifacts homeworld" perks and "dictatorship" government. Ship defense bonus is large, +50 points to beam evasion and hidden +25 to missile evasion. It's basically inertia stabilizer without turning speed improvement. The bonus is not very useful early on when everybody use missiles and you don't have more defensive technologies. It's also no help versus space monsters since most of them have weapons that always hit. Once you get equipment for competent beam ship, the bonus will help you a lot. Paired with ECM jammer and trained (regular crew) it yields 102 missile evasion vs normal missiles and 67 evasion vs ECCM missiles which translates to 9.5% and 32% chance to be hit with no scanner and 73% with neutron scanner. Add inertia stabilizer to the mix and chances fall down to 3.4%, 14% and 48% respectively. Not bad considering it's usually hard to evade missiles. Evading beams is much easier, with this bonus and inertia stabilizer all ships would have at least 140 beam evasion and small ships with veteran and elite crew would be over 200 making them impossible to hit with beams without serious dedication to accuracy which AI doesn't do. Artifacts homeworld perk is there to get you faster to the mid game. It gives +2 research points per scientist on the homeworld only, that's 8 extra points on turn 1. With it getting research laboratory tech takes 8-9 turns less, about 5 turns less to get automated factory and almost 20 turns less to get planetary supercomputer. Great time saver early on and extra time can be used to either maintain technological lead or expand. Dictatorship is default government type in MoO II, colonies has to have barracks to mitigate 20% morale penalty and spy defense is increased by +10 points. Advanced form of dictatorship, imperium removes "no barracks" penalty while keeping +20% morale bonus from barracks, raises spy defense bonus to +20 and most importantly increases command points by 50%. Command point bonus is big deal, depending on the stage of the game you'll be spending 60% - 80% of command points on ships protecting owned systems. 50% more command points means your attack fleet could be twice or four times larger without having to pay maintenance fee. And that is recurring theme in the Master of Orion II, almost nothing is plain.

My starting location was near the center of the map (see the galaxy map below, Altair is my homeworld but as MoO player you already know that :)) so I've found Orion system and made contact with other races very early. First race I've found were Klackons at the bottom left corner but due to absolutely no suitable unguarded planet to colonize near starting system I was weak economically and it took some time to establish trade agreement with them. Trading techs certainly helped there. What didn't help was failed attempt to kill space eel guarding Yifne system. There were two large planets with decent climate and one was ultra rich. For some reason I though interceptors are going to synergize well with defense bonus and attacked the eel with two destroyers, each with one interceptor squadron. The eels have plasma flux weapon (stronger version of pulsar, area of effect weapon, always hits) and lightning field special (50% chance to destroy incoming missiles, torpedoes and fighters) which made it really well defended against early weapons, especially interceptors. Fortunately both ships successfully retreated and since I haven't had economy to make a swarm of missile ships I've abandoned the campaign for the time being. So I've tried my luck at the other end of Urna wormhole and hit the jackpot. There was Oshi system with large arid planet. I've made an outpost at Urna system and escorted colony ship with one of carrier destroyers to Oshi. Oh boy, I had reasons for military escort, it was on the other side of the galaxy and near the Mrrshan homeworld. It was only matter of time before they attacked. But before that I've made contact with Humans and started trading shortly after. My economy was good, research was getting even faster and trade got me couple of interesting techs, fusion bomb, missile base, mass driver and deuterium fuel cells. That made me free to research other techs in the same fields, most importantly class I shields and tritanium armor. By that time I've researched planetary supercomputer and soil enrichment on my own. When Mrrshans attacked I still had interceptors on my destroyer defending Oshi. I managed to destroy most of attacking fleet except the last ship. Thing is this game likes to round down numbers, if a squadron of 4 fighter loses a single member, it won't relaunch after returning to carrier. Since I had only one squadron per carrier it meant the carrier was useless after interceptors returned. I lost Oshi to ground invasion but as it turned out it was only minor setback. I've refitted remaining destroyer with autofire lasers, built another one plus a troop ship and liberated Oshi with them. No buildings and population was harmed in the process so I could continue where I've left of. The moment I've showed up in their Derke system (I've built one more destroyer so I can defend Oshi and attack with two ships) they requested peace and gave me 10% tribute. I've accepted it, ordered my fleet to return and demanded fusion drive, a technology I've hoped to gain during the war. To my surprise they agreed.



Then for some reason Humans declared war on me. There were few skirmishes at Urna system, I've lost an outpost, they lost half a dozen destroyers and almost as much frigates, I attacked their colony but didn't have enough bombs to destroy fighter garrison, made even bigger fleet, sent it to Urna, they got scared, asked for peace, gave me tachyon communication technology and all was good. Klackons declared war on me too, somebody framed me for espionage. Truth, I had decent number of spies but I was sending them to steal from Humans during the war and was honorable to those I was at peace with. After losing two battleships at Oshi they didn't make any more attacks. The reason was Antaran intrusion, they repeatedly attacked their colonies and destroyed their economy. Finally there was some period of peace. That gave me time to make few extra warships, a colony ship, kill space eel and colonize sweet Yifne system. Then Antarans attacked me at Altair. It was intense battle, I had a star base, fighter garrison, missile base and radiation shield on the planet and four destroyers armed with two autofire mass drivers (tritanium armor, fusion drive, electronic computer, class I shield, battle pods, battle scanner, inertia stabilizer and ECM jammer). They had four frigates and two destroyers. I barely survived, as I was destroying them one by one they had less and less cannons to shoot down nuclear missiles from planet, I've lost all ships and the star base but they were good distraction (ship defense bonus helped a lot) while nukes were doing the real damage.

Guess who made an audience with me then. Mrrshans! They asked for 5% tribute, I said no and got myself another war. Reason for rejection this time was my economy relied on every penny because I've lost trade agreement with Humans and Klackons and I was really looking forward to build up new colonies. Mrrshans reasoning was that I was weak after Antaran attack because I lost two thirds of my fleet. What they didn't take into account was that my fleet was made of powerful destroyers. The thing with destroyers is they can be built anywhere (bigger ships require star base) and on well developed colony it only takes two turns to build one. War was usual one, they attacked Oshi, lost a battle, brooded for a while and asked for peace when I positioned my fleet for an attack. At least my spies stole the merculite missile tech in the process. There was peace again, much longer then the last time. I've researched terraforming and started to colonize all the barren planets in vicinity, Herschel system, smaller planet in already colonized systems and Weg system near Klackons. I also colonized radiated planet in Urna system, Humans for some reason took toxic one. Then Galactic Council elections started. At the first few elections Klackons and Humans were candidates but after Antarans decimated Klackons and I expanded a little, I was there against Humans. By that time I've seen enough of Alkari, rapid early research, almost impossible to hit ships and Mrrshan opinion of them so I've decided to end the game through Galactic Council if the opportunity presents it self. So I started advancing construction field all the way up to advanced city building technology and taking planet construction in the process. My economy was thriving, military was strong in both quantity and quality. I moved from mass drivers to neutron blasters, upgraded shields to class III and armor to zortium.

There was one last war, for some reason Humans felt strong enough to demand Oshi system. I turned them down, I don't like giving away colonies. I would amuse them if it was small system but Oshi was the best system in my empire (two large planets, one small ultra rich and one normal). I said no, nope, not a chance no matter how charismatic you are and they responded with war next turn. Their first attack was at Altair no less. Again I defeated them with smaller ships without losing any. I've tried to remove them from Urna with experimental cruisers that had shield capacitor instead of ECM jammer but planetary defenses bested them. Simultaneously they colonized the Rotan system in the nebula and blockaded Herschel system with a single frigate. Colony in the Herschel system had a missile base so it was safe from invasion but it still took 50% blockade penalty. I had only one destroyer to spare, others were patrolling in other systems or blockading Urna, and sent it to bomb Rotan. I managed to destroy all buildings but couldn't finish off the last unit of population in a single turn so I've sent the ship to defend Herschel. I've attacked a frigate "blockading" my system but it had leader with defense bonus which prevented me from destroying it fast enough and it retreated to Rotan. It was a game of a cat and a mouse. I've decided to go offensive and attacked Rotan again while Human frigate came back to blockade Herschel. It took me three turns to finish off the Human colony in Rotan but when it was done, frigate didn't have enough fuel range any more to maintain the blockade and was forced to retreat. Other Human colonies fell soon afterwards, I've built another batch of cruisers (with ECM jammer this time), bombed Urna, bombed Elcorno and moved toward Sol, Human homeworld. When they saw the fleet, Humans offered hyperspace communication and asked for peace. I accepted.

I continued to arm myself expecting another war, building cruisers and upgrading them, swapped neutron blasters for graviton beams, fusion bombs with antimater ones, upgraded shields to class V and added hard shields in case of Antarans. In the mean time I expanded myself in the nebula colonizing Rotan and Grus and worked to improve relationship with other races. Klackons were still angry with me for espionage I have not done but eventually they accepted a non-aggression pact which improved relation enough to establish trade and research agreements which in turn improved relations even more. Mrrshans were a bit more agreeable to trade with me. Few elections passed and everyone voted for Humans. Since they together had less votes then me alone, no leader was elected. My fleet grew large and powerful enough to consider conquering Orion system. As I was refitting my older cruisers and preparing colony ship, Antarans appeared on the map, two cruisers 5 turns away from Altair. Not a big threat but nice opportunity to get some endgame techologies. I postponed my Orion campaign and started to build "assimilator" ships, battleships armed with assault shuttles and limited defenses, designed to capture ships. I calculated there would be three assimiltors when Antarans attack but then suddenly I won the game, two turns before battle with Antarans. There was Galactic Councile election and Klackons voted for me, though I think I would have won election anyway at that point.


Yeah I won! Still I was curious how many Antaran ships I could have captured and which technologies I would get from them and Orion. Loaded game few turns prior victory, refused to vote in Galactic Council, fought Antarans and successfully captured one cruiser, other self-destructed on capture. Scraping Antaran ship gave me particle beam and neutron bomb technologies. Then I've sent 10 cruisers to attack Guardian and won losing 4 ships. Orion gave me death rey, xentorium armor, reflection field and spatial compressor technologies.


All in on all it was a great game, challenging starting position, good AI interaction, interesting battles, nothing got too broken. And Alkari have demonstarted their strengths and weaknesses.

Wednesday, August 12, 2015

Master of Orion II: every race

Master of Orion II is an old game and I'm still playing it. It can thank it's longevity to the deep race customization and the research system that makes a player choose one path over the other. At first I was mainly playing it with "creative" race (gets all two or three technologies when advancing a field instead of only one) variations and occasionally with non-creative race (but not "uncreative") to try out some more powerful but risky combinations. Few years back I've played around various gimmicks, diplomacy, espionage, ground combat, missiles only, small ships only, etc.

Reading about stock races in both MoO I and II (mostly comments how they suck in multiplayer and how some races are plain weak) I've realized I haven't played most of them. I've played stock Psilons, Silicoids and maybe Humans on one of my first few runs. Psilons are only stock race with "creative" perk which makes them a great race for learning the game and OK choice for higher difficulty levels. After learning the game mechanics I, like most people, had tendency to play with custom races that were "creative" but had other perks different from Psilons. Problem is "creative" gives false sense of power, yes you have all the toys at disposal but wisdom in choosing technologies and little espionage can make you equally versatile and some other perk instead of "creative" can make your race expand and develop faster. There are many interesting combinations without "creative" perk. Stock Silicoids are one of them, they don't eat and don't care about environment, meaning they have roughly twice more research and industry points at the beginning then other races and can immediately exploit hostile large and/or rich planets. With a little customization say replacing slow population growth with some other negative perk could make even more powerful race.

Finding a right trait combination is practically mandatory on the highest difficulty single player and doubly so in multiplayer. Stock races are simply outclassed there. So I figured if I want to play a normal stock race I could set other settings to "normal". Not every game has to be 8 player huge map on impossible difficulty. In fact higher difficulty levels break empire interaction. Wars happen more often, if you play custom race with "repulsive" perk (no diplomacy beyond declare war but can pick more positive perks) you'll be declaring wars on sight. And there is flawed AI power estimation making it to either attack you thinking you are weak for favoring ship quality over quantity or to declare war on you because you've expanded more then they did. On average difficulty AI is much better at role playing and my first game in this series was really interesting. Below will be links to posts about the game with each race:

Wednesday, July 29, 2015

On Isaac Asimov novels

Same friend who introduced me to Harry Turtledove's Wroldwar series talk to me a lot about Isaac Asimov's Foundation series. Also I've heard a lot about Asimov's "three laws of robotics and generally how he brought robots to everyone's mind. So I started reading and got through books, all of them. I've started with this: http://scifi.stackexchange.com/questions/2335/what-order-should-asimovs-foundation-series-be-read-in, basically all of the robot stories then all of Foundation stories and finally the rest of 101th "mystery" short stories and novels. Nice thing about Asimov's novels is they are almost all "mysteries". If you are like me born 50 years after most Asimov's work was published and don't have "mystery" in your genre list, it's broader term for crime/detective story (or "krimić" in Croatian). Broader in the sense that it doesn't have to involve murder or any crime but still develops as a regular detective story, something not fully described happens and protagonist spends 500 pages collecting clues to reveal the big picture. That mystery part is the reason why his novels are so addictive.

Robot stories

Back to robots and the famous three law of robotics. First thing first, Asimov's robots are not what we call a robot today, at best they are androids (not Android but lower case android, as robot with human form) and they have very human-like way of thinking. Second thing first there was no Internet nor proper transistor powered computers back then and it shows in his work. When you see a word Multivac (also described as large as room or whole building) you'll know how little he thought about the future of computers. Back to robots and the famous three law of robotics. In Asimov's novels "robots" are metal humans with three mental restrictions. Aside from those restrictions they have normal human hopes, desire to get free from oppression, have fight or flight instinct and whole slew of human characteristic that you'll not find in modern military drones, mining equipment and mine sweeper robots. Also Asimov didn't invent any true laws of robotics, just wrote a stories that introduced reader to metal humanoid beings (MHB further on) with three particular mental restrictions and then played with what ifs. What is this restriction was taken literally, what is there was MHB without that restriction, what if there was MHB with this or that ability and so on.

In the end, despite having all technology depicted wrong (oh I have to rant about it even if it happens in the middle of the sentence like this, in one story the author postulates that is more feasible to control machinery on Mercury with special brain on Earth then to land a computer on Mercury and then believe the reader won't ask whether 25 minute lag would be a problem), robot stories were fun to read. Those where MHBs are not object of "what if" are even better and those that are prequels to prequel to the Foundation series are golden.

Foundation series

Which brings as to "great man theory". The Foundation series is more about people that defined fictive future history of mankind then about how famous psychohistorians' plan for the whole galaxy developed. Similar to robot stories there is a path the humanity is supposed to follow and author throws various what ifs that derails it but this time protagonists and objects of "what if" are humans. And each such human is an epic thinker that accomplishes great deeds through careful observation and planned action. End of the series is a bit weak, Asimov kind of went hippie there but as I've learned recently, he planned to write more, didn't have right inspiration and died. Other authors continued his work. I'm a bit skeptical but I might give them a try.

What Asimov had inspiration for was more great man stories so he wrote prequels to the Foundation detailing the life of the first psychohistorian. Who was in love (platonic, no sex, please no Hollywood crap here) with a robot, ups, MHB (at some point in robot stories MHBs became so sophisticated that some are hardly distinguishable regular humans), "mathed" his way out of deadly dangers, ruled the galaxy for a while, laid the way for new galactic empire and helped certain MHB with "zeroth law of robotics".

Robot series

Which brings as back to robot series. There were great men too, Susan Calvin (didn't say all are male), Elijah Baley and I'd include even MHB R. Daneel Olivaw. I've found stories centered around Elijah Baley most fascinating. In the first there was a murder which means mystery, in the second there was a clash of vastly different cultures, then a story about a third vastly different culture and finally a story about evolution of galactic proportions going from subtle to global. And there are toilets, vivid, detailed description of a toilet in each culture. On the serious side worth mentioning are differences in how families function, on the one side are our normal mother-father-children groups while on the opposite end is absolute separation of children and parents.

Other stories

Other stories cover so many subjects, from classic "somebody died, who is the killer?" detective story to an old lady trying to remember a street name. Some stories are weird with assumption that humans would resent going outdoor which was probably work of author's claustrophilia. And there are puns. I'm not American, English is not my mother tongue so I don't find them funny (pun gets lost in translation) and some I didn't get before looking up because they referenced some song that was popular in bygone century on the other side of the planet. But most of the stories are good read. It also helps that Asimov studied biochemistry. Golden egg goose is golden.

Wednesday, August 6, 2014

Master of Orion II - missiles

Master of Orion II is an old, old game. It was released in 1996 but people still play it and await for worthy successor. One reason why fans still play MoO II is a deep and meaningful customization. Like in AAA "RPGs" (quotes because role play games get confused with "whatever has experience bars and level ups"), before the game starts player can spend an hour picking traits for his/hers race and empire. Many traits add or remove game mechanics such as lithovore: race doesn't need food or telepathic: empire can mind control colonies. When the game starts every few turns, depending on empire's research output, player has to choose one of the two or three mutually exclusive technologies (or take all is the empire has certain trait). This choices heavily influences which tools will player have at his/her disposal, much like deck building in CCGs. And finally, player can design combat units. I can't even start to explain how much game defining it is and considering the topic I presume you, dear reader, have played the game and are familiar with most of it's feature. If you haven't played it, please do, you can get it from GoG.com for 5$.

Every now and then I find new "build" I haven't tried so far. It sounds unbelievable considering that I play the game for many years (I'm not disclosing how many :)) but I was noob back then and only used one strategy, playing turtle until I got all technologies and then unleash invincible fleet on everyone. Last few years I was trying new stuff, diplomatic race, spy race, uncreative race, empire with heavy money generation bonuses, limiting my self to only the smallest ships and so on... Recently I've tried limiting my self on using weapons other then beams. It was surprising, I had no idea interceptors are so strong in early and mid game. So in the last game I excluded special weapons too, only missiles and bombs were allowed. It was fun and tense at first but AIs were not developing well so it became too easy. They managed to keep pace with armor upgrades but by turn 350 nobody managed to get anything beyond class I shields. Still, I managed to experience new stuff. Having no beam weapons leaves ships free from beam enhancing equipment and frees up nice amount of research points. I've used those points to speed up research of chemistry (better missiles, armor and ship range) and construction, to get automated repair sooner. You see where I was going, high quality armor and self repair equals invincible ship. Unless enemy has ion cannon and it so happened that AI was good enough to get it and bad enough get any better beam weapon for a long time. I was invincible in ship to ship combat but assaulting planet required some fancy footwork in order to have shielded part of the ship facing star base when it was about to fire ion cannon.

After reaching the end of chemistry techs, I've switched to power in order to try out torpedoes. Torpedoes are interesting weapons but in my opinion too high in tech "tree". Antimatter torpedo is OK, easily accessible for mid to late game. By the time proton torpedo becomes usable the game is almost over. Same holds for plasma torpedo that is very last technology in power field. As I said I was facing underdeveloped AIs so it was not fun upgrading torpedoes when antimatter was more then enough for the job. One the bright side, researching torpedoes gives player opportunity to get energy absorber which is great addition to ships designed around taking hits instead avoiding them. Combine it with hard shields and damage reduction will be so high that all but late game weapons would become ineffective.

I've finished the game by attacking Antares and I did it twice, separately with torpedoes and with missiles. Those two roads were very different. Torpedoes were reliable on doing the job given enough time, in fact I had to attack Antares twice with torpedo ships because I reached turn limit first time. I did some bad moves and star fortress managed to shoot down 5 out of 6 ships and the last one didn't have enough fire power to destroy it within 50 combat turns. I could have brought more ships but I wanted to give some chance to Antarans :). Anyway, going with missiles was a gamble, missiles can be destroyed before doing damage and the ammunition is limited so it was possible end up in situation where ships have to retreat because they can't attack any more. I brought extra ships, just in case. With missiles it's either overkill or stalemate and aside from EMG they aren't that interesting. Unlike torpedoes, missile have no twist, they just do damage and higher missile technologies are simply damage upgrades. That is somewhat spiced by EMG, a missile modification that applies damage directly to target's engines if it's shields are down. Unlike armor, engines have very few hit points and if they are destroyed the ship self-destructs. To balance that EMG greatly increases missile size. But AI was not challenging enough to give me opportunity to try it out...

All in all there is material for another playthrough. Maybe this time with smaller ships and no creative trait. Yep, Master of Orion II is still play worthy.

Saturday, June 14, 2014

Harry Turtledove - Worldwar series

About three years ago a friend recommended me the World War series. Setting is SF alternate history where aliens with modern day human's technology are invading Earth during World War II. The twist is that aliens have serious shortcoming in their character, they are very conservative, slow at accepting change and expected that humans are too. Much like Stargate TV show where humans start underdogs and work their way among big guys, the World War setting instantly grabbed my attention.

It took me some effort to find the books and it took even more effort to read them. There are eight of them! To be exact World War on it's own is quadrilogy (four books) but there are four more books (Colonization trilogy and Homebound book) that continue in the plot and it make more sense than not to include all eight books to consideration when talking about World War. So, are the books any good?

World War grabbed my attention very fast. Aliens are well thought out and their perspective on the matter is very interesting. Their culture, psychology and biology are all thought out and consistent within the story. Human plot lines are mixed bag, most are very good and few are boring though those boring ones have moments of shine. Among good stuff are political intrigues between Russians, Germans, Poles, USA and aliens. Harry Turtledove is experienced alternate history writer and student of history so it's no wonder that those are good parts. What Turtledove is not good at are religious subjects. Since the author is Jewish and first part of the story is set during the World War II, the subject of Jew is more than forced upon the reader while other religions, if mentioned at all, are depicted in bad light. Vatican has sided with alien invaders because they supposedly prefer monarchy and got nuked with a comment that they deserved it. Mind you, the Pope at the time was Pius XII who today (June 2014) holds the title of Blessed which is one step before being Saint. Even though he didn't do much to protect Jew at the time, I feel as if the author was expressing the hate against him. On top of that Colonization series depict Muslims as nothing but violent mob, so hate speech against them is there too. Why I make so much fuss about that? Because probably the strongest point of the books is unstereothypical depiction all (most) groups of people. There are good Russians and there are bad Russians, there good, grey and bad Americans. There are good and bad Nazis too, one Nazi solder even saves city full of Jews from German nuclear bomb. But the author fails to do that on groups of people and groups I can relate with: Catholics and Croats. For some reason Croats are just evil, without much explanation. Google fails me there and if anyone can enlighten me, please drop the comment. All in all Worldwar scores 7/10 for me and don't get me wrong about Jews, they get interesting when they start standing on their feet.

Colonization covers the events 20 years after Worldwar, when alien colonists came to populate what was supposed to be conquered world. Even though they are same species and nation aliens from the first wave (conquest fleet) and colonists didn't simply get along. The Earth and humans changed aliens as much as they changed humans, they had to learn to adapt, to trade and to recognize other nations than their own. Colonists on the other hand came fresh from civilization that had only one nation and didn't do any action until it was thoroughly analyzed. Sounds like good drama material but somehow this trilogy left me with the least memories. Most scenes were static where people lives played out and nothing of importance happened, there were some forgettable characters and I was eager to read the final book. On the up side, political intrigues were still present, there were a few plot lines that made up for the boring ones and alien perspective although predictable was still interesting. All in all 5/10.

Last book in the series was so full of potential. I wish Colonization was two books shorter and Homeward Bound at least a book longer. Homeward Bound covers multiple time periods starting from about 10 years after Colonization series and ending in near future where humans develop "warp drive" and technologically surpass the aliens. Like previous books it also covers a lot of topics, politics, cultural differences, how each side adopts parts of other's culture, how humans continues to progress while aliens stagnate but all of it compressed to a single book. I'd like to read more about the alien emperor's perspective and how aliens would fare with invention of FTL technology. The story has to end somewhere and it feels like the author wanted to end it there, still if only Colonization was shorter and Homeward Bound longer. 7/10.

Wednesday, January 8, 2014

IKON: human oriented JSON look-alike

So, yet another DSL/markup but please take a look:

{ Star
   size = 12
    x = 9
    y = 4
    name "Alpha Centaury"
    planets [
        { Planet size = 100 }
        { Planet size = 120 }
        { Planet size = 10 }
    ]
}
Looks like JSON. So why make up another language? Well, unlike JSON this one isn't designed with Javascript compatibility first, instead it's designed with human editor in mind. In general case IKON (Ivan Kravarčšan's object notation) looks like JSON with less double quotes but it can be expanded with domain specific syntax. Need shorthand syntax for matrices? No problem, plug it in. And even more customization can be achieved by extending IKADN (Ivan Kravarščan's abstract data notatins) but more about it later.

(Brief) history

Before unleashing language/notation specifics allow me to tell you a little about brief history of IKADN and IKON. DSLs (domain specific languages) have a tendency of cropping up in almost every project. A year ago I decided to rewrite the Stareater, a strategy game and a rather big project of mine and since it was rewrite I knew that I'll need not one DSL but three: one for settings and save file, another one for assets (statistical data about game objects such as how much they cost and what image present them) and yet another one for localization. Most of developers would simply pick XML, XML and XML. I find XML too heavily oriented on describing data organization instead of data itself. It's good for some purposes but it's overkill for my needs. JSON, YAML and plain INI were options I considered but at some point I figured what I was really looking for is something that can adapted to a specific problem. Settings file would work OK general markup language such as JSON but localization files would work better with text oriented solution. For instance there is no need numbers and arrays in localization data while simplified syntax for single line text is very useful. So, I decided to make my own solution that satisfies specific needs.

The solution I came up with are IKADN, an abstract notation that can be used for making other markup languages and IKON, a general purpose language. The rest are technicalities but I'll mention that I'm actively using IKON and two IKADN derivates in the Stareater project for a year and improve them regularly.

About IKON

As said before IKON is general purpose solution so, much like JSON and YAML it features three classes of data:
  • Scalars (atoms of data such as numbers or texts)
  • Tables (key-value pairs)
  • Array (much like tables but with values only and values are ordered)
For more information about data types consult with project's wiki page: https://code.google.com/p/ikon-library/wiki/IKON. Some differences to JSON are that notation doesn't limit range and precision of numbers (it's up parser implementation), array items are not comma separated, table keys are without double qoutes (but they can't contain white spaces) and there is no separator between key-value pairs. Since it known where each value ends, item separators in arrays and tables would be purely cosmetic so I decided to drop them entirely. Strings (textual atoms) are similar to JSON's "backslash escaped" strings and I'm not very fond of it. It makes multiline text blocks look like a single line text and hard to edit. I do have an idea for a syntax that to make text blocks look more natural but I'm working on details on how to introduce it without breaking too hard the compatibility with previous version of the notation.

About IKADN

The sexiest part of the solution is an abstract notation that simplifies implementation (and to some degree design) of your own notation. Projects wiki page https://code.google.com/p/ikon-library/wiki/IKADN contains more details but in short IKADN syntax consist of following rules:
  • Each data type starts with a specific character (such as "=" for numbers in IKON or "[" for array), 
  • Notation designer defines how data it self looks like 
  • White spaces between data are ignored.
Doesn't look like much but IKADN parser and writer considerably simplify parser and writer of  concrete notation. Official C# implementation (I intend to write more detailed post about it later), available on NuGet, contains:
  • Logic for reading stream
  • Handling of unexpected end of stream 
  • Deciding which data type to read
  • Helper methods for reading, skipping and substituting characters from the input stream 
  • Helper methods for writing nicely indented IKADN document. 
For comparison, official implemention of IKADN consists of 243 lines of code while IKON implementation that uses it has 328 lines. That's 40% job done by IKADN.

How to get it

Official project web site it at Google Project Hosting: https://code.google.com/p/ikon-library/. There are source code, wiki pages and most recent build for .Net. Build is also available through NuGet.

Here is an example how to use the library. Let's say IKON document from the top of the post is in input.txt. This the code that would print the name of the star:


using System;
using System.IO;
using Ikadn.Ikon;
using Ikadn.Ikon.Types;

namespace IKON_example
{
    class Program
    {
        static void Main(string[] args)
        {
            var reader = new StreamReader("input.txt");
            using(var parser = new IkonParser(reader))
            {
                IkonComposite star = parser.ParseNext().To<IkonComposite>();
               
                Console.WriteLine(star["name"].To<string>());
            }
        }
    }
}


Parser can read form any TextReader subclass so if you want to read from string instead of file, use StringReader instead StreamReader. Also parser implements disposable patters so you can use it with using statement to ensure that input stream is closed after use.

Notice To<T>() method, it's the helper method for converting objects and the alternative to usual C#'s cast-and-get (cast an object to target type and then call a getter method). In the first case IkadnBaseObject is simply cast to IkonComposite (table type). The second case is more complex and shows true power or the method. Instead of type casting, underlying IkonText (textual type) returns it's contents as .Net string. Which types can be requested depends on the underlaying IkadnBaseObject subclass. For example, in the case of IkonNumber (numeric type) valid conversions include most native .Net numeric type (decimal, int, float, ...). In case of IkonArray (array type) one can ask for T[] (native .Net array) or IEnumerable<T> if array elements can be converter to T.

If you have any questions out the project, feel free to drop a comment. If you have a feature request or bug to report, you can file an "issue" on the project site too.

Tuesday, May 21, 2013

Mouse click and drag

This is a little bugger I coped with recently. In Windows forms dragging (holding a mouse button and moving the mouse) produces mouse click event after the mouse button is released. That's OK when a program is interested in only drag or click events but when it has to handle both events, each with different logic then there has to be a way to differentiate between those two events. Let's start with simple case where only mouse click is needed (C#-ish and .Net-ish code):

void init(){
    control.MouseClick.Add(clickHandler);
}

void clickHandler(object sender, EventArgs e)
{
    // Click logic
}

Now let see simple drag handler:

Point lastPos = null;
 
void init(){
    control.MouseMove.Add(moveHandler);
}

void moveHandler(object sender, MouseEventArgs e)
{
    if (lastPos == null)
        lastPos = e.Location;

    if (e.Button.HasFlag(MouseButtons.Left))
    {

        Point change = (e.Location - lastPos);
 

        // Drag logic
    }

    lastPos = e.Location;



There is no need to handle the situations when mouse leaves or enters control's area because once mouse is pressed over some control, only that control will receive mouse related events. That greatly simplifies the code for handling the mouse movement. Only overhead is checking if last position has been initialized. I hope it work the same on Linux and Mac OS with Mono.

If those two pieces of code were combined, mouse drag that ends inside starting control will trigger click handler. One solution is to simply track how far was mouse dragged:

Point? lastPos = null;
double dragDist = 0;
 
void init(){
    control.MouseClick.Add(clickHandler);
    control.MouseMove.Add(moveHandler);
}

void clickHandler(object sender, EventArgs e)
{
    if (dragDist > 0)
        return;


    // Click logic


void moveHandler(object sender, MouseEventArgs e)
{
    if (!lastPos.HasValue)
        lastPos = e.Location;

    if (e.Button.HasFlag(MouseButtons.Left))
    {

        Point change = (e.Location - (Size)lastPos.Value);
        dragDist += Math.Abs(change.X) + Math.Abs(change.Y);

        // Drag logic
    }
    else
        dragDist = 0;

    lastPos = e.Location;

}

Well, Euclidean distance would do too. I used Manhattan distance because the line of code is narrower and has less chance of being broken to multiple lines in your browser. Neat thing about this solutions is that border between click and drag can be adjusted to tolerate some mouse movement.