Best way to make this game AS3 [closed] - actionscript-3

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I'm making a game as a part of my unit for uni but I don't know the best way of doing it as i'm new to AS3. I have 8 guests in a party each different and has different personalities, hobbies and interests. The game works like this, if you click on a guest and click anywhere on stage then that guest will move towards it. If you click on a guest and then click on another guest, the guest you clicked on first will move towards the guest you clicked on second and when they are close they will talk to each other.
All the 8 guests will share the same function and code in terms of the moving around. I have got the click and move part done but it was done on a Guest01 class but all the guest will have it the same. Should I create 8 different classes for each guest or should I do it using arrays. I really don't know how to start on this. Below is the code for click and move:
package
{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.filters.*;
public class Guest01 extends MovieClip
{
var walkSpeed:Number = 5;
var oldPosX;
var oldPosY;
var myGlow:GlowFilter = new GlowFilter();
public function Guest01()
{
addEventListener(MouseEvent.MOUSE_OVER, addGlow);
}
public function addGlow(event:MouseEvent):void
{
filters = [myGlow];
addEventListener(MouseEvent.MOUSE_OUT, removeGlow);
addEventListener(MouseEvent.CLICK, ready);
}
function removeGlow(event:MouseEvent):void
{
filters = [];
}
public function ready(event:MouseEvent):void
{
filters = [myGlow];
stage.addEventListener(MouseEvent.MOUSE_DOWN, walk);
removeEventListener(MouseEvent.MOUSE_OUT, removeGlow);
}
function walk(event:MouseEvent):void
{
oldPosX = parent.mouseX;
oldPosY = parent.mouseY;
rotation = Math.atan2(oldPosY - y,oldPosX - x) / Math.PI * 180;
filters = [];
stage.removeEventListener(MouseEvent.MOUSE_DOWN, walk);
stage.addEventListener(Event.ENTER_FRAME, loop);
}
function loop(event:Event):void
{
var dx:Number = oldPosX - x;
var dy:Number = oldPosY - y;
var distance:Number = Math.sqrt((dx*dx)+(dy*dy));
if (distance<walkSpeed)
{
// if you are near the target, snap to it
x = oldPosX;
y = oldPosY;
removeEventListener(Event.ENTER_FRAME, loop);
}
else
{
x = x+Math.cos(rotation/180*Math.PI)*walkSpeed;
y = y+Math.sin(rotation/180*Math.PI)*walkSpeed;
}
}
}
}

I have got the click and move part done but it was done on a Guest01 class but all the guest will have it the same. Should I create 8 different classes for each guest or should I do it using arrays.
You should not create 8 different classes for 8 different Guests but you should try to re-use the classes and methods for different Guests.
I have 8 guests in a party each different and has different personalities, hobbies and interests.
You would want to create one Guest class and keep all the properties (personalities, hobbies etc.) as the variables in the class. You'll have to initialize the Class for different Guest in the start based on the profile the guest selects (or random). Also all the methods for Guest (like walk, glow etc.) would be the methods of the class itself.
Hope it helps to give you some direction.

Just tried to answer your question from a different post. You need to break down the game into simple actions like moving the user from one place to another, calculating the offset position a user should move to if they wan to move to another user, calculating the position of elements for displaying a users hobbies and interests, ect.
Have you ever programmed in an object oriented language before? There are some fundementles that you must have a firm grasp of before taking on a project like building a game. Based on your last post, your next focus should be the following methods.
Since you have already written a function for relocating a player based on a user click you should write the following functions:
Inside the clickToMove() function ( or whatever you called it). Write an if test to see if the relocating click selects an empty location or a location with a user on it. If the user is present you need to write another method for offsetting the position of the player that is to move, otherwise the players will be layered on top of each other.
I'm boarding a plane now will post again soon

Related

AS3. How to set-up players for real-time game?

