Sync Random Number Generators On Two Machines - cocoa-touch

Is it possible to "synchronize" (for lack of a better word) random number generators on two different machines?
Context: I have a card game for iOS with network multiplayer. Both peers need to be able to access the card deck. When the deck gets shuffled, I can serialize my card deck object with NSCoding and ship it over to the other peer so the decks are in sync, but I could send less data if I could just count on the random number generators on both peers to generate the same random numbers.
Because this is a card game, I need the best random numbers available, so I prefer to use arc4random(), which seeds itself when first called. Is there, perhaps, a way to seed it manually?
Simply sending the card deck object is an okay solution, but I plan to implement asynchronous multiplayer using OpenFeint, and to do that, my game states need to stay under 16K, and just my card deck is almost 2K when serialized. :)
Thanks!

What if you just sent over the random number itself? Whichever device's "turn" it is can have the task of creating and sending it's random number so that all the versions can acknowledge the same draw. If you're careful to make sure that all the versions of the deck are in the same order/cards and that no random number is dropped, it should theoretically work with a very small amount of data transfer. If another player comes in part way through, you can mark which cards have been drawn by flipping individual bits in an object or array of objects and send that object/array.
Failing that I'm afraid I don't know the platform, but I do know that in some other languages, putting a seed as part of the call will seed it with a fixed value (ie: arc4random(seed)) I don't know if this is the case on what you're working on, but it's probably worth looking into.
Hope this helps!

Related

Create winnable "random" solitaire shuffles

I've created a solitaire game for Mac, but people keep complaining that there's not enough "winning" shuffles. People have a win-rate of about 5%-10%, where their usual win-rate is around 50%.
Right now, I'm creating an array with all the cards in the deck and after that I shuffle that array, using the F/Y method.
So my question is... is there any way that I can "check" for a winning solitaire shuffle, so I can bump up the numbers of winning solitaire shuffles I'm dealing to people?
Do you have a backend part of your app? if so then you can store all success (win) shuffled arrays on the server from all the users and increase the win-rate by sending them successes from other users with some frequency.
I read that for some sort of these games, there is no more efficient way than to do brute force checking of all possible moves.
My suggestion for situations like this is to start from the completed state (end of game), and move backwards randomly to create a random start state.
I run site with thousands of solitaire games played a day. We tried to built an AI that would allow us to understand what hands were winnable or not. It turns out, like many of the responses, that there are so many permutations to win or lose a solitaire game that an AI to detect a winnable or non-winnable game is extremely difficult to build and requires significant processing power. We weren't able to succeed in building it.
Now, we simply leverage our user data to find which games are winnable, and offer that as option for players who want to play winnable only games. Otherwise, they can choose a random game. I would recommend trying something similar!

Can this online highscore scheme be abused?

Background
One problem with games using online highscore lists is that they often can be abused. The game sends the current score to the server and a cunning user can analyze the protocol/scheme and send bogus scores. That is why some highscore lists are topped with 999999 scores.
A common solution to this problem is to encrypt the score in some way, and on top of that put other mechanisms to recognize false scores. But even if you do this, it's the client that sends the score and the client is living in the user's computer and can be reverse-engineered.
My idea
I am designing/thinking about a game (that I will complete, yeah right :) ) where you configure your player/robot with instructions on how to perform a task (and when these instructions are to be carried out). When a "Go" button is pressed the game runs the instructions. Finally a result and, if successful, a score, is obtained.
So, how about this: Instead of submitting the score, the actual instructions are sent to the server, where they are run, using the same implementation. Then the server calculates the score and places the user on the highscore list.
The question
Are there ways this idea can be abused to get a false score?
I understand that this probably is not a new idea. But if it works, it wouldn't be impossible to extend it to other games too, where it is possible to record all user actions.
People will always find a way to cheat, but this seems like a reasonable counter measure. You'll have to consider your intended traffic levels as your scheme will require more resources than if it was just recording the high score sent by the client.
But, as an aside - this game sounds an awful lot like my job (giving instructions to a machine so it performs some task). No high-score board though (although, that would be awesome).
as long as the robot program's behavior doesn't depend on the speed of the computer it'll be fine and if the programs are quite small at most a few kilobytes this would work fine; the only way i can see to cheat it is if one cloned the work space and ran a program to find the optimal program for the robot and then put it in and submitted it or if some one posted the solutions, and people used that but both of those issues can be solved with randomization.
(a note about the issue of speed dependent games, it's fine for the game to uniformly slow down if the computer can't run it at full speed but if the physics time step depends on the frame rate, you can get problems like the jump height varying with the frame rate)

