Planet Gamedev

Game AI for Developers

BROADCAST: Massively Parallel AI Kernels in C++ With OpenCL SYCL (October 30th)

by Alex J. Champandard at October 24, 2014 09:00 PM

BROADCAST: Massively Parallel AI Kernels in C++ With OpenCL SYCL (October 30th)

This upcoming broadcast on Thursday, October 30th at 19:00 UTC will take place online within your browser using streaming audio/video:

“This tutorial will focus on the new OpenCL specification called SYCL that allows developers to write parallel code in C++ as a single-source program. Using modern C++ programming techniques, kernels that run on the GPU (device) can be integrated into CPU code (host) easily using templates. This session will show some patterns to use in your code to make sure it's SYCL-compatible, and tools to use to help improve performance.”

To subscribe for email reminders and check the exact time in your current timezone, visit this broadcast's page on

Game From Scratch

C# comes to Unreal Engine

by at October 24, 2014 06:45 PM


On a daily basis I use dozens of different programming languages.  Some languages are certainly better than other languages at certain tasks, while other languages truly shine on certain platforms.  Some languages are more portable than others, others are more customizable while some can be faster.  All that said, when all other things are equal and I need to just pick a language, the one I go to is generally C#.  C# just strikes that right balance for me, straddling the line between low level and productivity, convenience and speed, functional and procedural, for me at least.  This news then is welcome, for me at least. :)


Xamarin, the maker’s of Mono, a cross platform open source version of the .NET runtime and framework (Perhaps most famously known as the language technology that underpins Unity)  have announced they are bringing it to Unreal Engine.  Here are some of the features and benefits of Mono for Unity:


Hot Reload


We fully support Unreal Engine's Hot Reload functionality.

This means that whenever you rebuild your C# code in Xamarin Studio, your changes are immediately reloated into the Unreal Editor. The changes are also reflected with running games in the editor, so you can quickly iterate on your design.

On fast machines, the process of rebuilding the C# code and reloading it live takes less than a second. It feel instantaneous.


Xamarin Studio

While hard core hackers are happy editing their game code with vi or emacs and have the hot reload functionality do all the work for them, we have also provided a nice integration with the MonoDevelop (and Xamarin's branded version, Xamarin Studio).

It provides a first-class IDE with rich, accurate code completion, and powerful refactoring and analysis tools.



Full support for C# debugging is included. Simply launch your game from Xamarin Studio as a standalone editor or mobile preview process, and it will connect to the runtime debug engine, giving you full access to a rich suite of abilities to inspect and debug your code.

Seamless Blueprint and Editor Integration

Your C# classes that are exposed to Unreal Engine are fully accessible from Blueprint and the Unreal Editor, just like Blueprint-accessible C++ classes.

You can continue using Blueprint for simple logic and use C# when things get more complicated.

And you can consume your C# classes from Blueprint.


Mixed C#/C++/Blueprint Solutions

The same tool that we use to generate bindings to Blueprint-exposed Unreal Engine APIs is integrated into Unreal Build Tool, and will automatically generate bindings to all of your Blueprint-exposed C++ gameplay code and engine modifications.


Native Access

In addition to the automatically generated bindings to Blueprint-exposed Unreal C++ code, the Mono runtime allows accessing any native APIs, including custom C/C++ code and the native platform API.

You can manually bind C APIs using Platform Invoke services, or use CppSharp to generate bindings to C++ APIs.


Async Programming

The Getting Started tutorial shows the low-level approach to defining behaviors, but this approach can become cumbersome when defining more complex behaviors and AI. Luckily, this task can be simplified with async programming, a C# compiler feature that rewrites what appears to be linear code into a state machine.

For more details about how this helps writing complex gameplay logic, see our overview of async programming.


API Profile

The Mono Mobile Profile is the core API profile in the support for Unreal Engine.

The Mono Mobile Profile removes a number of bloated .NET features including System.Configuration support from the Base Class Libraries. This is the same API profile used by Xamarin's Android, iOS and Mac products.

Note: The Mobile Profile is not ABI compatible with existing assemblies compiled for a different profile (like the .NET desktop, Silverlight or Windows Phone). You mustrecompile your source code to generate assemblies targeting the Mobile profile.

A full list of the assemblies in our Mobile framework profile can be found here.


Portable Class Libraries

You can use Portable Class Libraries with Xamarin's Unreal Engine support. This allows the same binary library to be shared across a wide range of platforms without code modifications.

To learn more about using Portable Class Libraries with Xamarin, read our Introduction to Portable Class Libraries document.


There are a couple limitations.  It’s based on .NET up to 4.5, with a smattering of .NET 5 features.  Well, anync, which is frankly the .NET 5 feature.  Perhaps the biggest limitation is it only has access to code from the Blueprint API.  Given that the Blueprint API has access to just about everything C++ does, this isn’t perhaps the limitation it sounds like.  If you want to make more C++ accessible to .NET you need to use CppSharp.  Additionally, Unreal AND Mono need to be available on the targeted platform, although frankly, Mono is available just about everywhere these days.  However, right now only Windows and Mac are supported, with other platforms under development.


Oh yeah, there is of course one other big side effect… money.


To redistribute code written with Mono for Unreal Engine, you must have a commercial license to the Mono runtime. These licenses are available from Xamarin for Mac, Android and iOS online, and you can request Windows licenses through support.


This of course is completely reasonable.  People make their money selling software, so obviously they have to sell their software.  That said, I’ve always found Xamarian’s licensing to be a bit awful.  There are almost unique in the development world for not offering a (real) free version for non-commercial development and this is a huge mistake IMHO.  The lack of a free edition makes open source software around their tools pretty much non-existent.  Of course you can open source work made with Xamarian tools, but good luck building a community around a commercial only development product.


That said, this is still an interesting development and one more feather in Unreal Engine’s cap.  Given that Unity is moving away from Mono and developing their own runtime, it’s not entirely shocking that Xamarin made this move.  It is somewhat ironic that the Unreal Engine .NET runtime will be substantially newer and more complete than Unity’s!

iPhone Development Tutorials and Programming Tips

Open Source Library For Creating Objective-C Playgrounds

by Johann at October 24, 2014 06:19 AM

Post Category    Featured iPhone Development Resources,iOS Development Libraries,Objective-C,Open Source iOS Libraries And Tools

The excellent playground feature in Xcode 6 provides a great way to create interactive programming examples, but unfortunately only works with Swift.

Here’s a library submitted by Krzysztof Zablocki providing an extensive feature set for creating Playgrounds in Objective-C called KZPlayground.

Some of the features of KZPlayground as stated in the readme include:

- Faster than Swift playgrounds (a lot)
– Extra controls for tweaking:
– Adjustable values
– Auto-animated values
– Buttons
– IDE agnostic, once you run it, you can modify the code even from vim.
– Full iOS simulator and access to all iOS features, so you can prototype production ready code.
– Nice DSL for rapid prototyping
– CocoaPods support, so you can add it to existing projects to experiment
– Open source, anyone can contribute to make them better!

An example project is included.

This video presentation from Krzysztof provides a great introduction to KZPlayground:

You can find KZPlayground on Github here.

A great library for making interactive programming examples.

Be the first to comment...

Related Posts:

FacebookTwitterDiggStumbleUponGoogle Plus

Original article: Open Source Library For Creating Objective-C Playgrounds

©2014 iOS App Dev Libraries, Controls, Tutorials, Examples and Tools. All Rights Reserved.

Geeks3D Forums

Rendering Fields of Grass using DX11 in GRID Autosport

October 23, 2014 07:01 PM

One thing we wanted to improve upon with GRID Autosport was our trackside environments, in particular the grass. The old system had served us well but it was time for an improvement so step up Rich Kettlewell, one of our programming wizards who...

iPhone Development Tutorials and Programming Tips

Open Source Component Providing A Fully Customizable Swift Based Stepper

by Johann at October 23, 2014 06:15 AM

Post Category    Featured iPhone Development Resources,iOS UI Controls,iPad,iPhone,Swift

The UIStepper component provides a very basic stepper with little room for customization.

Here’s an open source component submitted by Kyle Weiner called KWStepper providing a customizable stepper control with delegate functions that execute on value changes, and when min/max values are reached.

KWStepper allows you to set a label on the steppers, customize the step value for increments, and change events are triggered immediately..

Here are a couple of images from the readme showing KWStepper in action:


You can find KWStepper on Github here.

A nice custom stepper component.

Be the first to comment...

Related Posts:

FacebookTwitterDiggStumbleUponGoogle Plus

Original article: Open Source Component Providing A Fully Customizable Swift Based Stepper

©2014 iOS App Dev Libraries, Controls, Tutorials, Examples and Tools. All Rights Reserved.

Physics-Based Animation

SPGrid: A Sparse Paged Grid structure applied to adaptive smoke simulation

by christopherbatty at October 22, 2014 08:48 PM

Rajsekhar Setaluri, Mridul Aanjaneya, Sean Bauer, and Eftychios Sifakis

We introduce a new method for fluid simulation on high-resolution adaptive grids which rivals the throughput and parallelism potential of methods based on uniform grids. Our enabling contribution is SPGrid, a new data structure for compact storage and efficient stream processing of sparsely populated uniform Cartesian grids.SPGrid leverages the extensive hardware acceleration mechanisms inherent in the x86 Virtual Memory Management system to deliver sequential and stencil access bandwidth comparable to dense uniform grids. Second, we eschew tree-based adaptive data structures in favor of storing simulation variables in a pyramid of sparsely populated uniform grids, thus avoiding the cost of indirect memory access associated with pointer-based representations. We show how the costliest algorithmic kernels of fluid simulation can be implemented as a composition of two kernel types: (a) stencil operations on a single sparse uniform grid, and (b) structured data transfers between adjacent levels of resolution, even when modeling non-graded octrees. Finally, we demonstrate an adaptive multigridpreconditioned Conjugate Gradient solver that achieves resolutionindependent convergence rates while admitting a lightweight implementation with a modest memory footprint. Our method is complemented by a new interpolation scheme that reduces dissipative effects and simplifies dynamic grid adaptation. We demonstrate the efficacy of our method in end-to-end simulations of smoke flow.

SPGrid: A Sparse Paged Grid structure applied to adaptive smoke simulation

Game From Scratch

Adventures in Phaser with TypeScript–Loading and Using Tiled Maps

by at October 22, 2014 07:43 PM



In this tutorial we are going to look at loading and using Tiled TMX maps.  Tiled is a free, open sourced map editor, and TMX is the file format it outputs.  You basically use it to “paint” levels using one or more spritesheets containing tiles, which you then load and use in your game.


Here is Tiled in action, creating the simple map I am going to use in this example:



By the way, I downloaded the tile graphics from here.  Additionally, you can download the generated TMX file we will be using here.


I am not going to go into detail on using the Tiled editor.  I actually covered this earlier here.  For Phaser however, just be certain you export as either JSON or CSV format and you should be good to go.


Now let’s look at some code to load the tile map.



/// <reference path="phaser.d.ts"/>
class SimpleGame {
    game: Phaser.Game;
    map: Phaser.Tilemap;
    constructor() { = new Phaser.Game(640, 480, Phaser.AUTO, 'content', {
            create: this.create, preload:
            this.preload, render: this.render
    preload() {"ItsTheMap", "map.json", null, Phaser.Tilemap.TILED_JSON);"Tiles", "castle_0.png");
    render() {

    create() { ="ItsTheMap", 32, 32, 50, 20);"castle_0", "Tiles");"Background").resizeWorld();"Midground");"Foreground");
        =[0].widthInPixels / 2; = 0;{ x: 0 }, 3000).