I'm creating flash fighting game 1vs1.
Here is Hero (local-player) and Enemy (remote-player). How I need to setup them correctly that after connection to arena they will be spawned successfully?
I mean if player 1 connects to arena he should be declared as Hero (local-player) and for him player 2 should look like Enemy (remote-player).
The same for player 2. He should be declared as Hero (local-player) and for him player 1 should look like Enemy (remote-player).
Here are 2 character's templates to choose and here is code:
public function selectHero(what:int):void {
// this is called with correct "what", design yourself. I use array index
var whatHero:Class = heroes[what]; // get selected hero symbol
if (Hero && Hero.parent) Hero.parent.removeChild(Hero);
// clean up previous hero. Drop listeners here, if any
Hero = new whatHero(); // get new hero
// process as usual, don't forget to "addChild(Hero)" somewhere
create_hero();
}
function choosePlayer(event:MouseEvent):void {
selectHero(0); // here choose first template
start(event);
}
function create_hero()
{
addChild(Hero);
}
So Hero added to stage (It is local-player).
This is how I declare Enemy:
public var Enemy:Priesas = new Priesas; //Priesas is instance name of Enemy
So as I understand I don't need to use addChild(Enemy); because will be added just template, how to add remote-player Hero (from other computer) that will be declared as Enemy? Or something like that.
This game is creating for Facebook. For that is needed AppWarp? Thank you for answers.
Yes, you would need AppWarp to connect the two players and to exchange messages between them. This seems similar to one of the samples of AppWarp (smiley space shooter). Have you already explored the samples and documentation?
http://appwarp.shephertz.com/game-development-center/actionscript3-game-developers-home/

universal collision detection for action script 3