In OOP, if objects send each other messages, won't there be easily an infinite loop happening?

In an Apple paper about Object Oriented Programming, it depicts objects sending messages to each other. So Appliance can send a message to Valve, saying requesting for water, and the Valve object can then send a message to the Appliance, for "giving the water".
(to send a message is actually calling the method of the other object)
So I wonder, won't this cause subtle infinite loop in some way that even the programmer did not anticipate? For example, one is if we program two objects, each one of them pulling each other by gravity, so one is sending to the other object, that there is a "pull" force, and the other object's method got called, and in turn sends a message to the first object, and they will go into an infinite loop. So if the computer program only has 1 process or 1 thread, it will simply go into an infinite loop, and never run anything else in that program (even if the two object finally collide together, they still continue to pull each other). How does this programming paradigm work in reality to prevent this?
Update: this is the Apple paper: http://developer.apple.com/library/mac/documentation/cocoa/conceptual/OOP_ObjC/OOP_ObjC.pdf
Update: for all the people who just look at this obvious example and say "You are wrong! Programs should be finite, blah blah blah", well, what I am aiming at is, what if there are hundreds or thousands of objects, and they send each other messages, and when getting a message, they might in turn send other messages to other objects. Then, how can you be sure there can't be infinite loop and the program cannot go any further.
On the other hand, for people who said, "a program must be finite", well, what about a simple GUI program? It has the event loop, and it is an infinite loop, running UNTIL the user explicitly asks the program to stop. And what about a program that keep on looking for prime numbers? It can keep looking (with BigNum such as in Ruby so that there can be any number of digits for an integer), so the program is just written to keep on running, and write the next larger prime number into the hard disk (or write to hard disk once every million time it find greater prime number -- so it find 1 million prime number and write that 1 millionth to the hard drive and then keep on looking for the next million prime numbers and write the 2 millionth number to hard drive (write only 1 number, not 1 million of them). Well, for a computer with 12GB or RAM and 2TB of hard drive, maybe you can say it can take 20 years for the program to exceed the capability of the computer, when hard disk is full or when the 12GB of RAM cannot fit all the variables (it might be billion of years that an integer cannot fit in 1GB of RAM), but as far as the program is concerned, it just keep running, unless the memory manager cannot allocate another BigNum, or the hard drive is full, that the exception is raised and the program is forced to stop, but the program is written to run indefinitely. So not all programs HAS TO BE written to be finite.
Why should Appliance request for water repeatedly?
Why should Valve bombard Appliance saying that water is being provided?
In theory - it's likely to create infinite loop, but in practice - it comes down to proper modeling of Your objects.
Appliance should send ICanHasWater message only once, wait for response, receive water or receive an answer that water cannot be provided, or will be in future when Applicance might want to try requesting water once again.
that's why I went into the 2 objects and gravity example instead.
Infinite loop of calculation of gravity effects between objects would happen only if You would trigger this calculation on calculation.
I think that common approach is to introduce Time concept and calculate gravitation for particular TimeFrame and then move on to next one for next round of calculation. That way - Your World would have control over thread between TimeFrames and Your application might do something more useful than endless calculations of gravity effects.
Without OOP it is as easy to create infinite loops unintentionally, using imperative programming languages or functional programming maybe. Thus I cannot see what is special about OOP in this case.
If you think of your objects as actors sending each other messages, it's not necessarily wrong to go into an infinite loop. GUI toolkits work this way. Dependend on the programming language used this is made obvious by a call to toolKit.mainLoop()or the like.
I think that even your example of modelling gravity by objects pulling at each other is not wrong per se. You have to ensure that something is happening as a result to the message (i.e. the object being accelerated and moving a little) and you will get a rough discretization of the underlying formulae. You want to check for collision nevertheless to make your model more complete :-)
Using this model requires some level of concurrency in your program to ensure that messages are processed in proper order.
In real life implementations there's no infinite loop, there's infinite indirect recursion instead - A() calls B(), B() calls C() and on some branch C() calls A() again. In your example if Appliance sends GetWater, Valve sends HeresYourWaterSir inmmediately and Appliance's handler of HeresYouWaterSir for whatever reason sends GetWater again - infinite indirect recursion will begin.
So yes, you're right, in some cases problems can happen. The OOP paradigm itself doesn't protect against that - it's up to the developer.

