Friday, December 14, 2012

Your Daily digest for Tech Geek`s Tools, Tips, Tricks and Tutorials

Tech Geek`s Tools, Tips, Tricks and Tutorials
Pipes Output
ATLAS Results: One Higgs Or Two?
Dec 14th 2012, 23:16

TaeKwonDood writes with news from CERN about more results in the search for the Higgs Boson, this time from the ATLAS experiment. Researchers report peaks in the data in accordance with what they'd expect from the Higgs. The curiosity is that the peaks are a couple GeV away from each other. "The ATLAS analyses in these channels return the best fit Higgs masses that differ by more than 3 GeV: 123.5 GeV for ZZ and 126.6 GeV for gamma-gamma, which is much more than the estimated resolution of about 1 GeV. The tension between these 2 results is estimated to be 2.7sigma. Apparently, ATLAS used this last month to search for the systematic errors that might be responsible for the discrepancy but, having found nothing, they decided to go public." Scientific American has a more layman-friendly explanation available. As this work undergoes review, physicists hope more eyes and more data will shed some light on this incongruity. Tommaso Dorigo, a particle physicist working at the CMS experiment at CERN, writes, "Another idea is that the gamma-gamma signal contains some unexpected background which somehow shifts the best-fit mass to higher values, also contributing to the anomalously high signal rate. However, this also does not hold much water — if you look at the various mass histograms produced by ATLAS (there is a bunch here) you do not see anything striking as suspicious in the background distributions. Then there is the possibility of a statistical fluctuation. I think this is the most likely explanation." Matt Strassler provides a broader update to the work proceeding on nailing down the Higgs boson.

Share on Google+

Read more of this story at Slashdot.

White House Must Answer Petition To 'Build Death Star'
Dec 14th 2012, 22:57

EdIII writes "The White House petition to secure funding for building the Death Star has garnered over 25,000 signatures, which means the White House must officially respond. I can't wait to see it. My question to Slashdot readers: what modifications would you add to the proposed Death Star? Obviously, as one journalist put it, 'guardrails around any of the facility's seemingly endless number of bridges, spans, shafts and pits.' What other changes would you ask your representatives to make?"

Share on Google+

Read more of this story at Slashdot.

People Are Living Longer, With More Disabilities Than Ever
Dec 14th 2012, 22:37

skade88 writes "Worldwide, people are living longer. Their lives are starting to look more like the lives of Americans: too much food is a problem, death in childhood is becoming less common, and so on. Yet with a population that lives through what would once have killed us, disabilities are starting to become the norm. A research report from the Institute for Health Metrics and Evaluation has a good glimpse into the new emerging world we find ourselves in." The Guardian has a nice visualization of the mortality data (but take note of shifting scales on the Y-axis).

Share on Google+

Read more of this story at Slashdot.

Automation Is Making Unions Irrelevant
Dec 14th 2012, 21:54

dcblogs writes "Michigan lawmakers just approved a right-to-work law in an effort to dismantle union power, but unions are already becoming irrelevant. The problem with unions is they can't protect jobs. They can't stop a company from moving jobs overseas, closing offices, or replacing workers with machines. Indeed, improvements in automation is making the nation attractive again for manufacturing, according to U.S. intelligence Global Trends 2030 report. The trends are clear. Amazon spent $775 million this year to acquire a company, Kiva Systems that makes robots used in warehouses. Automation will replace warehouse workers, assembly-line and even retail workers. In time, Google's driverless cars will replace drivers in the trucking industry. Unions sometimes get blamed for creating uncompetitive environments and pushing jobs overseas. But the tech industry, which isn't unionized, is a counterpoint. Tech has been steadily moving jobs overseas to lower costs."

Share on Google+

Read more of this story at Slashdot.

Will Tablets Kill Off e-Readers?
Dec 14th 2012, 21:34

Nerval's Lobster writes "Are e-readers doomed? A research note earlier this week from IHS iSuppli suggested that, after years of solid growth, the e-book reader market was 'on an alarmingly precipitous decline' thanks to the rise of tablets. The firm suggested that e-reader sales had declined from 23.2 million units in 2011 to 14.9 million this year — around 36 percent, in other words. The note blames tablets: 'Single-task devices like the ebook are being replaced without remorse in the lives of consumers by their multifunction equivalents, in this case by media tablets.' Even Amazon and Barnes & Noble, the reigning champs of the e-reader marketplace, have increasingly embraced full-color tablets as the best medium for selling their digital products. Backed by enormous cloud-based libraries that offer far more than just e-books, these devices are altogether more versatile than grayscale e-readers, provided their users want to do more than just read plain text."

