Recent posts by Salman on Kongregate

Flag Post

Topic: Game Programming / What do you think of this?

Let’s assume you want the game to be playable at fullscreen. I use my 1080p (1920×1080) tv as my monitor, so that uses the standard 16:9 aspect ratio. If the maximum width is 700, then with 16:9 the height should be around 393. A wide-screen monitor is 16:10 (e.g, 1920×1200). So for a widescreen monitor height should be around 437.
I’d make the height 393 for a width of 700, but that’s me.

Btw, THANK YOU, for asking that question. I had no idea the limit was 700. Good to know!

 
Flag Post

Topic: Game Programming / Solid Objects

Ok, here is a simple way. Suppose the user presses the left key, and your character will move left, but the house is there and so you don’t want him to move left. So your your keydown method for the left key (or up and right etc), store the characters current x,y coordinate in some temporary variable. Make the move (e.g, x = x – MOVEMENT or whatever you do), then do a hitTest between the house and your character. If there is a hit, then set your x and y coordinates back to the old values you had saved in the temporary variables, otherwise, keep them as they are.

 
Flag Post

Topic: Game Programming / Multiple Key Press

This is a problem with your keyboard, and not Flash. Many keyboards nowadays have this hardware limitation. Try this in other applications and you should see similar behavior. I am trying right now in this text box I am typing in, and if I hold down the right key, then the left key, then press down up, the cursor doesn’t go up, but if I only do left and then up, it goes up.

 
Flag Post

Topic: Game Programming / My first racing game

Hi KMAE,

Thats awesome! Well it turns out, I’m starting a series of articles on making a multiplayer car game. Please check out my blog at http://actionscriptdeveloper.blogspot.com/. This particular topic will be covered in my blog one day, but for now, I will answer your question here:



Create a Camera class, that takes in its constructor 2 DisplayObjects. Call the first one ‘reference’ and the second one ‘trackThis’. The idea is that you want to attach a camera to some display object (trackThis), and you want it to be the center of some other display object (reference). So, you’d pass the Track DisplayObject as the reference, and the Car DisplayObject as the thing you want to track. On the track, set its ScrollRect property to be the width and height of the stage, and if you use the Model-View-Controller architecture, then you can easily have multiple ‘views’ of the track, each with a different ScrollRect, allowing features such as split screen. Anyhow, in every frame, just invoke the following method in the Camera class:

public function doStuff() :void
{
var x :Number = trackThis.x;
var y :Number = trackThis.y;

var width :Number = reference.scrollRect.width;
var height :Number = reference.scrollRect.height;

var rect :Rectangle = reference.scrollRect.clone();
rect.x = Math.min(reference.width – width, Math.max(trackThis.x – width/2, 0));
rect.y = Math.min(reference.height – height, Math.max(trackThis.y – height/2, 0));
reference.scrollRect = rect;
}


Enjoy! More detail will be covered by my blog. Stay tuned…

 
Flag Post

Topic: Game Programming / Question involving Classes (AS3)