to({ x:[0].widthInPixels }, 3000).loop().start(); } } window.onload = () => { var game = new SimpleGame(); };


And when you run it… assuming like me you are using Visual Studio 2013 you will probably see:



Hmmmm, that’s not good.  Is there something wrong with our tilemap?  Did we make a mistake?


Nope… welcome to the wonderful world of XHR requests.  This is a common problem you are going to encounter over and over again when dealing with loading assets from a web server.  If we jump into the debugger, we quickly get the root of the problem:




Let’s look closely at the return value in xhr.responseText:

Ohhh. it’s an IIS error message and the key line is:

The appropriate MIME map is not enabled for the Web site or application.



See, Visual Studio ships with an embedded version of IIS called IIS Express, and frankly, IIS Express doesn’t have a clue what a JSON file is.  Let’s solve that now.  If you created a new TypeScript project in Visual Studio, it should have created a web.config file for you.  If it didn’t create one and enter the following contents:

<?xml version="1.0" encoding="utf-8"?>
  For more information on how to configure your ASP.NET application, please visit
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
      <mimeMap fileExtension=".json" mimeType="application/json" />


Now the code should run without error

I should take a moment to point out that this is an entirely Visual Studio specific solution.  However, this particular problem is by no means limited to IIS Express.  I documented a very similar problem when dealing with WebStorm’s integrated Chrome plugin.  If your loadJson call fails, this is most likely the reason why!  Well that or you typo’ed it. :)


Ok, assuming everything is configured right,now we should see:


No Iframe for you!


By the way, you may have to click on the to get it to start rendering.


Most of the loading code should look pretty familiar by now, Phaser is remarkably consistent in its approach.  There are a few things to be aware of though from that code.  First, the order you create layers in is important.  In Tiled I created 3 layers of tiles.  A solid background layer named “background”, a middle layer with most of the tiles in it called “midground” then a detail layer for the topmost tiles named “foreground”.  Think of rendering tiles like putting stickers on a flat surface… the front most stickers will obscure the ones that are behind them.  The same is true for tiles.  There are other options in tiled for creating foreground and background layers, but I stuck with normal tile layers for ease.  Just no that more efficient options exist.


The next thing to be aware of is when I called addTilesetImage, that is the same image filename that I provided to Tiled.  It is important that you use the same graphics files and names between Tiled and your code.  The next thing worth noticing is the call to resizeWorld() I made when loading the first tiled layer.  This simply set’s the world’s dimensions to be the same size as the tile layer you specified.  Since all the tile layers are the same size, you could have called it on any of them.  Finally, we made a simple tween that pans the camera from one end of the level to the other and back.


