Error on comparing Shared Object Data with a Number - actionscript-3

Hey everyone so been at this for a couple hours now and cant seem to figure it out.
So I have a Shared Object Data variable sharedObjectStarsPoints that is used to keep track of the number of stars that a player unlocks in a game.
So what I am trying to accomplish is say the player has unlocked 2 stars and retrys the level again but this time the player gets only 1 star I want the shared Object to ignore the player only getting the 1 star and keep the highest number of stars in the data base in this example that number would be 2. Player can get total of 3 stars.
So when the player loses it takes them to the game over screen which is where I remove all the ENTER FRAME listeners and everything else. This is also where I setup how many stars the player unlocked and try to use the logic from above to compare the two numbers like so:
so in the same function this is when the variable starsCollected is incremented.
if (bJanObjecMult)
{
objectiveScreen.janStars.bonus.gotoAndPlay(2);
//add 1 to star collector number
starsCollected += 1;
//Add one to levels screen stars completed
updateStarsCollected();
}else
{
objectiveScreen.janStars.bonus.gotoAndStop(1);
}
if (bJanObjectPoints)
{
objectiveScreen.janStars.points.gotoAndPlay(2);
//add 1 to star collector number
starsCollected += 1;
//Add one to levels screen stars completed
updateStarsCollected();
}
then below these if statements are where I try to use the logic like so:
if (sharedObjectStarsPoints.data.janStars > starsCollected)
{
trace("DONT SAVE DATA");
}else
{
sharedObjectStarsPoints.data.janStars = starsCollected;
allSharedObjectStarsData();
sharedObjectStarsPoints.flush();
trace("SAVE DATA");
}
so as you can see I am basically saying if my shared object data is greater than the stars collected data, then dont save anything because say the shared data has 2 and the other data only has 1 then I dont want anything to be replaced. But if that is not the case and its less than the starsCollected data then save the new information and update it.
Also to note whenever the player restars the game the starsCollected number var is set back to 0;
please any help would be appreciated!

Related

Can Media Source API appended buffer(range) be overwritten?

I did little investigation into Media Souce Extension/API but I haven't found a way for specific buffer to be overwritten. Lets say I have watched first 30 seconds with lower quality and player switched to higher quality after that, so 30-60 sec is HQ. So... when I seek back to seconds 0-30 I would get lower quality video (one already buffered), but I would like to re-append newly requested same range with higher quality and watch that. I've seen on existing players (MSE showcases) this is not the case.
I guess MSE determines where to append buffer based on (I cannot recall now for the name) start date time? So, is it possible to override some appended range/buffer in Media Source API ?
Yes, it's possible. Before you call appendBuffer() on a source buffer, set timestampOffset to the time in seconds you wish to start overwriting. For example:
var mediaSource = new MediaSource();
mediaSource.addEventListener('sourceopen', function() {
var sourceBuffer = mediaSource.addSourceBuffer('video/webm; codecs="vorbis,vp8"');
/* ...code to fetch low quality binary... */
sourceBuffer.appendBuffer(lowQualityBinary);
/* ...later fetch higher quality binary and overwrite
* entire video starting at the beginning...
*/
sourceBuffer.timestampOffset = 0;
sourceBuffer.appendBuffer(highQualityBinary);
});
Note that if the user is playing the video and you overwrite starting at a time prior to their current play time, the current behavior on Chrome is to continue showing the original appended video. If it's overwritten later, or they seek around, they'll see the new video.

How to Make My score Board works

i have been trying to make a score board, which will start counting from when the helicopter start running till when it falls cause of crashing with a enemie, but the score is not running or doing anything would you tell me whats the problem of my code?
http://prntscr.com/2aospf
that is the game, which is in frame 3, my button of play on frame 2 and the pre loader on frame 1
var score:"0";
//scoreCounter is the instance name of the dynamic text box
function updateScore():void{
score += 1;
scoreCounter.text = score.toString();
}
what im doing wrong? it doesnt start counting when the helicopter runs, thanks.
Are you calling your function whenever the score has to update? If the objective is to purely not hit an enemy and the score therefore based on time, you should call the function at the start of the frame and put a while loop around the counting and updating of the scoreCounter within the function to make the score go up through time.