Share on Google+

Read more of this story at Slashdot.

Ask Slashdot: Replacing a TI-84 With Software On a Linux Box?
Dec 14th 2012, 21:12

yanom writes "I'm currently a high school student using my TI-84 for mathematics courses. It has all the functionality I need (except CAS), but saying that the hardware is dated is putting it nicely. Waiting 4-5 seconds for a simple function to be graphed on its 96x64 screen just makes me want to hurl it at the wall. Recently, I've begun to notice the absurdity of doing my math homework on a 70's era microchip when I have an i7 machine with Linux within arm's reach. I've begun looking for software packages that could potentially replace the graphing calculator's functionality, including Xcas and Maxima, but both lack what I consider basic calculator functionality — xcas can't create a table of values for a function, and maxima can't use degrees, only radians. So, does anyone know of a good software package to replace my graphing calculator (and maybe provide CAS to boot)?"

Share on Google+

Read more of this story at Slashdot.

Baltimore Issued Speed Camera Ticket To Motionless Car
Dec 14th 2012, 20:31

SternisheFan sends this story from the Baltimore Sun: "The Baltimore City speed camera ticket alleged that the four-door Mazda wagon was going 38 miles per hour in a 25-mph zone — and that owner Daniel Doty owed $40 for the infraction. But the Mazda wasn't speeding. It wasn't even moving. The two photos printed on the citation as evidence of speeding show the car was idling at a red light with its brake lights illuminated. A three-second video clip also offered as evidence shows the car motionless, as traffic flows by on a cross street. Since the articles' publication, several lawmakers have called for changes to the state law that governs the way the city and other jurisdictions operate speed camera programs. Gov. Martin O'Malley said Tuesday that state law bars contractors from being paid based on the number of citations issued or paid —an approach used by Baltimore City, Baltimore County, Howard County and elsewhere. 'The law says you're not supposed to charge by volume. I don't think we should charge by volume,' O'Malley said. "If any county is, they need to change their program.'"

Share on Google+

Read more of this story at Slashdot.

The State of In-Flight Wi-Fi
Dec 14th 2012, 19:50

CowboyRobot writes "Byte magazine gives a run-down of the current state of Internet access on airplanes. 'All of the services function in basically the same way. They provide connectivity to the public Internet via a Wi-Fi hotspot accessible from the cabin of the aircraft. This in-cabin network may also be used to provide in-flight entertainment services ranging from television network feeds to movies and canned TV shows available from an on-board media server connected to the network. In the U.S., the Internet connectivity is available when the aircraft is above 10,000 feet and is turned off during take-offs and landings. Gogo, the current market leader, provides connectivity to aircraft via a network of 250 dedicated cell towers that it has built nationwide. Fundamentally, it offers the same type of connectivity you would expect to see on a standard 3G-capable phone. The connection is limited in speed to just over 3 Mbps — and all users on the plane share this one connection.'"

Share on Google+

Read more of this story at Slashdot.

27 Reported Killed In Connecticut Elementary School Shooting
Dec 14th 2012, 18:50

Several readers sent word of a shooting at an elementary school in Newtown, Connecticut. According to most reports, 27 people are dead, including 18 children. The alleged shooter is dead, a man in his 20s. He was armed with multiple weapons and may have worn a bulletproof vest. According to CBS, "It is unclear if there was more than one gunman at the school. Miller reports authorities have an individual in custody who investigators said may be a possible second shooter." (Investigators now say the person being questioned is not a suspect.) One student was quoted as saying, "I was in the gym and I heard a loud, like seven loud booms, and the gym teachers told us to go in the corner, so we all huddled. And I kept hearing these booming noises. And we all started crying." Another, 8 years old, said, "I saw some of the bullets going down the hall and then a teacher pulled me into her classroom."

Share on Google+

Read more of this story at Slashdot.

An Interactive Graph of the Certificate Authority Ecosystem
Dec 14th 2012, 18:00

An anonymous reader writes "Researchers of the International Computer Science Institute in Berkeley have created an interactive diagram that shows root-CAs, their intermediates, the relationships between them and how many certificates have been signed by them. The graph was generated by passively monitoring the Internet uplinks of a number of (mostly) edu sites for SSL connections and their certificate Information. Among other things the graph shows that one GoDaddy intermediate signed more than 74,000 certificates and that a German CA uses more than 200 sub-CAs for administrative reasons."

Share on Google+

Read more of this story at Slashdot.

Why The Hobbit's 48fps Is a Good Thing
Dec 14th 2012, 17:18