There is more to touch on with tiles, but I will have to cover that in later post(s).


GameDev.Net Articles

Luck in Games: Why RNG isn't the answer

October 22, 2014 07:15 PM

The topic of luck in competitive gaming always ruffles a lot of feathers, leading to never-ending complaints and hostility from many different types of gamers: players whining about losses caused entirely by randomness, fans whining about their favourite pros being knocked out of tournaments due to bad luck, and everyone else whining about all the whiners. The subject arises frequently in discussions surrounding card games like Hearthstone, where the issue has become a hotly debated topic in the wake of serious complaints from professional players concerning the role of randomness in the game.

In developing Prismata—a competitive turn-based strategy game sharing many features with card games—we’ve questioned whether the presence of luck was really worth all the fuss, raging, and drama. Could a game like Hearthstone still be as popular and fun if the element of luck was removed?

Over the years, we’ve talked to many professional gamers and expert game designers, including folks from Hearthstone’s design team, about the role of luck in card games. When asked whether it would be possible to design a card game without luck, they all told us the same thing:

“Bad players will never think they can win, and they will stop playing.”

“Your game can’t thrive if it doesn’t have luck.”

“You'd be crazy to try and make it a commercial success.”

Challenge accepted. I guess we’re crazy.

Of course, it’s no secret that there are many benefits to having elements of luck in competitive games. Randomness can create exciting moments for players, alleviate balance issues, and provide losing players with an excuse to avoid feeling bad about their performance. As a design decision, it has become the de facto standard in card games, copied from one game to another throughout the industry. But are luck-based game mechanics the only method of achieving these goals?

After four years of struggling over this issue, the answer is finally clear: a resounding NO.

The Secret

What took us four years to understand is that luck-based game mechanics are not necessary to achieve excitement, balance, or consolement. All of these objectives are reachable through other means, without the player frustration or toxic community behaviour that inevitably arises in games featuring a high amount of randomness.

In a nutshell, we've concluded that it’s possible to design a compelling competitive game without luck. Possible. Not easy. Not necessarily doable in a manner consistent with the breakneck pace and intolerance of failure that characterizes much of AAA game development. But possible.

Chess, go, shogi, and checkers have been played for centuries and feature no randomness whatsoever. This means that masters of these games will crush you. Every. Time.

In some sense, this doesn’t sound too surprising. Most of the world’s most famous traditional competitive tabletop games—like chess and go—have fascinated people for centuries despite possessing no luck whatsoever. But it would be naive to assume that their success should translate to the modern-day gaming audience, with their short attention spans and insatiable addiction to novelty. Accordingly, throughout the four-year process of designing Prismata, we encountered many roadblocks in trying to meet our goal of having no randomness in the game whatsoever.

Before discussing those roadblocks, or even our reasons for wanting to avoid luck-based game mechanics in the first place, let’s take a look at different types of luck found in video games, and their effects in games like Hearthstone.

Forms of Luck in Gaming

Most types of uncertainty or variance in competitive gaming fall into one of the following four categories:

(1) Absolute Luck

Examples: coin flips, die rolls, waiting for the result after going all in pre-flop in poker.


In games with absolute luck, there comes a point where no amount of skill or knowledge can prevent you from losing. You’re at the mercy of the dice, the cards, or the random number generator (RNG) used in a video game. You have no way of reacting to what happens; you simply win, or lose.

Absolute luck is seldom a wise choice when designing video games, because it often leaves players feeling frustrated and helpless when they become unlucky.

(2) Execution Luck

Examples: basketball shooting, bowling, headshots in first-person shooters.


Execution luck refers to unavoidable variance in performance due to imperfect skill, such as basketball players who sink only 70-90% of free throws.

Execution luck can have huge effects on player psychology. Players feel bad when they lose 3 consecutive all-in bets in poker due to unlucky river cards. But they can feel much worse when they’re playing a competitive shooter and miss 3 consecutive headshots that they are usually able to make. Execution luck feels different from most other types of luck because players blame themselves when they exhibit short bursts of sub-average performance, even if those bursts are statistically inevitable due to random variations in human performance (a person who makes 80% of their shots will miss three in a row about 1% of the time). Players often question their own skill when this happens, leading to them feeling extremely demotivated (“Am I playing like crap today? Did I get worse at the game? Should I just quit?”). Worst of all, it’s statistically unavoidable. Players will inevitably feel demoralized at some point in all games where execution luck is a huge factor.

For these reasons, designers need to be very careful when incorporating game mechanics that result in heavy penalties for poor execution. It’s important that players are given ample opportunities to demonstrate their skills so that random variations in performance are “averaged out” over the course of a full match.

(3) Yomi Luck (i.e. “mind games”)

Examples: rock-paper-scissors, build order selection in real-time strategy games, move selection in fighting games or pokemon.


StarCraft has many rock-paper-scissors situations due to the fog of war. A greedy economic build may yield an advantage against an opponent playing a standard build, but may lose to a rush. However, a rush can fail to an opponent playing standard, leading to a disastrous economic disadvantage. Hence Greedy > Standard > Rush > Greedy. (Of course, this is an oversimplification.)

Yomi is the Japanese name given to the “mind-reading” skill that allows people to win at games like rock-paper-scissors, in which both players simultaneously select an action. Despite having no true randomness associated with them, these situations exhibit large amounts of variance; no player can win 100% of the time at rock-paper-scissors.

Yomi situations show up often in real-time strategy games. The correct units to build often depend on what the opponent chooses to get, and that information may not be available at all times due to the fog of war and inability to scout the opponent’s base. In fighting games, human reaction time itself creates a natural “fog of war”; you won’t have enough time to counter your opponent’s move if you wait until it animates on the screen; you must predict what your opponent will do in order to counter it.

Games rich in yomi often provide a multitude of options to players: safe plays, risky gambles, all-ins, hard counters, soft counters, and the ability to trade resources for information (for example, by scouting with a worker in StarCraft). The blending of play skill and yomi luck can create a complex web of interaction that rewards experienced players. Many yomi situations allow experts to crush new players by exploiting their natural tendencies or lack of understanding. However, in expert vs expert games where both players have a mastery of the rules and mechanics, yomi situations often devolve into purely arbitrary outcomes that depend highly on luck rather than skill. Nevertheless, this can have some benefits: players feel accomplished when they “outplay” their opponents, even if they simply got lucky.

(4) Soft RNG Luck

Examples: backgammon, most card games.


RNG stands for “random number generator”. In the context of gaming, RNG refers to any situation in which an outcome is random. Games like Hearthstone have RNG effects every turn when card drawing occurs, as well as randomized in-game effects (such as spells that deal random amounts of damage, or minions that automatically attack a random enemy). However, these RNG effects are soft in that players are given an opportunity to react to the different situations that occur. In theory, better players should be better at planning their turns around the randomness that occurs, so the increased amount of in-game luck should theoretically be counterbalanced by an increase in the skill ceiling of the game itself.

As we'll see, this theory can break down in practice.

How Luck can Fail

To see a key example of where the presence of RNG can have a strongly negative effect on some players’ enjoyment of the game, we'll examine Hearthstone.