All 3 patterns I mentioned are from the bible of Software Engineering, called the Gang of Four, also known as “Design Patterns: Elements of Reusable Object-Oriented Software”, (http://en.wikipedia.org/wiki/Design_Patterns). They may seem crappy to you right now, but as you gain experience and exposure, you will begin to realize the value of such design patterns. Design patterns are actually really really cool to do, and now with AS3 many of them become possible, so I encourage everyone to try them out as it will significantly enhance your ability to design your games well.

You may not appreciate UML yet, but it IS the industry standard now and has been fully adopted by almost all the major software firms and institute in the world. Knowing just basic UML Class Diagrams is a very handy tool for everyone, and I would again encourage developers of this community to take a crack at designing your next game with UML before you start.

I know it seems like that is “not what’s really happening under the hood”, but in reality it is. It is extremely complicated and impractical to not do it that way under the hood. As I said, the only language I know of that does not do it that way is Eiffel; all others, AS3, .NET, Java, C++ all conform to the rules of ‘specialization’ under the hood.

 
Flag Post

Topic: Game Programming / Question involving Classes (AS3)

Hi Phantasmagoria,

Dazzer is actually correct (you are too but he is correcter than you ;). There is well-founded OO wisdom that states that avoiding code-duplication is not the purpose of Inheritance. If this is indeed the reason you choose to do Inheritance, then you could easily be potentially missing out on several other cool ways of avoiding code-duplication. This other route is “by association” instead of “by specialization” (specialization is the UML term for inheriting some other class). Try googling the State, Strategy or Bridge design patterns for some examples of cooler things you can do to solve your problem (I’ve never heard of Mixin before, but you could look into that too). This is not to say that you are wrong at all; you are still correct in saying that avoiding code-duplication is great, and the wisdom is JUST guidance, not some hard and fast OOP rule. In any case, since you asked, let me tell you what the UML community specifies the relationship between the ‘parent’ (superclass) and ‘child’ class (subclass) really is:

Firstly, if Class B inherits Class A, then the UML way to say this is “Class B specializes Class A”, or “Class A generalizes Class B”. I really like these terms more than inheritance, because this tells you exactly what their relationship is, though can be quite confusing to some people. To put it more plainly, it is saying that “Class B is a special kind of Class A, and thus Class B should technically be a more restrictive/constrained version of Class A”. However, if your purpose is code duplication, then this definition will confuse you, because it seems that your Class B is not a special kind of A, but rather it is an A and more, i.e, it gets everything A has, including that code you want to avoid duplicating, plus you’re adding more code in B. So this is the purpose of that guidance, to remind you that Inheritance is about specialization, not avoiding code duplication. Sometimes it is easier to think of this in reverse: Generalization is what enables you to do your polymorphism between various different specializations. In any case, even though it may seem like you are not really ‘specializing’ in that use-case, it is still specialization in technical terms. No languages support any other form of inheritance (except for stuff like Eiffel, which has contra-variance, which I don’t think qualifies as ‘specialization’).

Anyhow, you are both fully correct, and inheritance is indeed a nice way to avoid code duplication, even though there may be better ways but that depends on exactly what you are trying to do.

 
Flag Post

Topic: Game Programming / Question involving Classes (AS3)

Hi Mitijea,

This is a major problem with AS3. In most other OO languages, abstract classes are permitted, e.g, Java, C++ and C#. But in AS3, they do not yet support abstract classes. The good news is that the word ‘abstract’ is a reserved keyword, which could imply that Adobe in future may provide support for this :). For now unfortunately, you shall to find other ways.

Multiple inheritance is in general a very tricky, and easy-to-screw up concept, which is why many languages such as Java, C# and AS3 do not permit it. Basically, you should never do multiple inheritance when 2 or more of the classes you are inheriting have properties. This is a HUGE problem in C++, and Multiple Inheritance should only be used when you understand thoroughly how virtual function tables work, and you know exactly what will happen in all polymorphic scenarios. That said, almost all languages do support Multiple Inheritance the safe way, which is that only one of the superclasses has properties, and the rest of the classes do not have any data members. The extreme variant of these kinds of classes are called “Interfaces”, which not only contain no properties, but also contain no method implementations.

The problem you describe however does not need Multiple Inheritance. What you need are abstract classes, which like Interfaces, do not have any datamembers, but unlike Interfaces, have the permission to have implementation in its methods. There are several other things like this that I found missing in AS3 as compared to other OO languages. I hope they remedy these lackings asap.

 
Flag Post

Topic: Game Programming / Designing Multiplayer Games

Hi,
I see that there are a bunch of people in Kongregate that have submitted multiplayer games. I am currently in the process of making one, and was wondering if people could share some of their design decisions.

It is clear that with Flash, one has to use a Client/Server architecture, because this is the only way to have almost 0 firewall issue. However, within this architecture, I would like to ask you, fellow multiplayer game programmers, the following question:

Question: Where should Game State be stored?
Basically, the question is whether the truth of the entire game is stored on the server or if it is stored at the client, or somewhere in-between. Let me enumerate the two extremes:

1) All state on server:
This says that all information, such as the positions of all the players, is stored on the server itself. The server runs the game server-side, and the clients are all just dummys that receive frequent updates about the state. Any user events, such as a key-press, are sent to the server, which updates the state, and sends it back to all players, including the client. The clients however, will need to run the same ‘engine’ that the server is running, so that it can extrapolate the state of the game between updates from the server.
I have 2 main issues with this approach:
a) User responsiveness is a little lowered. The player presses a button, and must wait for the server to reflect the event.
b) The server ‘simulator’ must be identical to the client ‘simulator’ to enable proper interpolation by the client. This is a pain since the server is written in a different language, e.g Java, than the client.
c) Server has crazy amount of work to do: run the simulator AND process all packets, esp. since you cannot multicast due to lack of UDP sockets in Flash.