An anonymous reader writes "Last year, when we discussed news that The Hobbit would be filmed at 48 frames per second, instead of the standard 24, many were skeptical that format would take hold. Now that the film has been released, an article at Slate concedes that it's a bit awkward and takes a while to get used to, but ends up being to the benefit of the film and the entire industry as well. 'The 48 fps version of The Hobbit is weird, that's true. It's distracting as hell, yes yes yes. Yet it's also something that you've never seen before, and is, in its way, amazing. Taken all together, and without the prejudice of film-buffery, Jackson's experiment is not a flop. It's a strange, unsettling success. ... It does not mark the imposition from on high of a newer, better standard — one frame rate to rule them all (and in the darkness bind them). It's more like a shift away from standards altogether. With the digital projection systems now in place, filmmakers can choose the frame rate that makes most sense for them, from one project to the next.'"

Share on Google+

Read more of this story at Slashdot.

Freebie: Christmas Icon Set (10 Quality Icons, 256×256px PNG)
Dec 14th 2012, 17:02

  

Today, we have a beautiful Christmas icon freebie for you created by the talented, hard-working folks at RocketTheme. The icon set contains ten icons available as 256×256px PNGs that have been lovingly and exclusively prepared for Smashing Magazine and the Web design community. As usual, the set is released under a Creative Commons license and can be used in commercial and private projects.

Christmas Icon Set

is work is licensed under a Creative Commons Attribution-NoDerivs 3.0 Unported License. You are free to build them into your work, even commercially. However, please always credit the original designer of the set (in this case, RocketTheme).

Download The Christmas Set For Free!

You can use this icon set freely for commercial and personal projects. Please link to this release post if you want to spread the word.

Free Icon Set

Description

The set contains 10 icons for the upcoming Christmas holiday. Each icon is available as a PNG. The icons included are:

  • A bag full of presents,
  • A glass ball ornament,
  • A Bullfinch,
  • Cookies,
  • Christmas decorations,
  • Christmas presents,
  • A Gingerbreadman,
  • A pair of mittens,
  • A Nutcracker,
  • A Christmas stocking.

The amount of hard work the guys behind RocketTheme have put into creating this icon set is remarkable. Hats off, guys! We sincerely appreciate your time and effort!

And if you’d like to stay updated with more upcoming freebies as well as our recent articles, make sure to subscribe to our email newsletter. Happy holidays, everyone!

(il)


© Smashing Editorial for Smashing Magazine, 2012.

No Charges In UK For Gary McKinnon
Dec 14th 2012, 16:34

clickclickdrone sends this news from the BBC: "Computer hacker Gary McKinnon, who is wanted in the U.S., will not face charges in the U.K., the Crown Prosecution Service has said. Director of Public Prosecutions Keir Starmer QC said the chances of a successful conviction were 'not high.' He announced the decision some three months after Home Secretary Theresa May stopped the extradition. Mr. McKinnon, 46, admits accessing U.S. government computers but says he was looking for evidence of UFOs. The U.S. authorities tried to extradite him to face charges of causing $800,000 (£487,000) to military computer systems and he would have faced up to 60 years in prison if convicted."

Share on Google+

Read more of this story at Slashdot.

Fast DNA Origami Opens Way For Nanoscale Machines
Dec 14th 2012, 15:52

ananyo writes "DNA strands can be coaxed to fold up into shapes in a matter of minutes, reveals a study published in Science (abstract). The finding could radically speed up progress in the field of DNA origami. DNA origami involves using short DNA strands to hold a longer, folded strand in place at certain points, like sticky tape. Until now, assembling the shape has involved heating the DNA and allowing it to cool slowly for up to a week. But researchers at the Technical University of Munich in Germany have worked out that for most of the cooling period, nothing happens. But when a crucial temperature is reached, the whole structure forms suddenly. The researchers now aim to design nanostructures with optimal folding temperatures close to 37 C, the temperature at which mammalian cell cultures are grown, so that DNA machines could one day be used in biological settings."

Share on Google+

Read more of this story at Slashdot.

Solar Panels For Every Home?
Dec 14th 2012, 15:10