AS3: Combining counter (score) variable from multiple objects in different classes

I am developing a fairly basic objective class space-shooter style flash game in AS3. The game originally contained 1 enemy target which had random variable parameters, such as speed and health, but the combined score counter remained predefined, one.
I have since expanded my game to where I have several enemy targets each having their own class, thus, they have their own variable parameter values. I also took the liberty of increasing the combined score, to reflect the difficulty of each enemy target.
The problem that I am running in to, is that my original line of code for combining the score counter is still set to "score++;", which just adds a value of 1 each time that "if statement" occurs.
My question, is how can I get my score counter to increase the score based on the value assigned for each respective class?
Here are a few bits of relevant code, with notes to help explain my view:
"If statement" (housed in my Level class) for when an enemy target is killed:
// if the bullet is touching the ship
if (MyMaths.hitTest(sh, bullets[bcount])) {
sh.health--; // lose 1 heath point
score++;
removeChild(bullets[bcount]); // remove the bullet from the screen
bullets.splice(bcount, 1); // remove the bullet from the list
}
Ship1 (housed in my Ship1 class) score value
public function Ship1() {
score=1; // set point value
}
Ship2 (housed in my Ship2 class) score value
public function Ship1() {
score=2; // set point value
}
Ship3 (housed in my Ship3 class) score value
public function Ship1() {
score=3; // set point value
}
I am just not sure if I would need to make a new function for combining the score value, and have my "score++;" pull from that, and how would I go about that?
I feel that this is a question that many fellow Objective-Oriented programmers would deem relevant, as combining a variable from multiple classes to a single counter is not as easy as it may seem. Also, this could be used in a wide range of other developer niches, apart from game developing -- creating a database of multiple models of computers in a network, and calculating a "total completed" field, after refreshing the workstations with a new OS or required software.
I really would appreciate anybody who could offer their expertise, opinion and/or words of encouragement.
Thank you very much,
Alex
Why not have a Singleton that each of the ships communicate with instead of doing it that way.
Whenever you increment the score:
ScoreManager.getInstance().incrementScore(ShipX.getScoreDelta())
Where getScoreDelta() would be reset to 0 after each collection.
Then when the game is done:
ScoreManager.getInstance().getCurrentScore();

Time Slow/Speed Up Power Up