As the Hearthstone metagame has become more fully explored, many strong players have become frustrated at the lack of opportunities for skill expression. Unlike in chess—where the best player in the world is a 91% favourite when playing a single match against the 100th-best player—in Hearthstone, the best player is often only a marginal favourite when playing any reasonably good player with a good deck. Gosugamers reports that popular player Tidesoftime, who is currently ranked 4th in the global ELO rating, has won only 63% of his matches. With that win rate, a player will lose a best-of-five series over a quarter of the time, meaning that most tournaments (televised ones in particular) don't have nearly enough games to have a high likelihood of rewarding the most skilled players.

Worst of all, unlike in poker—where a talented player will inevitably see a profit from playing millions of hands over the course of his or her career—skilled Hearthstone players have only a few opportunities each year to do well in a meaningful tournament, where winning requires an enormous amount of luck. Being good isn't enough.

Of course, many players insist (rightfully so) that this is how card games typically are—luck is a part of the game. But it's also abundantly clear that at least some fraction of players are very unhappy with the current state of the game.

This week, popular streamer Reynad announced he was taking a break from Hearthstone, complaining that the game, in its current state, doesn't reward skill enough. Kripparrian—another renowned gaming celebrity who streams Hearthstone regularly—posted a video of his own in the wake of Reynad's announcement, in which he stated the following:

Kripparrian: In Hearthstone, in constructed, at this time, it's pretty much just about draw RNG, and that really dictates who wins the matches.

Gaara, a teammate of Reynad, had similar concerns, which he made clear in a video. Gaara complains that Hearthstone has too many auto-win hands and situations where there is little decision making involved. If the opponent gets a good draw and you don’t, there’s often very little you can do.

For those familiar with Hearthstone, one picture says it all:


Against any reasonable opponent, your chances of winning here are likely less than two percent, even though the game has just barely begun.

In the scene above, which we shall refer to as the awful zoo hand, the player on the bottom has drawn too many high-cost cards. These cards don’t work well together, and none of them can be played during the first few turns of the game anyway. The player on top is in a much stronger position, and is virtually guaranteed victory. All the skillful decision-making in the world cannot save the player on the bottom from losing. These situations are not fun at all, and fairly common with the current set of decks that are most effective in Hearthstone.

Are We Better Off Without Luck?

Mark Rosewater, head designer of Magic: The Gathering, has written extensively about the different types of RNG effects found in card games, and their effects on player enjoyment. Though he stresses that most players of card games don’t enjoy too much randomness, he also emphasizes several key benefits of RNG: increased surprises and excitement, the ability for losing players to make comebacks, the ability for weaker players to win, and the increase in opportunities for strong players to demonstrate skill by accurately preparing for random events and reacting to them.

We’ll look at several of these points. In each case, the question we’re asking is “can the same effect be obtained without any luck?”


Mark lists a catch-up feature as the fourth entry on his list of ten things every game needs and describes how the random card draw system in Magic and other card games ensures that players who are behind can always draw a key card required to make a dramatic comeback.

However, I think Mark is missing the bigger picture here (he loves to say “every game needs X”, where X is a feature that Magic has.) Having talked to our players, we’ve learned that what they truly want is NOT comebacks. They simply want to avoid being dragged along for many turns in an unwinnable position. Comeback mechanics are one way of achieving this, but not the only way.

Let’s go back to our “awful zoo hand” from above. If you’re in this situation, you’re faced with an uncomfortable decision: do you play on, knowing that the chance of winning is likely under 2 percent? Or do you resign, saving yourself some time, but costing yourself a chance to win? Many players choose to play on, unable to resist the urge to eke out every last percentage point of possible winnings. But players who do so seldom have a good experience during the remainder of the game, often just sitting there cursing the RNG gods for dealing them such an awful hand.

Another common example can be found in League of Legends, where teams often play on for 20 minutes or more in situations where they have an extremely low probability of winning, but are forced to cling on in hopes that their opponents make enough mistakes for them to catch up:


The key insight is that lack of a comeback mechanic is NOT the problem. Indeed, these games both have comeback mechanics. The problem is that regardless of the strength of the comeback mechanics, there will always be situations where your chance of winning lies in the single digit percentages, and it shouldn’t take 20 minutes for your opponents to close out the game when they have such a monstrous advantage. Your opponent should be able to swiftly terminate you, and the game rules should be designed so that they are strongly incentivized to do so, rather than to play conservatively and torture you for another 20 minutes.

In many games, luck has the opposite effect of facilitating this. In games like League of Legends, fear of bad Execution Luck or Yomi Luck results in teams playing conservatively when they’re ahead, exacerbating the problem that comeback mechanics are meant to solve.


In a tabletop game like Magic: the Gathering, in which players must physically meet up to play and don’t have the luxury of choosing from hundreds of online opponents, players aren’t always able to find opponents of exactly equal skill. Consequently, it’s important that weaker players stand a chance against stronger ones so that weaker players don’t quit when they have no balanced opponents to play against and get crushed every game. Thus it makes a lot of sense for games like Magic to be balanced so that weaker players can get lucky and win against stronger players.

With modern online matchmaking and rating systems, any player of any game with a sufficiently large audience should be able to quickly find a match against an opponent that they can beat 50% of the time. There’s absolutely no reason to deliberately increase the role of luck in determining who wins.


Random events in card games can be very exciting and have produced some extremely memorable moments like Craig Jones’s famous topdeck of the century is filled to the brim with videos displaying amazing instances of RNG completely turning the tide of a game, or yielding funny or ironic results.

However, many of the most popular video clips are not acts of luck. They are acts of skill, like Reynad’s brilliant highmane sacrifice, which won him a key match in a Dreamhack tournament from earlier this year when all hope was lost.

You can find many other examples of truly amazing feats of skill in Hearthstone, often yielding clutch victories. Check out some of Amaz's crazy board clears and lethal combos if you haven’t seen them already. One thing is obvious: highly skilled plays are just as exciting, if not more exciting, than lucky plays.


Here, I won’t argue with Mark. It’s certainly true that much of the skill expressed in games like Magic: the Gathering is centered around preparing for, and reacting to, random events. Any Shaman player in Hearthstone will tell you the same thing. Playing well under situations where a lot of random events can occur requires a lot of planning, calculation, and ingenuity.

That said, there is no shortage of skill to be displayed in games that have no randomness at all. In games like chess or StarCraft, players can concretely understand every aspect of the game at incredible depth because of the ability to replay deterministic openings or build orders and study the situations that result. In games like Hearthstone, it’s much harder to argue that a person “made the optimal play”, because merely calculating the percent chance of winning is incredibly complicated in all but the simplest of positions. So randomness can make it harder to obtain satisfying answers to what the optimal move in a particular situation is.

Just Imagine…

Given our understanding of the benefits and drawbacks of luck in card games, let’s perform a thought experiment to see what it might be like if we tried to design a card game in which all of the luck was removed.

Imagine a game like Hearthstone or Magic: the Gathering where there was no draw phase at all; you simply drew your whole deck on the first turn, and could play any card from your deck as if it were in your hand. Let’s call this imaginary game:

DeckHand. In DeckHand, there are no mulligans, no bad draws, no RNG, and you can “live the dream” every game. You can always play a perfectly optimized (“on curve”) sequence of cards, and you always have access to whichever cards are necessary to deal with whatever your opponent is plotting.

DeckHand. Imagine having a 30-card hand on turn one. What would your dream opening be?

What would DeckHand be like?

If your answer is, “broken as hell”, you’re probably right, but let’s think a bit about how the metagame in DeckHand would play out, supposing that the cards were balanced around the new format, and appropriate steps were taken to ensure that the player going second wouldn’t be too disadvantaged (for example, by providing something similar to Hearthstone’s “coin” card).

We can already predict several problems with DeckHand. Many of them were also issues with Prismata during the early days of its development:

Problem 1: Openings

DeckHand players would quickly settle on a few optimal decks, and learn precise opening sequences for each deck. This would lead to an “opening book” like chess, where the best players memorize deep sequences of moves to play in the early stages of the game. Optimal play would depend heavily on huge amounts of study and memorization rather than game knowledge or strategizing. Many players would not find this to be fun.

Problem 2: Repetition

There would likely be a few popular decks in DeckHand, and players would quickly learn all of the basic matchups. Without randomness to naturally create variation in each game’s opening sequence of moves, each matchup would proceed quickly and predictably through the first few turns as players “played out the book”. A player of a specific deck in DeckHand might only really ever find themselves in 3 or 4 different situations over the course of all of the early turns in all of their games. This would cause games to get very repetitive. Not fun at all.

Problem 3: Balance

In most card games, if your opponent is playing a deck that “counters” your deck and is favoured to win, then despite being an underdog, you seldom have a probability of winning below 25%. Your opponent can always get unlucky with their draws, giving you the opportunity to win despite playing a disfavoured deck. In DeckHand, this would no longer be the case. Your opponent would have complete access to all of the cards that counter your strategy, and you could easily find yourself in situations where your odds of winning are effectively zero if your opponent plays correctly. Many games in DeckHand could simply be decided by which deck you get matched up against. The "automatch RNG" would simply take over as the dominant factor in determining the winner. Definitely not fun.

Solution Step 1: Use Randomized Decks

The problems listed above are inherent to the constructed metagame in any card game, but they are mitigated by random opening hands, which add variety to games, discourage deep memorization of openings, and help boost the win rate of underdog decks. Without random opening hands, we need another trick up our sleeves. The solution is simple: don’t randomize the opening hands, randomize the whole deck! Providing each player with a randomized, but balanced decklist would make each game of DeckHand fresh, with new strategies to uncover in every match. A game that does something similar to this is Dominion, in which players build decks over the course of the game using cards from a randomly generated pile.

Dominion—where the cards you use are different every game. However, unlike in DeckHand, you can still fall victim to bad draws. Better pray to RNGesus.

You might be thinking, “Wait, I thought we wanted to remove luck from the game; why are we adding random decks?” You’d have a point, but we’ll address that later.

Solution Step 2: Use the Same Deck for Both Players

Of course, randomized decks vary greatly in strength, meaning that many games of DeckHand would be unfair if one player’s randomly generated deck was stronger than the other. So for fairness, let’s give both players the same randomly generated deck. Unfortunately, this leads to a further problem: if every match features the same cards on both sides, won’t both players just play identical cards every game? DeckHand won’t be too interesting if every game is a mirror match, which can be common in games like Dominion when experienced players square off.

Solution Step 3: Build Diversity By Forcing Players to Make Tech Choices

The three technologies that can be purchased in Prismata. If you want to rush, go red.

This step is a bit harder to explain, but I’ll summarize what we did in Prismata. In Prismata, there are three different technologies that players can invest in. Each unit in the game has different technology requirements, so you can’t buy a unit whenever you want; you have to purchase the prerequisite technologies first. Upon seeing a player invest in a particular technology, the opponent will often react by investing in a different technology to have access to the units that counter those of the first player. This process continues as the two players jockey for position, making their tech investments in response to those of their opponent. This naturally promotes tech diversity, and hence mirror matches are uncommon. We could easily imagine doing something similar for DeckHand, though it might require a non-trivial revamp of the game's economy.

Let’s try DeckHand?

Of course, DeckHand was an imaginary game, and many changes to the cards and abilities would likely be necessary to ensure that everything worked well. We can’t say for sure that DeckHand would be a good game, but it should be conceivable that the key problems induced by removing card draw RNG can be overcome.

So What About Prismata?

Of course, the whole discussion about DeckHand is very much an analogy of some of the struggles we faced in designing Prismata. Prismata is essentially just DeckHand with modified combat rules, and an economy that feels a bit more like a turn-based version of what you’d find in a real-time strategy game. Prismata isn’t completely free of RNG, but the only randomness present lies in the random selection of units available for purchase in each game, and the selection of which player goes first. Once the game begins, there is absolutely no luck involved.

There is one last point that we didn’t address. As I mentioned at the very outset of this article, there was one serious doubt that was much harder to shake:

“Bad players will never think they can win, and they will stop playing.”

Back when Prismata was our pet project and we were still in school, we never intended for it to be a game for “bad players”. We were massively addicted to it and tried quite hard to play well! But before quitting school to work on Prismata full time, we needed to be absolutely sure that players inexperienced with strategy games wouldn’t have a bad time. We did several rounds of user testing, and what we discovered was quite astonishing.

Despite Prismata having no randomness, beginners who lost actually thought they were unlucky.

As it turned out, beginners had not formulated any concrete strategies when deciding which units to buy, and had just chosen some at random. If their units happened to be strong against whatever their opponent chose, they would win. If not, they would lose. And they didn’t blame themselves for losing, because they had just chosen randomly.

The best explanation that I have for this phenomenon is that it exemplifies a fifth type of luck in games:

(5) Outcome Uncertainty

Examples: strategy games, in which players choose a strategy without knowing whether it will work.

Outcome uncertainty is sometimes called opaqueness luck as it refers to situations in which the final outcome of a choice is not visible to players, even though it may be deterministic. A quick example would be a contest in which the goal is to guess the closest date to a chosen person's birthday. Such a contest involves no RNG in any sense, but to the participants, the results are essentially random. Opaqueness luck is not unique to beginners; in fact, much of the variance in performance among chess grandmasters can be attributed to it. Strong chess players may make a move thinking, "this is probably good for white", but they seldom know for sure.

As it turns out, opaqueness is the key source of luck in games like Prismata. With a near-infinite number of possible combinations of initial configurations, games of Prismata present limitless opportunities for players to be placed in unfamiliar situations. While still learning the game, beginners often buy the wrong thing and lose. Frequently, they develop a favourite unit as a result of getting lucky with it, and then continually purchase that unit whenever it's available, regardless of whether a unit countering it can be bought by their opponents. Confronted with a loss, they actually tend to blame the RNG for providing their opponent with a counter to their favourite unit.