Hugh Pickens writes "David Crane and Robert F.Kennedy Jr. write in the NY Times that with residents of New Jersey and New York living through three major storms in the past 16 months and suffering sustained blackouts, we need to ask whether it is really sensible to power the 21st century by using an antiquated and vulnerable system of copper wires and wooden poles. Some have taken matters into their own hands, purchasing portable gas-powered generators to give themselves varying degrees of grid independence. But these dirty, noisy and expensive devices have no value outside of a power failure and there is a better way to secure grid independence for our homes and businesses: electricity-producing photovoltaic panels installed on houses, warehouses and over parking lots, wired so that they deliver power when the grid fails. 'Solar panels have dropped in price by 80 percent in the past five years and can provide electricity at a cost that is at or below the current retail cost of grid power in 20 states, including many of the Northeast states,' write Crane and Kennedy. 'So why isn't there more of a push for this clean, affordable, safe and inexhaustible source of electricity?' First, the investor-owned utilities that depend on the existing system for their profits have little economic interest in promoting a technology that empowers customers to generate their own power. Second, state regulatory agencies and local governments impose burdensome permitting and siting requirements that unnecessarily raise installation costs. While it can take as little as eight days to license and install a solar system on a house in Germany, in the United States, depending on your state, the average ranges from 120 to 180 days."

Share on Google+

Read more of this story at Slashdot.

The Web We Lost
Dec 14th 2012, 14:29

An anonymous reader writes "Anil Dash has an insightful post about cutting through the social media hype to see all of the social functionality we've lost on the web over the past decade. 'We've lost key features that we used to rely on, and worse, we've abandoned core values that used to be fundamental to the web world. To the credit of today's social networks, they've brought in hundreds of millions of new participants to these networks, and they've certainly made a small number of people rich. But they haven't shown the web itself the respect and care it deserves, as a medium which has enabled them to succeed. And they've now narrowed the possibilities of the web for an entire generation of users who don't realize how much more innovative and meaningful their experience could be. ... We get bulls*** turf battles like Tumblr not being able to find your Twitter friends or Facebook not letting Instagram photos show up on Twitter because of giant companies pursuing their agendas instead of collaborating in a way that would serve users. And we get a generation of entrepreneurs encouraged to make more narrow-minded, web-hostile products like these because it continues to make a small number of wealthy people even more wealthy, instead of letting lots of people build innovative new opportunities for themselves on top of the web itself.'"

Share on Google+

Read more of this story at Slashdot.

NASA Prepares Probes For Suicide Mission
Dec 14th 2012, 13:46

Press2ToContinue writes "According to a NASA news release, 'Twin lunar-orbiting NASA spacecraft that have allowed scientists to learn more about the internal structure and composition of the moon are being prepared for their controlled descent and impact on a mountain near the moon's north pole at about 2:28 p.m. PST (5:28 p.m. EST) Monday, Dec. 17. Ebb and Flow, the Gravity Recovery and Interior Laboratory (GRAIL) mission probes, are being sent purposely into the lunar surface because their low orbit and low fuel levels preclude further scientific operations. The duo's successful prime and extended science missions generated the highest resolution gravity field map of any celestial body. The map will provide a better understanding of how Earth and other rocky planets in the solar system formed and evolved. Both spacecraft will hit the surface at 3,760 mph (1.7 kilometers per second). No imagery of the impact is expected because the region will be in shadow at the time.' That's too bad; observing the impacts could provide valuable feedback. For example, a spectrographic analysis of the impact dust cloud could reveal additional density and compositional element information for the lunar polar surfaces." Emily Lakdawalla at the Planetary Society has more information about the violent end to GRAIL's mission. If the probes were going to hit the surface of the Moon vertically, they would probably leave a crater about 3 or 4 meters in diameter. However, they are actually coming in at a very slight angle: 1.5 degrees from the horizontal, though the mountain itself has a 20-degree slope. Despite the darkness at the impact site, NASA will attempt to monitor the crashes using the Lunar Reconnaissance Orbiter.

Share on Google+

Read more of this story at Slashdot.

US Refuses To Sign ITU Treaty Over Internet Provisions
Dec 14th 2012, 13:04

An anonymous reader writes "The United States said today that it will not sign an international telecommunications treaty thanks to the inclusion of Internet-related provisions. According to the BBC, the U.K. and Canada have also pledged not to sign the treaty in its current form, while delegates from Denmark, the Czech Republic, Sweden, the Netherlands, New Zealand, Costa Rica, and Kenya also have reservations."

Share on Google+

Read more of this story at Slashdot.

Australian Prime Minister's Spoof "Apocalypse" Speech Goes Viral In China
Dec 14th 2012, 10:21

brindafella writes "Australian Prime Minister, Julia Gillard, recorded a spoof speech about the Mayan calendar apocalypse several days ago, for radio station "Triple J". Gillard said in part, 'Whether the final blow comes from flesh eating zombies, demonic hell beasts or from the total triumph of K-pop, if you know one thing about me it is this: I will always fight for you to the very end.' The speech has been picked up in China on Sina Weibo (China's Twitter) and has achieved well over 23,000 repeats, without anyone picking up the irony." This comes on the heels of the online version of China's Communist Party newspaper picking up an Onion story about North Korean dictator Kim Jong Un being named the "Sexiest Man Alive."