2) All state on the clients:
In this approach each client stores a truth, and periodically receives updates from all the other clients about their respective truths (via the a dumb forwarding server). This way, the user never feels any lag on his own player, only other players, and since the user is focused on their player, they will not notice lag issues with other players as much.
Issues:
a) If each user is running at different framerates, then the simulators must be completely frame-rate agnostic, which can be very difficult to do for certain types of real-time games.
b) The delay in the other player’s truth is perceivably doubled with respect to the user’s character.
c) Game events become tricky to synchronize. E.g, who got to the finish line first in a close race?

I am very curious about the various decisions people have made in this regard, and would appreciate discussion in this area.

 
Flag Post

Topic: Game Programming / Sockets

Happy to be the recipient of your 2000th post :)

 
Flag Post

Topic: Game Programming / Sockets

Thanks for the feedback.
On the event note, I think pel you are right; flash internally is processing its’ events at a much higher rate than the fps.

On the ping problem, I have finally fixed it :D. The problem was actually on the Java side:

I was saying:

out.write('p'); // The ping command
out.write('\0'); // Termination for validating my ping command
out.flush(); // Send the data out

Well, in Flash data isnt sent out until you say flush(). But in Java, data can be sent out every time I say write (because it is supposed to be a ‘streaming’ TCP/IP connection, as opposed to a UDP Datagram connection). As such, my ping receiver in Flash would wait for the \0 after the ‘p’ byte, giving a combined ping time that was high. So now what I do, is that I just say

out.write("p\0".getBytes());
out.flush(); // just incase

And just by doing this fixed my ping problem, making my games’ pings almost identical to the ping you get from cmd.

 
Flag Post

Topic: Game Programming / AS3 vs AS2 for someone new to flash

I found AS 2.0 to be ok, but it was a major pain once the game becomes complex, or in the late stages of a game. With AS3 you can truly design your game architectures properly, however leveraging AS3 properly cannot be done without prior experience with OOP design patterns. In general though I have been disappointed with AS 3.0 too for missing out on several critical aspects of OOP, such as function overriding, private constructors and abstract classes. However, it does provide very easy ways to leverage several other OOP concepts such as Events and Reflection.

 
Flag Post

Topic: Game Programming / Sockets

I am making a game using the Socket class. I am new to Flash. I wrote my server in Java. I implemented a very simple ‘ping’ command, that flushes out 2 bytes, and starts a timer. On the java side I have a simple loop that will echo back the ping. Then I handle the socket data event and measure the time elapsed.

On my own computer, I measure a time of like 0 ms or 1 ms, as expected. But when I try to connect from some remote computer, then I found my ping to be like 300ms. ping via cmd between the same two machines reports like 85 ms.

A ping of 300ms (to-and-fro the server only btw) is too slow for the kind of game I am making.

Does anyone have any suggestions on how to do socket programming in flash properly. Should I use events or should I be polling? I tried polling, and it is much much slower on my own local computer (like 4 ms!). By polling I mean like I check the socket buffer on every frame event. I do not understand why polling in the frame event is so much slower than handling the socket data event. It completely eludes me. But even with events, 300ms is very high.

Or perhaps this is because I am using TCP instead of UDP? Normally I write network applications using UDP, and this is the first time I am using TCP for gaming. Is there anyway I can use UDP in Flash?

Or is it that it is not possible to make fast-paced action multiplayer games in Flash? Someone please help :(

Edit: Solved. See my next post.

 
Flag Post

Topic: Game Programming / Secure php posts through flash

Hey,

I was making a high score submission thing, and was wondering how people post a high score to their mysql database through flash. All the tutorials I found online just append the score to the url, which is horrible. I want to encrypt in Flash first then decrypt on the server, but I do not see any API in Flash to do this. I dont even see any api for generating an md5 hash! Can someone please describe how they handle secure communications in Flash and/or what built-in API to use.

Thanks,

Salman

 
Flag Post

Topic: Game Programming / Flash Development Process

I would really like some of the experienced people to please explain to me how they develop there games. I am making my first game and there are too many issues i’m facing and was wondering how other people resolve them:

1) Source Control management: The CS3 source management via ftp is pretty crappy. Can someone please elaborate how they deal with shared-development. Presently I am using Perforce but the damn fla file is binary.