In any case, I’m now wholeheartedly convinced that strategy game players will never change. Despite our best efforts to make a luck-free game, there will still be threads in which people claim that going second is OP, or whine that the randomly generated card sets are rigged, or complain that there are too many whiners. In the end, such discussions are a healthy part of most strategy game communities, as excuses help protect players' egos. However, we think players are good enough at coming up with excuses on their own, so we've come down firmly against the idea of adding more randomness for its own sake. Instead, our highest priority (on top of creating an enjoyable game) is to provide a quality matchmaking service guaranteeing that our players genuinely have a 50% chance of winning.

That should be enough to keep them happy.

Or so I hope.


Game Design Aspect of the Month

Critical Combat Systems in Competitive Gaming

by (Sande Chen) at October 22, 2014 01:43 PM

In this article, retired Dungeon Master Derrick B. Smith delves into the history of Critical Combat Systems and explains why such systems may not be the best choice for competitive games.

Computer game players are finding more games with Critical Combat Systems for entertainment. The inclusion of a random critical system in a non-competitive game can bring a level of excitement. The inclusion in any competitive gaming environment is a mistake. It turns a competitive game from being fair and balanced to one of random dumb luck. Imagine tossing a 6-sided die to decide how many points a touchdown was worth in an American Football game.

The starting point for Critical System being introduced to gaming dates back to the beginning of the RPG genre. Typically seen as “House Rules,” many groups adopted the concept. Dungeons & Dragons (D&D) and similar RPG games have simplified combat systems that lend themselves to the addition of a “Critical Strike”. Many groups would later go on to add a “Critical Fail” mechanic to their existing gameplay.

Photo taken by Davi Silva.

The D&D combat system used a 20-sided die (d20) roll for combat resolution. In its easiest form, any natural d20 roll of a 20 would allow for a “Critical Hit”. This allowed the attacker to double the damage the target suffers. There were many ways to resolve this double damage. Most groups’ double the full damage including any modifiers the player’s character was entitled to utilize. Other groups adopted a doubling of only the weapons base damage die than adding any modifiers unchanged. The main difference in the two systems was the maximum damage. The second reduced the potential significantly.

Other gaming systems added complex “Critical Strike” charts typically broken down into weapon groups and creature body type/armor. Though it allowed for more diversity in the results, they also slowed gameplay down. A talented Dungeon Master could story line the results without relying on any complex charts to add flavor to the game.

The Critical Fail system allowed for comical or tragic failures. The failure was rarely automatic and very dependent on the situation at the time of the failure. This shows why a true RPG requires a Human Game Master. Though computers are great for doing calculations and simplifying some tasks, they are not able to adapt to a changing story line based on game events and player decisions. The fumbling player would in many cases be required to make additional die rolls to reduce the negative result. An example would be to prevent breaking a weapon or hitting an ally or themselves.

As computer-based games developed, it was natural to see RPG-styled games created. A “Critical Strike” component added to non-competitive games can be more exciting than harmful. Within a Player vs Computer game, the effect of this random element does not add a noticeable negative aspect to the game. This is not true when you have games designed to be competitive or built with a Player vs Player (PVP) aspect. The random element that a “Critical Strike” adds could be compared to flipping a coin to determine who goes first in each round of a Chess Match. This random factor removes the development of tactical skills from many games. Players will still develop strategies for gameplay but there will be many who only try to score that Critical to win.

There are games designed to be competitive and the random luck “Critical Strikes” add diminishes the inherent skill component some games contain. Instead of an evolution of attacks and defenses strategies being developed, players migrate to getting lucky and falsely believe that luck is similar to true skills. Though a Critical Strike system brings uncertainty and a sense of suspense, the thrill does not last long and an enduring game fails to evolve.

Derrick B. Smith is a retired Dungeon Master. He started playing D&D and similar games before it was called 1st edition. He is still waiting for the first real RPG computer game to be developed. Also, Biker, Trucker, Gamer, Seamstress.

CUDA finance course Dec 2-5, 2014, New York

by dom at October 22, 2014 08:09 AM

Developed in partnership with NVIDIA, this hands-on four day course will teach you how to write and optimize applications that fully leverage the multi-core processing capabilities of the GPU. This course will have a finance focus. Commonly used algorithms such as random number generation and Monte Carlo simulations will be used and profiled in examples. A background in finance is not necessary. For more information please visit:

Cf4ocl Brings Object-Oriented API to OpenCL C API

by dom at October 22, 2014 08:07 AM

The Cf4ocl project is a GPLv3/LGPLv3 initiative to provide an object-oriented interface to the OpenCL C API with integrated profiling, promoting the rapid development of OpenCL host programs and avoiding boilerplate code. Its main goal is to allow developers to focus on OpenCL device code. After two alpha releases, the first beta is out, and can be tested on Linux, Windows and OS X. The framework is independent of the OpenCL platform version and vendor, and includes utilities to simplify the analysis of the OpenCL environment and of kernel requirements. While the project is making progress, it doesn’t yet offer OpenGL/DirectX interoperability, support for sub-devices, and doesn’t support pipes and SVM.

Cf4ocl can be downloaded from

iPhone Development Tutorials and Programming Tips

Open Source Component For Creating Great Looking Iconized Grid Menus Using iOS 8’s Blur Effects

by Johann at October 22, 2014 06:10 AM

Post Category    Featured iPhone Development Resources

Last month I mentioned a tutorial on using the new visual effect styles in iOS 8 including UIBlurEffectStyle and the BTSimpleSideMenu library for creating blurred slide-in side menus.

Here’s an open source component submitted by Carson Perrotti for creating customizable blurred Mailbox app inspired grid menus using iOS 8’s blur effects called CNPGridMenu.

CNPGridMenu allows you to easily specify icons, and titles for the individual menu selections, and you can also choose between different blur styles for the menu using UIBlurEffect.

Here’s an image from the readme showing CNPGridMenu in action:


You can find CNPGridMenu on Github here.

A great looking easily customizable component for creating iconized grids.

Be the first to comment...

Related Posts:

FacebookTwitterDiggStumbleUponGoogle Plus

Original article: Open Source Component For Creating Great Looking Iconized Grid Menus Using iOS 8’s Blur Effects

©2014 iOS App Dev Libraries, Controls, Tutorials, Examples and Tools. All Rights Reserved.

GameDev.Net Articles

300 Employees On Multiple Continents: How We Work Without An Office

October 21, 2014 09:50 AM

We decided to go office-less at the very start. For a small translation agency focused on working with IT companies via the Internet, this was a logical step. Now, ten years later, Alconost includes more than 300 people worldwide. Our staff is diverse: besides translators, we employ marketing specialists, contextual advertising experts, sales staff, editors, localization managers, and video production pros. But despite our growth, we still think that offices are inefficient and we feel good about the choice we made. As company co-founder, I, Kirill Kliushkin, would like to share about how we make the absence of an office work for us.

Not having an office has had a large and positive effect on our business. Our clients are located all over the world, so they often write to our managers outside of our local working hours. Because of this time difference, an ordinary, office-bound company would take days to communicate with distant clients and resolve issues. But not us. We do not hold our employees to a strict eight-hour regimen, instead asking them to answer messages quickly whenever they have the opportunity. Clients truly appreciate fast answers, even if it is just to say that “I will get the necessary information and write back to you tomorrow.” The client is happy, which means that we are happy too.