I'm creating a collecting game, and I want to create a time slow/speed up powerup.
Any ideas on how to do that in Flash/AS3?
One way I thought of was simply changing the frame rate. I can slow down the frame rate. But when I try to increase the frame rate beyond 60, Flash caps it at 60.
Thank you in advance for your help.
I like to do time-based movement instead of frame-based movement for better consistency. The general concept is to check the amount of time passed between frames and base movement on that instead of frames which can alternate (e.g. you can have 60FPS for a bit and then it slows down to 30FPS). You can do a simple calculation based on time passed for movement, for instance player.x += player.speed * timeDiff but that can result in odd situations if the time passed between frames happens to be really large (for instance, the player can end up missing lots of collisions since you are moving him in one large movement). Instead, I like to use a game loop to move the player X times based on the amount of time that has passed between frames, ensuring that collisions and any other game loop events will be properly checked.
This also has the advantage that it is easy to adjust the speed.
Here is the basic concept:
private var speedMultiplier:int = 100;//100 normal speed, 0 paused
private var currRealTime:int = getTimer();
private var currGameTime:int = currRealTime;
private var globalLastTime:int = currRealTime;
private var totalTimeDiffRemainder:int = 0;
private var loopTime:int = 20;//every 20 ms run our actions
public function getGameTimer():int
{
return currGameTime;
}
private function updateGameTime():void
{
var realTime:int = getTimer();
currGameTime = currGameTime + speedMultiplier/100*(realTime - currRealTime);
currRealTime = realTime;
}
private function runEvents(event:Event):void
{//ENTER_FRAME event
var totalTimeDiff:int = getGameTimer() - globalLastTime + totalTimeDiffRemainder;
globalLastTime = getGameTimer();
while (totalTimeDiff > loopTime)
{//every 20 ms run all our actions
totalTimeDiff -= loopTime;
//run all your game loop events here, such as collision checks
}
totalTimeDiffRemainder = totalTimeDiff;
updateGameTime();
}
So every time an ENTER_FRAME event fires, we will check the time passed since the last ENTER_FRAME event and then run our actions once for each 20ms that has elapsed and pass the remainder over to the next ENTER_FRAME event. For instance, if it's been 47 ms since the last ENTER_FRAME, we will run our actions twice and pass over 7 remaining ms to the next ENTER_FRAME event.
In order to pause, slow down, or speed up the game, all you have to do is modify speedMultiplier. Changing speedMultiplier to 0 will pause the game, 50 is half speed 100 is normal speed, 200 double speed, etc.
I believe the general way to do this would be to use an MVC like setup where your model holds all the data for the game elements (character position/orientation, enemies, dynamic map elements) then the controller is modifying the model. With the controller modifying the model this way you could add a multiplier to the model, and use the multiplier when having the controller update the model for "physics" or other modifying dynamic elements in the game.
Roughly:
Model
public var speedMultiplier:Number=1;
public var playerXSpeed:Number;
public var playerYSpeed:Number;
Controller (I'm assuming you make a controller class and pass the view to the constructor and are listening for events from the view in the controller).
private function enterFrame_handler(event:Event):void
{
var playerSprite:Sprite = mainView.playerSprite;
playerSprite.x += playerXSpeed*speedMultiplier; //only problem I can see here is your player skipping past certain elements, to avoid this you could use a loop to make each motion and do checks but it's more CPU intensive
//var enemySprites:Vector<EnemySprite>;
//other game physics here, reduce speed due to drag, fix any invalid values etc.
}
Edit
Actually in thinking this through some more, although I do generally like using an MVC setup myself since it allows one to have a single sprite that does all the drawing; you could also use the same concept of a speedMultiplier shown here without necessarily changing around any software patterns. If you end up needing to do it with a loop because you need it to do checks for every spot it would hit as an object moves along, you may need to have your default speedMultiplier be something like 10 so you could set it down to 1 to get 1/10th speed with all the same checks as it would get at 10 being normal speed (again only issue here being it has to do whatever calculations 10 times for every update, in this case you may want to use a timer instead of the frame rate to control the overall calculation speed).

Fastest method to find a complex type in a list (Vector, Array, Dictionary, whatever is faster)

Hail, Stack!
I need to know the best method to find an item inside a list (Vector, Array, Dictionary, whatever is faster) of complex type (extensions of Objects and Sprites).
I've used "Needle in Haystack" method, but it seems that it isn't fast enough.
E.g.
Suppose that I have a collection of Sprites (a pool, in fact).
Each sprite will be added to the stage and perform some action. After that, it will die.
I don't want to pay the cost to dispose it (garbage collect) and create another (new) one every time so I'll keep the dead sprites in a collection.
Sometimes times I'll call a method that will add a sprite to the stage.
This sprite can be a old one, if it is already dead, or a new one, if the pool don't have any free sprite.
One of the scenarios that pushed me to this question was a Particle System.
A "head" particle leaving a "trail" of particles every frame and exploding into a flashy multitude of particles... Every frame...
Some times this counts up to 50.000 PNGs with motion, rotation, alpha, event dispatching, scale, etc...
But, this is JUST ONE scenario...
At the moment I'm trying to use a Object Pool with a Linked List...
Hopes that it will be faster that running a whole Array/Vector or create new instances every frame an let them dye with Garbage Collection.
Someone knows a better/faster way to do it?
I'm not sure about what you are searching and what you want to do with it.
If you are trying to determine if a string is in a list, the fastest solution is the Dictionnary. I've done a little benchmark.
/**
* Determine which is the fastest to find a key between array, object, vector and dictionnary
**/
public class FlashTest extends Sprite {
public function FlashTest() {
var array:Array = new Array();
var object:Object = new Object();
var dictionary:Dictionary = new Dictionary();
var vector:Vector.<String> = new Vector.<String>();
for (var i:int=0; i < 10000; i++)
{
array.push(i.toString());
object[i.toString()] = 1;
vector.push(i.toString());
dictionary[i.toString()] = 1;
}
var time:uint = getTimer();
for (i=0; i < 10000; i++)
{
array.indexOf(i.toString());
}
trace("array"+(getTimer()-time)); //2855
time = getTimer();
for (i=0; i < 10000; i++)
{
vector.indexOf(i.toString());
}
trace("vector"+(getTimer()-time)); //3644
time = getTimer();
for (i=0; i < 10000; i++)
{
object.hasOwnProperty(i.toString());
}
trace("object"+(getTimer()-time)); //48
time = getTimer();
for (i=0; i < 10000; i++)
{
dictionary.hasOwnProperty(i.toString());
}
trace("dictionary"+(getTimer()-time)); //35
}
}
Cheers!
Based on your revised question, I don't see this as a search optimization issue unless we're talking about thousands of objects. When one of your objects from the pool "dies", it could notify your code that is managing the objects (by event or callback) and you then null out its entry in your Dictionary of active items (or splice it from Array, or kill it with a flag, more on this below**), and push it onto another Array, which is a stack of objects waiting to be reused. When you need a new object, you first check if there is anything in your recycle stack, and if there is, you pop one of those and re-initialize it. If the stack is empty, you construct a new one.
**The best choice of which data structure you use for holding your active objects list (Array/Vector/Dictionary) will probably depend on the nature of your list--I'd be willing to bet that the data structure that is quickest to loop over (for example if you need to do it every frame to update them) is not necessarily the one that is cheapest to delete from. Which one you go with should be whichever works best for the number of objects you've got and the frequency with which they get removed, re-added or updated. Just do a little benchmarking, it's easy enough to test them all. If you have relatively few objects, and don't need to loop over them continuously, I'd put my money on the Dictionary for the active pool.
The key point to get from this answer is that you should not be looping through all the items each time you need to find a dead one to re-use, you should pull them out when they die and keep that as a separate pool.
This is really going to depend on how you need to identify the object. Are you comparing some value of it or comparing references?
Assuming references, you should be using the built in methods found on both Array & Vector. Linear searches (like looping over the entire list) grow slower as the number of items in the list increases. The built in solutions will use faster non-linear search algorithms. For example:
myList.indexOf(myObject);
The fastest thing you can do is direct access. If you are using either an Object or Dictionary you can use the object or a unique id as the key, this gives you direct access. But this doesn't help if you need the objects position in the list. eg:
//when setting it
var map = {};
map[myObject] = myObject;
//or
map[myObject.id] = myObject;
//then later
var myObject = map[THE KEY]
Do you have any sort of key that can be attributed to the objects?(or possibly use the object as a key)
I believe that a Dictionary look up would probably be the fastest since it is done similar to Java's HashMap.
In that case you could have the object as the key and just do
myDictionary[complexObject] != null
(it will be null if there is no entry of that object)
Although if you could specify further what it is you need to lookup I might be able to offer further application of this
I'd say Vector, but there seems to be some mixed results.
Vector.<> vs array
http://impossiblearts.com/blog/2008/06/fp10-vector-vs-array/
If your sprites have unique IDs, and you can use a Dictionary, then what's the question? Dictionary is definitely faster.
The average search on a Vector or Array takes, at best, O(log(n)) time. Though you can only achieve that if your Vector is sorted, which means spending time elsewhere to ensure it stays sorted. If you don't sort it then you have to scan, which means O(n).
Dictionaries (variously known as hashtables, maps), when implemented right (and I can only assume that what Actionscript provides is implemented right) guarantee O(1) access time. You pay for that in more memory. The O(1) hides some constant times that are higher than those of Vector searches, so for small lists of items Vector would be more efficient. However, from the description of your problem it sounds like a no-brainer.