Implementation of achievement systems in modern, complex games

Many games that are created these days come with their own achievement system that rewards players/users for accomplishing certain tasks. The badges system here on stackoverflow is exactly the same.
There are some problems though for which I couldn't figure out good solutions.
Achievement systems have to watch out for certain events all the time, think of a game that offers 20 to 30 achievements for e.g.: combat. The server would have to check for these events (e.g.: the player avoided x attacks of the opponent in this battle or the player walked x miles) all time.
How can a server handle this large amount of operations without slowing down and maybe even crashing?
Achievement systems usually need data that is only used in the core engine of the game and wouldn't be needed out of there anyway if there weren't those nasty achievements (think of e.g.: how often the player jumped during each fight, you don't want to store all this information in a database.). What I mean is that in some cases the only way of adding an achievement would be adding the code that checks for its current state to the game core, and thats usually a very bad idea.
How do achievement systems interact with the core of the game that holds the later unnecessary information? (see examples above)
How are they separated from the core of the game?
My examples may seem "harmless" but think of the 1000+ achievements currently available in World of Warcraft and the many, many players online at the same time, for example.
Achievement systems are really just a form of logging. For a system like this, publish/subscribe is a good approach. In this case, players publish information about themselves, and interested software components (that handle individual achievements) can subscribe. This allows you to watch public values with specialised logging code, without affecting any core game logic.
Take your 'player walked x miles' example. I would implement the distance walked as a field in the player object, since this is a simple value to increment and does not require increasing space over time. An achievement that rewards players that walk 10 miles is then a subscriber of that field. If there were many players then it would make sense to aggregate this value with one or more intermediate broker levels. For example, if 1 million players exist in the game, then you might aggregate the values with 1000 brokers, each responsible for tracking 1000 individual players. The achievement then subscribes to these brokers, rather than to all the players directly. Of course, the optimal hierarchy and number of subscribers is implementation-specific.
In the case of your fight example, players could publish details of their last fight in exactly the same way. An achievement that monitors jumping in fights would subscribe to this info, and check the number of jumps. Since no historical state is required, this does not grow with time either. Again, no core code need be modified; you only need to be able to access some values.
Note also that most rewards do not need to be instantaneous. This allows you some leeway in managing your traffic. In the previous example, you might not update the broker's published distance travelled until a player has walked a total of one more mile, or a day has passed since last update (incrementing internally until then). This is really just a form of caching; the exact parameters will depend on your problem.
You can even do this if you don't have access to source, for example in videogame emulators. A simple memory-scan tool can be written to find the displayed score for example. Once you have that your achievement system is as easy as polling that memory location every frame and seeing if their current "score" or whatever is higher than their highest score. The cool thing about videogame emulators is that memory locations are deterministic (no operating system).
There are two ways this is done in normal games.
Offline games: nothing as complex as pub/sub - that's massive overkill. Instead you just use a big map / dictionary, and log named "events". Then every X frames, or Y seconds (or, usually: "every time something dies, and 1x at end of level"), you iterate across achievements and do a quick check. When the designers want a new event logged, it's trivial for a programmer to add a line of code to record it.
NB: pub/sub is a poor fit for this IME because the designers never want "when player.distance = 50". What they actually want is "when player's distance as perceived by someone watching the screen seems to have travelled past the first village, or at least 4 screen widths to the right" -- i.e. far more vague and abstract than a simple counter.
In practice, that means that the logic goes at the point where the change happens (before the event is even published), which is a poor way to use pub/sub. There are some game engines that make it easier to do a "logic goes at the point of receipt" (the "sub" part), but they're not the majority, IME.
Online games: almost identical, except you store "counters" (int that goes up), and usually also: "deltas" (circular buffers of what's-happened frame to frame), and: "events" (complex things that happened in game that can be hard-coded into a single ID plus a fixed-size array of parameters). These are then exposed via e.g SNMP for other servers to collect at low CPU cost and asynchronously
i.e. almost the same as 1 above, except that you're careful to do two things:
Fixed-size memory usage; and if the "reading" servers go offline for a while, achievements won in that time will need to be re-won (although you usually can have a customer support person manually go through the main system logs and work out that the achievement "probably" was won, and manually award it)
Very low overhead; SNMP is a good standard for this, and most teams I know end up using it
If your game architecture is Event-driven, then you can implement achievements system using finite-state machines.

Representing the board in a boardgame

I'm trying to write a nice representation of a boardgame's board and the movement of players around it. The board is a grid of tiles, players can move up, down, left or right. Several sets of contiguous tiles are grouped together into named regions. There are walls which block movement between some tiles.
That's basically it. I think I know where to start if all the players were human controlled, but I'm struggling with what happens with a computer controlled player. I want the player to be able to say to itself: "I'm on square x, I want to go to region R a lot, and I want to go to region S a little. I have 6 moves available, therefore I should do..."
I'm at a loss where to begin. Any ideas? This would be in a modern OO language.
EDIT: I'm not concerned (yet) with the graphical representation of the board, it's more about the route-finding part.
I'd say use a tree structure representing each possible move.
You can use a Minimax-type algorithm to figure out what move the computer should take.
If the problem is with pathfinding, there are quite a few pathfinding algorithms out there.
The Wikipedia article on Pathfinding has a list of pathfinding algorithms. One of the common ones used in games is the A* search algorithm, which can do a good job. A* can account for costs of passing over different types of areas (such as impenetrable walls, tiles which take longer to travel on, etc.)
In many cases, a board can be represented by a 2-dimensional array, where each element represents a type of tile. However, the requirement for regions may make it a little more interesting to try to solve.
Have a Player class, which has Map field associating Squares to probability of moving there, that is, Map<Square, Double> if you'll represent them as a 0..1 double.
Have a Board class encapsulating a series of Squares. Each Square will have four booleans or similar to mark where it has a wall, its coordinates, and which Player, if any, is on it.
I can tell you what worked for me on a commercial board game style product.
Break your representation of the board and core game logic into it's own module, with well defined interfaces to the rest of the game. We had functions like bool IsValidMove(origin, dest), and bool PerformMove(origin, dest), along with interfaces back to the GUI such as AnimateMove(gamePieceID, origin, dest, animInfo).
The board and rules only knew the state of the board, and what was valid to do. It didn't know anything about rendering, AI, animations, sound, input, or anything else. Each frame, we would handle input from the user at the GUI level, send commands to the board/game state code, and then be done. The game state code would get commands, resolve if they were valid or not, update the game state and board, then send messages back to the GUI to visually represent the new state of teh board. These updates were queued by the visual representation system, so we could batch a bunch of animations to happen in sequence.
The good thing about this is that the board doesn't know or care about human vs. AI players. Your AI can be a separate submodule that acts on it's turn. It can send the same commands as the human player, and the game logic and visual results will be the same. You'll need to either have a local per-AI bit of info about the game board state, or expose some BoardSnapshot() functionality from the game logic that lets the AI "see" the board, but that's it. Alternately, you could register each AI as an Observer Pattern on the game state, so they get notified when the board updates as well, in case they need to do any complex realtime planning.
Keeping each section of your game separate and isolated will help with unit testing, and provide a more robust system. Well defined interfaces are your friend.
If you are looking for in-memory representation of the games (and it's state), a matrix is the simplest. However, depending on the complexity of the board, the strategy, you may have to maintain a list of states.
If you mean on-screen representation, you'd need some graphics library to begin with.