We have gone without offices not because we wanted to take a more relaxed pace. If anything, the answer is the opposite: often tasks need to be finished in minutes, not hours. Half of orders on our Nitro rapid online translation service are completed in less than two hours. We promise to reply to all client questions regarding Nitro within one hour. If we were stuck to a fixed office schedule, we could never attain the responsiveness that we have today.

Our formula: remote work + people + freedom - control

Our formula for success consists of remote work plus excellent people and an open schedule, minus overbearing control. Remote work is common enough these days – work wherever you want, as long as you get the job done. The same goes for the schedule too: we do not actually care when and how much you work. What counts is that tasks are resolved, processes launched, projects completed quickly, and the other employees not waiting because of any delays from you. Often I find it easiest to write articles or scripts at 2 or 3 AM, when the day’s problems are finally set aside and I can get more done in two hours than I have during all of the last week.

We do not ask our employees to fill out time sheets or, even worse, install tracking software on their computers to monitor time worked and get screenshots of what they are working on. Our approach is fundamentally different. Standing over an employee’s shoulder with a stopwatch and a calendar is counterproductive both for the employee and for the company. If a person is putting in the proper effort, we can see this by the tasks that get done and the satisfaction of colleagues and clients. If someone is lagging behind, we can see this too. We value the results, not the processes that led to these results. Business is what interests us, not control.

The next component of our formula is “excellent people”. Without them, nothing else works. But “excellent” is the key part. If someone just wants to sit in a desk chair for eight hours and does not care what they are working on, that person would not last long here. If work for someone is exclusively a way to earn money, that person would not fit us either.

How do I identify excellence? My way involves asking a lot of questions at the job interview – some of them personal, some of them uncomfortably so. By the end of the conversation, I have a high-resolution psychological portrait of the candidate. Looking back at all of my interviews with potential employees, I think that our conversations have usually allowed figuring out right away whether a person is the right one for us.

Mistakes can always happen, of course, and sometimes employees lose their motivation and start to drift. We battle for each employee: we try to figure out the reason for this change in attitude, inspire the employee to get back “into the groove”, and think of interesting work that could excite him or her. If we still lose the battle, we cut our losses and part ways.

Motivation vs. internal crisis

If we are on the topic of motivation, I should add a few words about the importance of motivation for employees at office-less companies. It is not a question of salary. When you are not sitting side by side with your boss, colleagues, or subordinates, it is easy to forget that you are part of a team. After working online for six months or so, an internal crisis sets in – you can forget that you work at a company and fall out of the corporate culture. Even Internet-centric companies like ours have a culture: in our case, one of care for the client, the desire to be a step ahead of the game, and the ability to answer questions that the client has not even thought of yet.

There is no one-size-fits-all technique for fighting off these teleworking blues. One effective method in our toolbox is to ask the employee to write an article for the media or to speak at a conference. While the employee is preparing the text or presentation, he or she dives into the topic and feels like part of something bigger. Another way is to simply meet and socialize informally, maybe drink a little whiskey. One way or another, managers need to think proactively about how to preserve motivation and help employees to feel socially needed, so that they do not suddenly snap one fine day and jump ship for a company with a plush office and after-work drinks on Fridays.

It is absolutely critical to be in contact with every employee and provide them with proper feedback. Don’t forget to praise a job well done, and don’t be afraid to say if a job could have been done better – but critique the work, not the person. The most important thing is to keep the lines of communication open and not be silent. I learned this the hard way, unfortunately. Last spring I traveled together with the other co-founder, Alexander Murauski, to Montenegro (another advantage of remote work, incidentally!) for three months with our families. All of the hassles of the temporary move distracted us from communication with employees. As a result, we lost a pair of workers who, if we had been “virtually” at their side, could have stayed, had we been able to help them in maintaining their motivation.


But leaving the country is not the only way of losing contact with employees. Simply concentrating too much on one aspect of the business can leave other employees feeling lonely and uncared for. Now I know how dangerous this can be.

Trello, Skype and The Cloud

Setting up workflows is much more important for an office-free company than it is for a company with employees housed in a giant cubicle farm. We realized this right away at the beginning of our company’s growth, when we needed to hire a second and later third project manager for handling client requests. We had to design processes and mechanisms to make telework just as efficient and seamless as working with a colleague at a neighboring desk.

Finding task management tools was a long effort. We tried Megaplan and Bitrix24, but later migrated to Trello, which is both very convenient and intuitive. Trello remains our project management tool of choice, although we continue to refine our processes. For localization of large projects, we often work with translators through a cloud-based platform. The rest of our communications go through email, Skype or Google Hangouts, which allow sharing screens in virtual group conferences.

All of our documents and files are stored on Google Drive. We forego Microsoft Office and other offline programs in favor of online documents only. The advantages are that documents are accessible from any device and the group collaboration/revision process is convenient.

We also have created an internal wiki to centralize and systematize our knowledge, rules, references, and procedures. Everything is in there, from step-by-step setup of Alconost email accounts to basic principles for working in Trello. Wiki articles are regularly added and updated, which helps new employees to get oriented quickly and makes work get done quicker.

Automating routine tasks and simplifying business processes is key. This saves work time, reduces headcount needs, and simply frees up resources for more creative tasks. A monotonous task that eats up five minutes every day will consume almost a week over the course of a year.

And of course, I recommend acquiring the tools you need so that you can work anytime, anywhere. With today’s devices and mobile Internet access, this is eminently doable. I remember when I spent an entire day writing video scripts, communicated with clients, and managed the company as I was waiting in line at a customs checkpoint. All I needed was my mobile phone and its five-inch screen!

Three tips for those working without an office

First: create a schedule. Wake up at the same time every day and figure out which times are most productive. People need rhythm.

Second, if you cannot work properly where you are, create the right setting so that you can. You simply cannot be productive in a two-room apartment with screaming kids and hyperactive pets. You need your own clearly marked, private space. For me, this is the study in my apartment. For Alexander, the other Alconost co-founder, the solution to two noisy children is a small room at a nearby business center.

And third: when there is no set schedule, your working day imperceptibly begins to “morph”. You do not have the clear division between personal time and working time that an office gives. Some people become fatigued by this, which is a sign that remote work is probably not right for them. When you like your work – if it is something that you are passionate about – it does not matter which of the day’s 24 hours you choose to spend doing it. Personally, I don’t even like the word “work”. I don’t “work”, I live and simultaneously pursue my business. It makes me happier – and lets me truly live.

iPhone Development Tutorials and Programming Tips

Open Source iOS Library Allowing You To Easily Slide Views Automatically Away From The Keyboard

by Johann at October 21, 2014 06:18 AM

Post Category    Featured iPhone Development Resources,iOS Development Libraries,Objective-C,Open Source iOS Libraries And Tools

Here’s a library called IHKeyboardAvoiding that works differently from previously mentioned libraries allowing you to automatically slide any view out of the way of the keyboard (not just text fields) submitted by Fraser Scott.

I mentioned a few libraries for solving the issue of text fields being covered by the keyboard, most recently IQKeyboardManager that provides an approach not requiring any code.