I'm writing a game where you have to go through a maze. I want this game to have different levels. But for each level, the maze is going to be different. So I drew other walls. But I do not want to write my collision detection method 50 times if I have 50 different levels.
I thought of a way of fixing it, but it's not working. I created a new symbol with nothing in it and named it wall. I think that I can make my wall = wall1 (another symbol I converted, and exported for as), and just do stage.addChild(wall). But I can't find a way to do that. So I need help!
Make a generic class e.g. Wall and make your library symbols use that for their base class. You won't need to create them at runtime using ActionScript for this inheritance to work, you can still just place your MovieClips on the stage.
The next thing you need to do is store these Walls somewhere. Because you seem inexperienced with ActionScript, and want to avoid writing code for new levels, you can automate this process using a manager type class. We will call this class WallManager and it will look like this:
public class WallManager
{
private static var _walls:Vector.<Wall> = new <Wall>[];
internal static function register(wall:Wall):void
{
_walls.push(wall);
}
public static function reset():void
{
_walls = new <Wall>[];
}
public static function get walls():Vector.<Wall>{ return _walls; }
}
Then we'll create your Wall class. Within the constructor for this class, we will automatically have the Wall add itself into the WallManager listing:
public class Wall extends Sprite
{
public function Wall()
{
WallManager.register(this);
}
public function touchingMouse(mouseX:int, mouseY:int):Boolean
{
// For this example I am checking for collisions with the
// mouse pointer. Replace this function with your own collision
// logic for whatever it is that is supposed to collide with
// these walls.
if(parent === null) return false;
var bounds:Rectangle = getBounds(parent);
return bounds.contains(mouseX, mouseY);
}
}
This setup is not 'best practice', but it is suitable in your situation because your project seems small, you appear to be working on it alone, it's simple and it gets the job done.
At the end of each level, use WallManager.reset() to remove the walls from the previous level. For checking collisions across all walls, just use a loop like this:
for each(var i:Wall in WallManager.walls)
{
var collision:Boolean = i.touchingMouse(mouseX, mouseY);
if(collision)
{
// There was a collision.
//
//
}
}
You can make one MovieClip with 50 frames saying stop() on the first frame and do your code like this:
private var wallnum:int;
public function Main()
{
stop();
wallnum = 1;
var wallobj = new Wall();
addChild(wallobj);
wallobj.gotoAndStop(wallnum);
}
For collision detection, I recommend Pixel Perfect Collision Detection (https://code.google.com/p/master-air-controller/source/browse/trunk/master-air-controller/src/PixelPerfectCollisionDetection.as?spec=svn6&r=6)

AS3 How to make separate menus/windows with heavy data? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
In games it's usual to be able to access some kind of menus.
A list of things with descriptions, a menu of upgrades, anything that's pretty heavy with pictures, text etc.
So what is a convenient way to organize it all?
As I tried classes, it seems like they don't share variables between them.
I need a way of sharing data between these windows/menus. And it shouldn't be overweighted with data, meaning each time I close a menu it's parts disappear to not make Flash calculate MovieClip positions, alphas, effects and other values that I don't need, working with another menu.
As an example to better understand, what if I make 5 games in one and need to share variables between them?
Say, first I play Arcanoid, then switch to Tetris and use Arcanoid score as a number of blocks I can get, then switch to Pinball and use the number of lines scored in Tetris as a number of balls, then switch to Gradius and my ship attack power is Pinball score divided by 1000, then I see a window of overall scores with heavy victory firework effects.
I'd need each game to work separately, otherwise they will go very slow overloaded with graphics and the length of code to find functions.
How is that achieved?
Thanks moskito, I'm a bit messy ^_^'
How is that achieved?
You create the architecture to make it happen. Your particular example could be approached like this:
Firstly, you want to define the foundation that these mini-games or separate batches of content will run on. This foundation will deal with running the mini-games, as well as tracking their state and information associated with them that you want to pass off to subsequent mini-games.
Secondly, you want to define the base class that will represent one of these mini-games. This class will be extended for each of the new games you want to create and have run on the platform. This base class will deal with notifying the platform of changes.
Lastly, you want to create some models represting a state in change within the mini-game. The inbuilt Event system is a good way to approach this, but you can easily create your own data models in this instance which you pass off to the platform directly.
Code samples.
The basics of your platform could be something along the lines of:
public class Platform
{
private var _game:MiniGame;
private var _recentGameStateData:GameStateData;
public function loadGame(game:MiniGame):void
{
if(_game != null) game.unload();
_game = game;
_game.start(this, _recentGameStateData);
}
public function update():void
{
if(_game != null) _game.update();
}
internal function manageStateChange(gameStateData:GameStateData):void
{
_recentGameStateData = gameStateData;
// Do stuff with the new game state data, like save the current score
// to use in your next game.
//
}
}
Your mini-game:
public class MiniGame
{
private var _platform:Platorm;
private var _score:int = 0;
public function start(platform:Platform, previousGameStateData:GameStateData):void
{
_platform = platform;
// Use previous GameStateData here.
//
}
public function update():void{}
public function unload():void{}
public function notifyPlatform(gameStateData:GameStateData):void
{
_platform.manageStateChange(gameStateData);
}
protected function get score():int{ return _score; }
}
Your game state data for the platform to manage:
public class GameStateData
{
private var _game:MiniGame;
private var _score:int;
public function GameStateData(game:MiniGame, score:int)
{
_game = game;
_score = score;
}
public function get game():MiniGame{ return _game; }
public function get score():int{ return _score; }
}
And then an example of sending that information up to the platform in your own mini-game:
public class TetrisGame extends MiniGame
{
override public function unload():void
{
// Let the Platform know about the current score when this game is
// being unloaded.
var state:GameStateData = new GameStateData(this, _score);
notifyPlatform(state);
}
}

Spawning and destroying things in AS3

Okay, so I am making a small game where the user picks randomly spawned flowers. When a flower is picked, it disappears and the user gets points.
Here is some of my code:
import flash.events.MouseEvent;
function makeFlower() {
var flower:Flower = new Flower();
addChild(flower);
flower.x = Math.random() * 500;
flower.y = Math.random() * 400;
}
function removeFlower(event:MouseEvent):void {
flower.pick();
}
setInterval(makeFlower, 2500);
addEventListener(MouseEvent.CLICK, removeFlower);
So in the above code, flower.pick() doesn't work because it's out of scope (how would I get it in-scope, by the way?)... that is one problem. But this problem got me questioning where the creation of the flower should happen. Would it be better to put addChild() in my constructor method?
And then the destruction part... the event listener which detects the flower being clicked... should this be separate (like how I have it) or should it be put into the Flower class? I am new to ActionScript and would like to know where things should be put.
Thanks!
try:
import flash.events.MouseEvent;
var flower:Flower;
function makeFlower() {
flower = new Flower();
addChild(flower);
flower.x = Math.random() * 500;
flower.y = Math.random() * 400;
flower.addEventListener(MouseEvent.CLICK, removeFlower);
}
function removeFlower(event:MouseEvent):void {
event.target.pick();
//removeChild(event.target); // active this to remove the clicked flower
}
setInterval(makeFlower, 2500);
Where you should handle things depends on quite a few factors, number one on my list would be if you're using the Flex framework or not, number two would be what is best for a given application. For your case it appears you're just using Flash IDE.
You'll want to have a collection of the flower objects your adding to the display tree. Then on click you'll want to use the target of the click to know which "flower" they picked, instead of arbitrarily removing some flower.
The other good thing about having a collection of the flowers is that you can actually just toggle the visibility (this also toggles the ability for a touch/click to interact with an object). Then you can have the Flower objects all created at once or at least re-used instead of having to be garbage collected and making a ton more objects (as pointed out by Daniel below the term is object pooling).
import flash.events.MouseEvent;
var allFlowers:Array = [];
var oldFlowers:Array = [];
function makeFlower() {
var flower:Flower;
if(oldFlowers.length>0) //if there's stale ones, already created but since picked
{
flower = oldFlowers.pop();//grab the last one from the list
flower.visible=true;//show it, update to position below should happen fast enough so you won't see it move
}
else
flower = new Flower();
allFlowers.push(flower);
addChild(flower);
flower.addEventListener(MouseEvent.CLICK, removeFlower); //Adding the listener directly to the Flower object, assuming it's a Sprite/MovieClip/InteractiveObject of some sort
flower.x = Math.random() * 500;
flower.y = Math.random() * 400;
}
function removeFlower(event:MouseEvent):void {
var clickedFlower:Flower = (event.target as Flower); //this is a local reference
clickedFlower.pick(); //assuming this toggles the visibility
oldFlowers.push(allFlowers.splice(clickedFlower,1)); //removing it from the "active array" putting it in the "stale array"
}
setInterval(makeFlower, 2500);
Ideally this would all be wrapped up in a class, really scoping variables just makes way more sense to me in the context of a class than just dangling in some block of code somewhere.
Since in your original code you declared that flower was a var and gave it the type of object stored at that var (Flower), it's scope is limited to the opening and closing curly braces for that function. In the case of the variables I defined they should be available so long as the object that contains the code is available.
There are three primary "scope modifiers" you can use when declaring variables or functions in a class in AS3 (namely public, protected, or private). Using public means the property/method (member) is accessible within the class definition (generally the file, something.as) as well as by anything else, if you make a variable public it can be modified by anything that uses the code, this can lead to un-predictable behavior of your application if change from the outside is unintended. Using protected means anything that inherits from or extends a class can access/use the protected member, but nothing that just has an instance of the object can access these members (hence the term access modifier). The third level is private which means only code within that class (across all methods) can access the member but no inheriting/sub-classes of the class can access the member. This is essentially an implementation of the concept generally termed encapsulation in computer science. There's a lot more detail, but really it's already getting too long for a decent SO post.

Creating Classes and Properties in AS3

I'm new to AS3. Learning how to create classes. Is comp = new HouseObjects creating a new class? Is comp creating an instance of the HouseObjects? I realize that this is inside public class TreeHouse. I'm thinking that HouseObjects, how I set it up is not a class...not sure what the correct way to set up classes and properties.
Also I noticed, that when I tried to link another movieclip using the same linkage name HouseObjects--it asked to enter a unique class. I'm trying to create multiple instances from the same class called HouseObjects.
package {
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.events.Event;
public class TreeHouse extends MovieClip
{
private var comp:MovieClip;
var powerData:int; // stores user data (of selected data)
//var currentPower:int; // stores current power
public function TreeHouse()
{
comp = new HouseObjects; // linkage in library
comp.power = 2; // amount of power
comp.name = "comp";
comp.buttonMode = true;
comp.bstate = 0; // button state
//add event listeners -- listens to functions that are called
comp.addEventListener(MouseEvent.MOUSE_OVER, rolloverToggle);
comp.addEventListener(MouseEvent.MOUSE_OUT, rolloutToggle);
comp.addEventListener(MouseEvent.CLICK, toggleClick);
comp.addEventListener(MouseEvent.CLICK, toggleClick);
stage.addChild(comp); // add computer to stage -----------------------------------
trace("tracing...");
comp.x = 100;
comp.y = 100;
}
// function rollOver --------------------------------------------------------------
function rolloverToggle(e:MouseEvent) {
if (e.currentTarget.currentFrame == 1)
e.currentTarget.gotoAndStop(2);
if (e.currentTarget.currentFrame == 3)
e.currentTarget.gotoAndStop(4);
}
// function rollOut-- --------------------------------------------------------------
function rolloutToggle(e:MouseEvent) {
if (e.currentTarget.currentFrame == 2)
e.currentTarget.gotoAndStop(1);
if (e.currentTarget.currentFrame == 4)
e.currentTarget.gotoAndStop(3);
}
// function toggleClick-------------------------------------------------------------
function toggleClick(e:MouseEvent) {
// On MouseEvent gotoAndStop(Frame Number)
if (e.currentTarget.currentFrame == 2)
{
e.currentTarget.gotoAndStop(3);
e.currentTarget.bstate = 1;
}
if (e.currentTarget.currentFrame == 4)
{
e.currentTarget.gotoAndStop(1);
e.currentTarget.bstate = 0;
}
//var powerData:int = HouseObjects[e.currentTarget.power]; // set power value
// Find out which object selected-------------------------------------------------
//trace("movieClip Instance Name = " + e.currentTarget); // [object Comp]
//trace(houseArray[e.currentTarget.name]); // comp
trace("using currentTarget: " + e.currentTarget.name); // comp
//trace("powerData: " + powerData); // power of user data
//trace("houseArray: " + houseArray[0]); // the 0 index of house array
trace(e.currentTarget.power); // currentTarget's power************
}
} //end of class
} // end of package
I am not quite sure if I understood your question correctly. comp = new HouseObjects creates a new instance (object) of the type HouseObjects. (A little research on OOP basics would probably make life easier for you.)
Regarding the »Please enter a unique class name« error: You cannot assign the same class to two library symbols because the symbol is hooked up to the class internally so that if you create a new instance (var x = new HouseObjects; addChild(x);), the content from the linked symbol is also added to the display list. If there were multiple library symbols linked to the same class, how would the Flash compiler know which one to choose?
Your question is pretty broad and , as klickverbot suggests, it would be better if you took a little time to understand basic OOP concepts.
There are a lot of resources available to get you started with AS3, check this for instance
http://tv.adobe.com/watch/colin-moocks-lost-actionscript-weekend/course-1-introduction
Colin Moock's tutorial is very easy to follow and will give you most of the tools you need to get started.
If you are new to AS3, and OOP in particular, you should check out Moock's Essential Actionscript 3 which is beyond fantastic for a step by step education in OOP in AS3.
HouseObjects appears to be a class and you are creating a new instance of it for the variable comp
You've got a duplicate definition. It appears that you are trying to use Flash Pro to extend HouseObjects for the lightbulb. It doesn't work like this in Flash Pro. You are creating a MovieClip symbol and giving it a class definition. It has to extend MovieClip and you cannot change this in this case. You could likely extend HouseObjects in an AS3 file and make use of it in your application.
Personally think that if you want to really get your head around OOP with AS3 you should get the book and get out of Flash Pro. Use an IDE like Flash Builder, FDT, Flash Develop, or IntelliJ IDEA. It is a lot easier to understand when you get away from the dialogs and other complications of the Flash Pro IDE :>