2) Developer/Artist collaboration: The game is one giant fla file, which is binary, which is a major problem; only one person can be using an fla file at a time. I am having MAJOR issues in this regard, and have to constantly tell my artist to put #include’s everywhere to .as files otherwise the code becomes hard-coded inside the .fla file.

3) Resource management: All resources seem to have to be placed inside the fla file. How do you guys deal with your resources (e.g images, sounds, music); If you split your resources and load them dynamically then do you face issues in deploying your swf and if so how do you resolve it?

4) Scene management: How do you guys manage your scenes or in-game menus? For scenes do you make each scene into a different fla? For in-game menus do you store the in-game menu in a separate frame on the timeline or do you instead create it on a new blank movie clip and then use that in the main scene?

5) Deployment: If I want to split my swf and resources etc. then I dont know how to deploy it correctly cuz usually u just link to an swf file. Will the swf look up things on the server side by default or do I have to do other funky stuff?

6) The process in general: Can people describe to me their ‘process’ of game development in general. I’m getting very frustrated with Flash and was hoping people could help explain to me how they are able to develop, produce, test and deploy their games.

Thanks a lot,

Salman

 
Flag Post

Topic: Game Programming / Slowdown, plus any tips?

Advanced Optimizations (WARNING: VERY difficult to implement correctly for not-so-experienced developers):

Collision detection is a major problem and one way to solve it is via binary space partitioning (bsp). There are many forms of bsp, usually based on facts about your game. In your case ithe bullet is ALWAYS going up. Since this is known, you can partition your collision domain along the y-axis. The way to do this is by storing your bullets in a kind of queue/vectory. Arrange it in a sorted way, i.e, everytime a bullet is created stick it at the head of the queue, and every time a bullet leaves the screen or collides away remove it from the list. Instead of going through each bullet, and for each bullet going through each monster, just go through each monster instead. And for each monster, you look at its y-value and use that to binary-search your list. Just google binary search to get the algorithm. You should end up with a ‘range’ of possible bullets that may be hitting it (though most likely just 1 bullet in your case). Then for each of those bullets in that range you check if they intersect in the x-axis. If so you have a collision.

The benefit of this approach will be quite significant when you have large number of entities in the game.

One last note again is that do not use sqrt since u are just comparing, and do not use Math.pow for integer powers (esp. powers of 2).

 
Flag Post

Topic: Game Programming / Slowdown, plus any tips?

There is no need to do Math.sqrt for comparing distances. Just do (dx * dx + dy * dy). Why bother with Sqrt if you just want to compare distances. Also, NEVER do Math.pow(x, 2); just do x * x (although the compiler should optimize this, I wouldn’t really trust Adobe enough). sqrt is very expensive btw.

 
Flag Post

Topic: Game Programming / OOP in flash

Hey,

I am a C++ / UML guy, and am new to Flash. I’m making my first flash game, and am using CS3 but with AS2.0 to be able to target my game for stuff like the Nintendo Wii and Kongregate APIs. Clearly AS 2.0 has severe issues with regards to their OOP, and frankly I cant stand it much, so I am very pleased with the design of AS 3.0. However, I would really like to understand how OOP is implemented by the Flash Player. In particular, I am curious about how it handles the virtual function dispatching and also how differently must I think of Flash OOP from my existing C++ knowledge (e.g, in C++ I may try to ensure that the compiler will not generate the vtable for a certain class, but perhaps such an optimization is meaningless in Flash?).

Thanks,

Salman

 
Flag Post

Topic: Game Programming / ENTER FRAME vs Timer

hey fucrate,

cool demo. The “system timer” itself has a maximum accuracy of 10ms. It cannot be better than that. For proof that Flash is limited by the system timer, read the following article by a blogger working at Adobe:
http://www.kaourantin.net/2006/05/frame-rates-in-flash-player.html