IHKeyboardAvoiding allows you to register a target view and when that keyboard intersects with the bottom of the target view it slides the view (and views contained within) upwards out-of-the-way of the view.  This view can be any view, and use of a UIScrollView is not required.  The library works with all orientations, auto layout and different keyboard setups (dock, undocked, normal, split).

Here’s an animation showing IHKeyboardAvoiding in action – notice the button and text fields sliding out-of-the-way:


You can find IHKeyboardAvoiding on Github here.

A nice library for solving the issue of views being covered by the keyboard.

Be the first to comment...

Related Posts:

FacebookTwitterDiggStumbleUponGoogle Plus

Original article: Open Source iOS Library Allowing You To Easily Slide Views Automatically Away From The Keyboard

©2014 iOS App Dev Libraries, Controls, Tutorials, Examples and Tools. All Rights Reserved.


PHP Mad Notebook

by Mike K at October 21, 2014 05:51 AM

This isn’t a blog. It’s a notebook.

APCu Functions

Arguments in []’s are optional. Cross reference with APC docs. PECL Page. Github.

function apcu_cache_info([$type [, $limited]]);
function apcu_clear_cache([$cache]);
function apcu_sma_info([$limited]);
function apcu_key_info($key);
function apcu_enabled();
function apcu_store($key, $var [, $ttl]);
function apcu_fetch($key [, &$success]);
function apcu_delete($keys);
function apcu_add($key, $var [, $ttl]);
function apcu_inc($key [, $step [, &$success]]);
function apcu_dec($key [, $step [, &$success]]);
function apcu_cas($key, $old, $new);
function apcu_exists($keys);
function apcu_bin_dump([$user_vars]);
function apcu_bin_load($data [, $flags]);
function apcu_bin_dumpfile($user_vars, $filename [, $flags [, $context]]);
function apcu_bin_loadfile($filename [, $context [, $flags]]);

Iterator functions are omitted, but also available.

The above is a cleaned up version of what’s output by "php --re apcu".

Perl-like ?: Operator

$a = TRUE ?: FALSE;       // true
$b = FALSE ?: TRUE;       // true
$c = NULL ?: "DeathRope"; // "DeathRope"

From Tips.

Data Format: Raw PHP variables (var_export)

To serialize something to disk in the fastest way PHP can read it, you make it source code by calling var_export. Whenever the file changes, it should cause a cache miss with OPcache.

mixed var_export ( mixed $expression [, bool $return = false ] );

$php_array = Array( 2,5,6,14 );
$export = var_export($php_array, true); // true = return the value (else echo)
file_put_contents('export.php', '<?php $php_array = ' . $export . '; ?>');

To use it:

include 'export.php';

Alternatively, if you store it a different way:

eval( $php_array );

But this will cause OPcache to miss every time.

Data Format: JSON (decode, encode)

Apparently this is the fastest encoder, as of PHP 5.3. Benchmarks.

mixed json_decode ( string $json [, bool $assoc = false 
    [, int $depth = 512 [, int $options = 0 ]]] );

string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] );

int json_last_error ( void );

$json_in = '{ "money":200, "love":false }'; // json uses "", not ''
$array_out = json_decode( $json_in, true ); // true = output an array (else object)
$json_out = json_encode( $array_out );

var_dump( $array_out );
// array(2) { ["money"]=> int(200) ["love"]=> bool(false) }
var_dump( $json_out );
// string(26) "{"money":200,"love":false}"

json_decode, json_encode, json_last_error

Data Format: Serialize, Unserialize

A faster decoder (slower encoder), and types/classes persist.

string serialize ( mixed $value );
mixed unserialize ( string $str );

$data = Array( 'fox'=>true, 'zippy'=>13 );
$out = serialize( $data );
$new_data = unserialize( $out );

var_dump( $out );
// string(37) "a:2:{s:3:"fox";b:1;s:5:"zippy";i:13;}"
var_dump( $new_data );
// array(2) { ["fox"]=> bool(true) ["zippy"]=> int(13) }

serialize, unserialize

Data Format: IGbinary

An alternative, external binary encoder/decoder. According to benchmarks, the fastest. (PECL)

// Drop in replacement for serialize/unserialize //
string igbinary_serialize ( mixed $value );
mixed igbinary_unserialize ( string $str );

$data = Array( 'fox'=>true, 'zippy'=>13 );
$out = igbinary_serialize( $data );
$new_data = igbinary_unserialize( $out );

// TODO: VarDump

Smaller too.

Tips and Tricks:

Data Format: CSV

Reading Only.

array str_getcsv ( string $input [, string $delimiter = "," 
    [, string $enclosure = '"' [, string $escape = "\\" ]]] )

$arr = str_getcsv($data);

// TODO: output

Data Format: XML

Reading Only (there is writing, but it seems more difficult).

SimpleXMLElement simplexml_load_file ( string $filename 
    [, string $class_name = "SimpleXMLElement" 
    [, int $options = 0 [, string $ns = "" 
    [, bool $is_prefix = false ]]]] )

SimpleXMLElement simplexml_load_string ( string $data 
    [, string $class_name = "SimpleXMLElement" 
    [, int $options = 0 [, string $ns = "" 
    [, bool $is_prefix = false ]]]] )

$string = "<thing>It Happened</thing>";
$xml = simplexml_load_string( $string );

// TODO: Output

If you prefer Array format (like me), here’s a function.

function __xml2array($xml) {
	$arr = array();

	foreach ($xml->children() as $r) {
		$t = array();

		if (count($r->children()) == 0) {
			$arr[$r->getName()] = strval($r);
		else {
			$arr[$r->getName()][] = __xml2array($r);
	return $arr;

Then simply

$string = "<thing>It Happened</thing>";
$xml = simplexml_load_string( $string );
$array = __xml2array($xml);

Data Format: HTML

Use Simple HTML DOM parser. (Manual)

// $html = file_get_html('');
// $html = str_get_html('<div id="hello">Hello</div><div id="world">World</div>');

$text = '<html><body><div id="me" class="president">cant touch this</div></body></html>';
$html = str_get_html( $text );

// TODO: Output

Data Format: String Delimiter

array explode ( string $delimiter , string $string [, int $limit ] );
string implode ( string $glue , array $pieces )

$in_data = "Frank|Donald|Scott|Wrenchy";
$out = explode("|",$in_data);
$csv = implode(",",$out);

var_dump( $out );
// array(4) { 
//  [0]=> string(5) "Frank" 
//  [1]=> string(6) "Donald" 
//  [2]=> string(5) "Scott" 
//  [3]=> string(7) "Wrenchy"
// } 
var_dump( $csv );
// string(26) "Frank,Donald,Scott,Wrenchy"

explode, implode


$myvar = "hello";
unset( $myvar ); // Deleted. See documentation for notes on Globals and references

val and type juggling

echo boolval(2);                 // true
echo intval("14") + 1;           // 15
echo floatval("12.5") * 2;       // 25 (NOTE: doubleval is an alias for floatval)
echo strval(true);               // "true"
echo settype("5bars","integer"); // 5 (explicit casting)
echo (boolean)10;                // true (typecasting)