Share on Google+

Read more of this story at Slashdot.

Electrical Grid Hum Used To Time Locate Any Digital Recording
Dec 14th 2012, 08:04

illtud writes "It appears that the Metropolitan Police in London have been recording the frequency of the mains supply for the past 7 years. With this, they claim to be able to pick up the hum from any digital recording and tell when the recording was made. From the article: 'Comparing the unique pattern of the frequencies on an audio recording with a database that has been logging these changes for 24 hours a day, 365 days a year provides a digital watermark: a date and time stamp on the recording.'"

Share on Google+

Read more of this story at Slashdot.

Smart Input Field Position Indicator jQuery Plugin
Dec 14th 2012, 07:31

Advertise here via BSA

For a given input field, it would be cool to indicate the current cursor position and how much text is occupying it. It would be awesome if it’s easy to implement in any website without modifying the DOM at all. Here we got Smart Input Field Position Indicator jQuery Plugin.

It needs no images, it’s pure CSS rendering. It is accurate and dynamic, which means you can add or remove text and it will adapt. It uses Event-Delegation so don’t worry about performance if you have a million input fields or dynamically-created ones.

smart-input-field

Requirements: JavaScript Framework Demo: http://dropthebit.com/325/smart-input-field-position-indicator/ License: License Free

Sponsors

Professional Web Icons for Your Websites and Applications

How to Optimize Your Code in JavaScript
Dec 14th 2012, 07:01

Advertise here via BSA

This article recently appeared on BuildNewGames.com, a collaboration by the teams at Bocoup and Internet Explorer. It is authorized to publish on WebAppers.

At Bocoup, my colleagues and I often laze about in antique leather armchairs, sipping Mai Tais, waxing rhetoric about important issues-of-the-day including international politics and automatic semicolon insertion. One thing I find fascinating is how people working on different types of projects have different wisdom to share: best practices for jQuery plugins are different than those for Facebook apps, and tips for Backbone.js ecommerce sites may not be useful when developing real-time strategy games.

javascript-optimize

What I'd like to share in this article is some code organization tips and tricks I've learned while making HTML5 games. I've tried to keep them as generally useful as possible, but you'll definitely get the most out of this if you make games like I do.

First I'll discuss organizing JavaScript code into files and modules. Then I'll talk about code sharing approaches such as component systems. Lastly I'll share some ideas for writing data-driven code in games.

Files and Modules

It should go without saying that a large application all stuffed into one file is a maintenance nightmare. Still, even now, the logistics of organizing JavaScript in separate files are being ironed out. First let's look at the file issue itself, then the more complex issue of what sorts of modules those files contain.

Many Files in Development, Concat in Production

When setting up a new JavaScript project, I recommend using grunt, a build tool that has built-in tasks for concatenating all your files into one, then minifying the result. You want users to end up downloading just one minified JavaScript file. This is great in production, since it reduces HTTP requests and download sizes. In development, it's not so good: having readable code in separate files is necessary for efficient debugging.

I recommend having something like this in your index.html:

1  2  3  4  5  6  7  8  9  10  11  12  13
<head>    ...    <!-- source files for development -->    <!-- <script src="src/setup.js"></script> -->    <!-- <script src="src/player.js"></script> -->    <!-- <script src="src/enemy.js"></script> -->    <!-- <script src="src/bullet.js"></script> -->    <!-- <script src="src/explosion.js"></script> -->      <!-- concatenated / minified source for production -->    <script src="production/app.js"></script>     ...  </head>

This way you can comment out app.js and uncomment the source files for easy development.

However, this isn't ideal. One thing you might do is modify your build process to have options to build for development or for production, saving you the effort of manually commenting / uncommenting lines. No build tools do this out of the box as far as I know, but for some projects this extra effort of customizing your build process may be worthwhile.

Source Maps

Google Chrome has a cool new feature called Source Maps that solves this problem. When you use a JavaScript concatenator/minifier that supports Source Maps, the compiler will add a comment to the code that refers to the source map (a header can also be used). The source map contains all the necessary information for linking from the compiled code to the source file. As a result, development tools that support Source Maps will understand what file some given code originally came from. There is no longer any issue debugging / developing with minified code.

Right now the Closure compiler and Google Chrome are the only compiler and browser that support Source Maps, so it can only be used on certain projects. Still, if more tools start to support it, this may be the future of debugging JavaScript.

IIFEs and Namespaces