Now, suppose you force your fps=30, then when ur game is on slower machines, the fps may end up being 25. To make things worse, flash behaves 20% slower on a browser than the flash player. In your demo right now, when I put fps=30 i get an fps of 25 (ur cool demo certainly helps make my point! Did you try to test on a browser?). This will cause your assumptions to mess up and your game difficulty to vary significantly. Also, when high scores are reported, its not so fair because people with slower machines had more time to react.

The best technique is specify your physic properties in actual units. For example, I want my car to travel 20 pixels / second. Period. No matter how slow or fast the computer is, it should go at 20 pixels / second. Ideally, you should be saying stuff like, the car should go 0 to 60 mph in 5 seconds. Guess what, you CAN do that! You do that by placing the desired scale on the frame (in this case in miles), converting hours to second, then just multiplying that number by dt/1000 using the technique I described.

Try it; I think you’ll find the results quite interesting :).

Good luck,

Salman

 
Flag Post

Topic: Game Programming / ENTER FRAME vs Timer

lol.

Whoops. You’re right; I accidently wrote p = dv/dt when it should be v = dp/dt and a = dv/dt. Big boo boo. And yes ofcourse that makes the Math wrong. I’ve fixed it in the original now. You need to do the following in your code:

v += a * dt/1000;
p += v * dt/1000;

Ofcourse, I treat p, a and v as vectors, so you’ll have to do stuff like
v.x += a.x * dt/1000;
v.y += a.y * dt/1000;
p.x += v.x * dt/1000;
p.y += v.x * dt/1000;

Or you could create a Class called Vector2 and overload the + and * operators (dunno if u could do that in AS3).

Sorry about that. The equation you provided is correct, but for small deltaTimes this method is much faster, and is accurate. Also, the equation you provided, i.e s = ut + 0.5at2 works great when you base your code on the actual result of getTime() or some concept of time elapsed. This can be useful when doing some fixed animation, but for games where there are dynamic events, its better to deal with dt than timeElapsed.

 
Flag Post

Topic: Game Programming / ENTER FRAME vs Timer

Hi,

Thanks fucrate for your excellent input. I do however have some criticism of your post at the end.

I’d like to provide some additional information to ekagauranga and all others interested in simulation-style game development.

As explained by fucrate, deltatime is the jump in time that occurs between 2 consecutive frames. Because of this jump, the science of simulation is based on discrete-math and numerical analysis. If we are to assume that deltatime is almost zero, then we can readily apply our high-school/college physics in really cool ways. For example, if you know some calculus, you are probably aware that:

[edit: math fixed]
a = dv/dt. (v is velocity, a is acceleration, t is time, da means delta-acceleration which means ‘change in acceleration’)
Similarly,
v = dp/dt. (p is position)

And guess what, the dt in those formulas, can be replaced by the deltaTime calculation shown by fucrate (I’ll be showing a nicer method later). I will now rearrange the formula for position as an example:
v = (new_p – old_p)/dt; // (dv = change in velocity)
new_p – old_p = v * dt;
thus: new_p = old_p + v * dt;
p += v * dt; // QED

As such, you can make a really cool space game for example, where given some force or acceleration, you can derive its position in the following way:
a = F/m; (F is Force and m is mass, if you want to be really anal)
v += a * dt/1000; // (the * 1000 comes from the fact that dt is in milliseconds)
p += v * dt/1000;

And thats it :). This way you get fps-independent, realistic physics motion. How come? If you think about, when the FPS is really high, then dt will be very small, and since from the equation that means that the velocity and position will change by a lesser amount. This makes sense because on a fast computer, more frames are invoked so the change in distance at each frame should be smaller. Similarly when the FPS (frames per second btw) is low, then dt is high making the jump in distance and speed higher, thus resulting in the same distance covered over the same amount of time. btw, C freaks that prefer performance over accuracy could rewrite this formula to be v += a * dt>>10 but I wouldn’t recommend it cuz you will lose some additional accuracy (wont work in Flash anyways).

Ofcourse, dt is NOT zero, so it will not be totally accurate, but will be close enough for games. However, if you are modelling the solar system for example with planets rotating, you may need some manual correction. The above is a variation of Eulors method. If you want greater accuracy, try Eulors ODEs (Ordinary Differential Equations), to be able to predict discrete events and take them into account. For example, frame 1, ball is above ground (falling downward), frame 2, ball is partially gone through the ground. You then use ODE’s to find the point of intersection and extrapolate the correct new position of the ball above the ground. If you want to go really crazy, try Runga Kutta, and you can accurately model even atoms!

Now I present a significantly easier calculation of dt which will work just fine:

deltaTime = getTimer() – lastTime;
lastTime = getTimer();

Voila! Much easier huh? Also, fucrates method is not something performance-intensive game developers will want to use. It contains a loop that will be done every single frame, all to satisfy the redundant requirement that dt should be “the same every time you update”. This is actually bad and you should not do that. If games did that, there would be no such thing as an FPS, because it would be the constant all the time.

fucrates talked about using Polymorphism, which is very useful. Do try to use polymorphism for performing such functions. As an example, you may have the following structure (written in C++/UML form):

NewtonianClass
+ virtual void doFrameMath() { v += a * dt/1000; p += v * dt/1000; }
+ virtual void doFrame() = 0;

  1. Vector3& F, a, v, p; // Vector3 for 3D games, Vector2 for 2D games

AllOtherObjects : NewtonianClass
+ virtual void doFrame() { doFrameMath(); DO OBJECT PER-FRAME STUFF; }

Now you can have an array that holds all your objects as a NewtonianClass, and just have:
for (var n : NewtonianClass in objectArray) {
n.doFrame();
}

And just these 2 lines will automatically do the physics for all the objects.

I would also like to clear a certain misunderstanding. A lot of people say timers are inaccurate, true, but the statement that “over the small amount of time… the getTimer() command is fairly accurate”. This is actually incorrect. The “lot of people” got it right. In fact, the longer the duration, the more relatively accurate it is. The precision of a timer is what defines its’ accuracy. The getTimer() method in Flash has a precision of about 10ms, which means that it is accurate to the nearest 10th millisecond. If you are a C++ programmer, then you have access to the more higher resolution timers on a system, however these timers are computer-architecture dependant and their api are operating-system dependant. On Windows, you can use the QueryPerformanceCounter for a high-resolution timer, which will give a count of the clock cycles of your cpu. getTimer() however is a low-resolution timer, and thus, when deltaTime is very small, its’ relative accuracy is actually much lower.

WARNING:
Although the method shown here is crucial for many games, especially multiplayer games, it does have its problems. The main problem is that if for some reason the computer freezes for a few seconds, then deltaTime is growing, resulting in a sudden jerk in motion to make objects appear where they should have appeared had they carried on their motion. This is a good and bad thing. The bad of it is that it can mess up your assumptions. This is exactly the effect we call lag in online games.

 
Flag Post

Topic: Game Programming / QBASIC helpful?

Hi,

I think QBasic is a great language to learn. I would not advise jumping into Object-Oriented concepts for 2 reasons: 1) It can be very difficult to understand and apply them without the basic procedural language skills and 2) You will not be able to appreciate the power of OOP (Object Oriented Programming) without first knowing how to do the P part of the OOP adequately, and QBasic or VB can set you up with that nicely.

Ofcourse, ActionScript is great too to start with, however there is a lot of non-programming related stuff you need to do in Flash, and many alternatives to programming, that you may not end up learning as much about the basics of control flow as you should need.

As such, go ahead learn QB, and as soon as the course is done, dive into AS. And if you really are interested in Software Engineering as a career, I’d recommend C/C++ via OpenGL.

 
Flag Post

Topic: Game Programming / Preloader doesnt work

The one on http://www.kongregate.com/logos .

 
Flag Post

Topic: Game Programming / Preloader doesnt work

Hi,

The preloader doesnt seem to contain any animation or loader; plus its missing some font. I see it used by rotZion. Can someone point me to it?

Salman

 
Flag Post

Topic: Game Programming / [Kongregate API] AS2 Integration

So do I submit HighScores both as a Statistic AND via the High Scores API?

 
Flag Post

Topic: Game Programming / Small games required

Interesting. arcaneCoder, and other veterans out here, would you be able to share what are the other forms of income through flash games? First of all, I’d like to get an idea of how much one gets from Sponsorship. Also, how many websites do you normally try to distribute the game to. Finally, do you also use Mocha? Basically, say I make one kick-ass game; what would be the best strategy, in your respective opinions, for deployment such that I maximize the revenue.

Salman