Now that you have a build process that intelligently handles multiple files, what actually goes in those files?

The first concern is global variables. Since global variables in separate files are still shared, we can use IIFEs to give each file its own local scope. Here is an example:

file1.js

1  2  3  4  5  6  7  8  9  10
(function() {      var i = 0;      setInterval(function() {      i += 2;      console.log("File 1 counter: " + i);    }, 1000);    }());

file2.js

1  2  3  4  5  6  7  8  9  10
(function() {      var i = 0;      setInterval(function() {      i += 5;      console.log("File 2 counter: " + i);    }, 1000);    }());

The first and last line of each file is the IIFE. The only purpose of those lines is to create a local scope for each file. As a result, the i variable in each file will not conflict.

This works to avoid conflicts and polluting the global scope, but what about when we do want to share state between files?

A global namespace is my favorite way to handle this. In this approach, your game will have one single variable in the global scope. It will contain a hierarchy of all the game's global state. Here is an example:

1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19
(function() {      // create global namespace    window.game = {};      // add some data    game.player = {      hp: 10,      mp: 5    };      game.enemies = [];      game.enemies.push({      name: "zombie",      hp: 10    });    }());

Then, another file could access this information:

1  2  3  4  5  6  7
(function() {      // set up the UI    document.getElementById("hp").innerHTML = game.player.hp;    document.getElementById("mp").innerHTML = game.player.mp;    }());

Often it's convenient to use the IIFE to pass through global variables as local variables. The previous example could be modified like so:

1  2  3  4  5  6  7
(function(player) {      // set up the UI    document.getElementById("hp").innerHTML = player.hp;    document.getElementById("mp").innerHTML = player.mp;    }(game.player));

A pattern called the Module Pattern is similar. In this pattern, the IIFE is modified to return a value that is put in the global scope:

1  2  3  4  5  6  7  8  9  10  11  12  13  14
window.game.boss = (function() {      var hp = 30;      if (game.temperature < 5) {      hp -= 10;    }      return {      name: "elder red kitten",      hp: hp    };    })();

Notice in the last line that we've moved the () outside of the parentheses that wrap the IIFE's function. This is not necessary but is often done to indicate that the return value is used.

Module Systems

With IIFEs and namespaces we have solved the global scope issue. However, we may still have issues in projects with complicated dependencies. In some games its reasonable to just include all your scripts in the order that they depend on each other. For projects with more complicated dependencies, especially multi-page apps with different script needs on each page, a module system may be helpful.

RequireJS is an advanced JavaScript module loader. With RequireJS, you can have just one script element in your HTML:

1  2  3  4  5
<head>    ...    <script data-main="scripts/main" src="scripts/require.js"></script>    ...  </head>

Then, in your main.js file, you use require to load other scripts that you need:

1  2  3
require(["scripts/world"], function(world) {      // world.js will load, then this code will run  });

Each other file loaded by require can have its own dependencies, and so on. You end up with a dependency graph that reflects your code's actual needs, rather than a mysterious load order that just so happens to work. This makes it much easier to set up a separate page that needs some, but not all, of your scripts. Think of a save / load screen, or a high scores list, that needs information about loading player accounts, but not information about collecting powerups.

You need to follow the AMD specification to use require.js, so you should familiarize yourself with that if you intend to use it.

Now that we have these basics worked out, we can move on to the fun stuff: how to organize the code itself.

Code Sharing

A whole lot of code organization boils down to code sharing. How do you share code that is used in more than one place? It's a big question, and ultimately the answer depends on your project, your language, your frameworks, and your personal preferences.

A common symptom of poor code sharing is super objects. A super object is an object that has too many responsibilities. It's too big, and it contains a lot of code that would be better organized into different units. Often, super objects are a result of laziness. When writing new code, it's easiest to just put the code in the nearest super object, rather than deciding where it really belongs. The best weapon in the fight against super objects is diligence.

Here's an example. Let's say you have player.js and enemy.js. You want to write the code wherein an enemy damages the player. At first, it seems convenient to put it in player.js, since the code concerns the player's properties.

1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17
(function() {      game.player = {        receiveDamage(amount) {        if (Math.random() < this.resist) {          amount /= 2;        }        this.hp -= amount;        if (this.hp <= 0) {          this.die();        }      }      };    }());

Later, we add a feature where an enemy can poison the player. Let's add that code in there.

1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19  20
(function() {      game.player = {        receiveDamage(amount, enemy) {        if (Math.random() < this.resist) {          amount /= 2;        }        this.hp -= amount;        if (this.hp <= 0) {          this.die();        }        else if (enemy.poisonous) {          this.setPoisoned(true);        }      }      };    }());

Then we add enemies that can blind the player. Then enemies that can stun the player. receiveDamage is getting too big, and player is becoming a super object.

One problem is that receiveDamage is very entangled with both the enemy and player objects. To untangle this code, we should put the enemy's responsibilities in one place, and the player's responsibilities in another.

Another issue is that there is only one type of player, but many types of enemies. In this case, each type of enemy should describe its own unique interaction with the player, rather than having the player, or a common enemy object, describe every type of interaction.

Let's rewrite this code in 3 different files.

Now we can extend this code in a more reasonable way. You may have noticed that the poisonous enemy uses explicit delegation to call enemy.damagePlayer. This is perhaps the simplest form of code sharing, and it works, but this is a clear example where implicit delegation via inheritance may be preferable. We could refactor this code to use inheritance, but instead, let's discuss another option…

Components

Laziness isn't the only cause of super objects. A more subtle problem is when your code sharing strategy doesn't suit your object model. Many classically-trained programmers have been taught that inheritance is a one-size-fits-all code sharing strategy. In fact, many programming languages seem to have that assumption baked in. Let's show an example where classical inheritance falls short, then discuss an alternative.

Here is some simple code to start with:

Maybe you wrote this code by writing methods as they became useful. But, stepping back, you realized this: all of these objects need to be able to do all of these things! Using inheritance, you might move all these methods up to a common parent, like so:

Now the common behavior is shared, but you can still add custom code for each type of entity.

There are two potential problems here. First, it's possible that entity will end up being a super object. Second, it's possible that while most enemies can move, some can't! Or that there are rare indestructible crates! How do we deal with these exceptions?

For many applications, inheritance works great. It turns out, though, that the problems I just described are very common in game development. For this reason, many game developers use components.

With inheritance, objects get their behavior from their place in the inheritance hierarchy. With components, objects contain any number of components which determine their behavior. These components can be mixed and matched differently in each object. Let's look at an example using components:

The first thing you'll notice in this code is that a simple component system is implemented in componentSystem.js. Some game frameworks provide their own more robust component systems. Then there are files for each component that entities can contain. At the end there is some code demonstrating how to use the component system to create entities with different capabilities.

At first, it might seem strange to check if a method exists when you want to use it. You may not always need to do that, for example in code where you can safely assume a method will be present, or for methods that you know are always present. You could even create a component system where this check is not necessary. For my games, I tend to embrace duck typing. I've found that the test isn't tedious because it's important to consider what might need to go in the else block.

You could build a more complex component system where components remain encapsulated after they've been added to an entity, which may be useful if you want to achieve state that is private to each component. This may be seen as a "true" component system, where what I've built in this previous example may be closer to mixins, or abstract base classes with multiple inheritance. The lines between these concepts tend to get blurry in JavaScript, and either way, what we've built in this example is incredibly expressive as is.

Code and Data

Another aspect of code organization in games is data. Data-driven programming involves a separation of code and data, where the code reads in data files that describe objects and their states, then the code is responsible for describing how those objects behave and interact. A common example in games is world files: descriptions of maps and monsters read in and brought to life by the game code.

Let's look at a simple example of some data-driven code:

This is great for two reasons. One, a separation of data and logic makes for more maintainable and more reusable code. Two, a team member without programming experience is better able to contribute to content creation.

That should be easy enough. What's less clear is what happens when the line between code and data gets blurry. Let's say that we want to create some code that is only relevant to dragons:

Now damage against dragons is reduced by half. Maybe lots of enemies have this "half damage" trait? You'd be better off making a halfDamage property in your data format. That's pretty straightforward.

On the other hand, it depends on how your data will grow. The direction we just described will work well if you have a small number of traits that are frequently reused. Where this approach falls short is when you have a large number of enemies with unique properties. You'll end up with a big, complicated data format that is mostly dedicated to describing exceptions to the rules.

What I advocate in these cases is data-like code. Rather than using JSON, we'll use JavaScript that happens to be mostly data, but with the ability to add custom code at predefined locations. Here is an example:

We've added the ability for enemies to define a custom filter on the amount of damage they receive. We can easily add one enemy that always takes half damage, then another enemy that takes double damage. I added self as an argument to filterDamage because it's very useful in these types of data formats: you may want to filter damage differently based on the enemy's state. The best part is, you can create all kinds of unique enemies without modifying the data format. The code and data are still mostly separate, except where a little overlap is appropriate. And a non-programmer could still work with this data pretty easily, until they need to ask for help with a special enemy (which they would have had to do anyway).

Of course, if your game doesn't need anything this complicated, it's always best to stick with the simplest data format that works.

Conclusion

I hope these tips were helpful for you. If you want to play a game I developed where I learned some of these lessons, check out 91. If you want to see a game framework that uses a cool component system as described in this article, check out my boxbox project. Have fun making games!

About the Author

Greg is a hacker at Bocoup. You can follow his blog at incompl.com.

Sponsors

Professional Web Icons for Your Websites and Applications

New "Sanny" Cyber-Espionage Attack Targets Russia
Dec 14th 2012, 06:56

CowboyRobot writes "A new targeted attack campaign with apparent Korean ties has been stealing email and Facebook credentials and other user-profile information from Russian telecommunications, IT, and space research organizations. The attackers are grabbing email user accounts and passwords from Outlook, as well as information about the victims' email server."

Share on Google+

Read more of this story at Slashdot.

Japanese Police Offers First-Ever Reward For Wanted Hacker
Dec 14th 2012, 05:28

alphadogg writes "Japanese police are looking for an individual who can code in C#, uses a 'Syberian Post Office' to make anonymous posts online, and knows how to surf the web without leaving any digital tracks — and they're willing to pay. It is the first time that Japan's National Police Agency has offered a monetary reward for a wanted hacker, or put so much technical detail into one of its wanted postings. The NPA will pay up to $36,000, the maximum allowed under its reward system. The case is an embarrassing one for the police, in which earlier this year 4 individuals were wrongly arrested after their PCs were hacked and used to post messages on public bulletin boards. The messages included warnings of plans for mass killings at an elementary school posted to a city website."

Share on Google+

Read more of this story at Slashdot.

Seattle To Get Gigabit Fiber To the Home and Business
Dec 14th 2012, 03:01

symbolset writes "Enthusiasm about Google's Kansas City fiber project is overwhelming. But in the Emerald City, the government doesn't want to wait. They have been stringing fiber throughout the city for years, and today announced a deal with company Gigabit Squared and the University of Washington to serve fiber to 55,000 Seattle homes and businesses with speeds up to a gigabit. The city will lease out the unused fiber, but will not have ownership in the provider nor a relationship with the end customers. The service rollout is planned to complete in 2014. It is the first of 6 planned university area network projects currently planned by Gigabit Squared."

Share on Google+

Read more of this story at Slashdot.

Ask Slashdot: Facebook, Twitter For Business, Is It Worth the Privacy Trade-Off?
Dec 14th 2012, 01:28

cayenne8 writes "I've been a staunch advocate of NOT joining Facebook or Twitter or the other social networks to protect my privacy and to not voluntarily give all my personal information away to corporate America, or even the Government. However, I'm beginning to look into making money through various means on the side, one of them being photography/videography. With these mediums, being seen is critically important. Having a business facing site on Facebook/Google+ and even using Twitter can be great for self promotion, and can open up your business to a huge audience. If you were to open your FB and other social network accounts with business ONLY information, and keep your personal information (name, image, etc) off the Facebook account...will this keep your personal privacy still from them, or are their algorithms good enough to piece together who you are from the business only sites? Is the payoff worth the potential trade-off for generating potential customers for your business and guiding them to your primary website?"

Share on Google+

Read more of this story at Slashdot.

Slashdot Story Helps Raise $43,200 For the FreeBSD Foundation In Three Days
Dec 14th 2012, 01:00

An anonymous reader writes "The FreeBSD Foundation has posted blog article article talking about the remarkable surge in donations they've received in the last three days following a recent Slashdot article reporting on weak fundraising this year. Deb Goodkin reports that the FreeBSD Foundation, as with many non-profits, receives more than 50% of its annual funds at the end of the US tax year, but that the Foundation has never seen this rate of donations before, and will hit a new record for unique donors this year. She comments that it was Slashdot readers that made the difference! She does, however, appeal for further donations noting that they have a long way to go on their full goal."

Share on Google+

Read more of this story at Slashdot.

The SEO Spammers Behind Online Infographics
Dec 14th 2012, 00:39

jfruh writes "Over the past couple of years, you may have noticed a rash of often high-quality infographics by third parties appearing on your favorite websites. These images are offered to Web publishers free of charge, with the only request being a link back to the creator's own site. But when one blogger got an odd email from a the creator of infographic he put on his site two years ago, he did some digging and discovered that he had inadvertently helped some shady characters do SEO spamming."

Share on Google+

Read more of this story at Slashdot.

You are receiving this email because you subscribed to this feed at blogtrottr.com.

If you no longer wish to receive these emails, you can unsubscribe from this feed, or manage all your subscriptions