AS3 How to shorten this bit of code? - actionscript-3

I was working on something and I have this chunky bit of code in there:
if(contents.x>-199 && contents.x<-1) {
mcPosX = 0;
} else if(contents.x>-399 && contents.x<-201) {
mcPosX = -200;
} else if(contents.x>-599 && contents.x<-401) {
mcPosX = -400;
} else if(contents.x>-799 && contents.x<-601) {
mcPosX = -600;
} else if(contents.x>-999 && contents.x<-801) {
mcPosX = -800;
} else if(contents.x>-1199 && contents.x<-1001) {
mcPosX = -1000;
} else if(contents.x>-1399 && contents.x<-1201) {
mcPosX = -1200;
} else if(contents.x>-1599 && contents.x<-1401) {
mcPosX = -1400;
} else if(contents.x>-1799 && contents.x<-1601) {
mcPosX = -1600;
} else if(contents.x>-1999 && contents.x<-1801) {
mcPosX = -1800;
} else if(contents.x>-2199 && contents.x<-2001) {
mcPosX = -2000;
} else if(contents.x>-2399 && contents.x<-2201) {
mcPosX = -2200;
} else if(contents.x>-2599 && contents.x<-2401) {
mcPosX = -2400;
} else if(contents.x>-2799 && contents.x<-2601) {
mcPosX = -2600;
} else if(contents.x>-2999 && contents.x<-2801) {
mcPosX = -2800;
} else {
//mcPosX = contents.x;
}
basically I have a long movieclip (much wider than the stage), it snaps to certain points as you drag it around, depending on which section is shown on the screen.
I feel like this section is really long and I'm trying to improve my AS3. Can this be shortened/improved at all?

Hard to determine exactly what you're trying to do, butI think this might help you on the right direction:
mPos.x -= (Math.floor(contents.x / 200) * 200);

Related

*RPG-Engine Troubleshoot (AS3): "Multiple Levels" code snippet returns a "null" HitTestObject

*Hello!
I'm working on an open-source game engine scripted in AS3
and I am attempting to have the MC advance to another area/level...
*How it Works/The Idea...
When the MC obtains a key, it is used to turn kameHouseLocked to kameHouseOpen.
When the kameHouse is set to open the player can hold the "up arrow" towards the
door to advance. I have two ways to achieve this, either within a movieclip or by
calling whatever second layers are needed layers to the stage. The way my code is
currently set up, it is unable to reference the kameHouse which is needed to trigger
the event. The logic worked well enough for the key, should I make sure whatever is
being referenced in encased within a movieclip? Do I need an independent snippet
entirely to handle the collisions? Any help would really be appreciated,
I will kindly credit you for any effort/involvement, thank you in advance!
*Output spits this out?
TypeError: Error #2007: Parameter hitTestObject must be non-null.
at flash.display::DisplayObject/_hitTest()
at flash.display::DisplayObject/hitTestObject()
at pokemongameexperiment/keyDownHandler()
*The Code in Question...
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.Event;
import flash.display.Stage;
import flash.events.MouseEvent;
mc.gotoAndStop("standingRight");
toggle_btn.stop();
hide_text.stop();
stop();
//backenvironment.kamiHouse.stop();
var keyCodeToListenForDown = '40'; //downarrow key
var keyCodeToListenForUp = '38'; //uparrow key
var keyCodeToListenForLeft = '37'; //leftarrow key
var keyCodeToListenForRight = '39'; //rightarrow key
var keySinglePress:Boolean = false;
var keyDoublePress:Boolean = false;
var timeToWaitForDoublePress:Number = 300;
var waitingForDoublePress:Boolean = false;
var leftBumping:Boolean = false;
var rightBumping:Boolean = false;
var upBumping:Boolean = false;
var downBumping:Boolean = false;
var leftBumpPoint:Point = new Point(-30, -55);
var rightBumpPoint:Point = new Point(30, -55);
var upBumpPoint:Point = new Point(0, -120);
var downBumpPoint:Point = new Point(0, 0);
var pp:Boolean=true;
var played:Boolean=false;
var mySound:Sound = new MySound();
var myChannel:SoundChannel = new SoundChannel();
var rightPressed:Boolean = new Boolean(false);
var leftPressed:Boolean = new Boolean(false);
var upPressed:Boolean = new Boolean(false);
var downPressed:Boolean = new Boolean(false);
var mcSpeed:Number = 10;
var roshiTimer:int = 0;
var roshiDuration:int = 0;
var roshiFacing:int = 0;
var roshiSpeed:Number = 3
var RF:Array =
["roshiUpWalk", "roshiDownWalk",
"roshiLeftWalk", "roshiRightWalk",];
var RX:Array = [0, 0, -1, 1];
var RY:Array = [-1, 1, 0, 0];
var kameKeyCollected:Boolean = false;
var kameHouseOpen:Boolean = false;
var currentLevel:int = 1;
//kameHouse(2).prevBtn.addEventListener(MouseEvent.CLICK, prevSection);
addEventListener(Event.ENTER_FRAME, onRoshi);
toggle_btn.addEventListener(MouseEvent.CLICK, togglePlay);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
stage.addEventListener(Event.ENTER_FRAME, gameLoop);
stage.addEventListener(KeyboardEvent.KEY_DOWN, handleKeyDown);
//kameHouse(2).nextBtn.addEventListener(MouseEvent.CLICK, nextSection);
//function prevSection(event:MouseEvent):void
//{
//var thisLabel:String = pages.currentLabel;
//var thisLabelNum:String = thisLabel.replace("sct", "");
//var curNumber:Number = Number(thisLabelNum);
//var prevNum:Number = curNumber - 1;
//pages.gotoAndStop("sct" + prevNum);
//}
function handleKeyDown(keyEvent:KeyboardEvent)
{
if (keyEvent.keyCode == keyCodeToListenForDown)
{
keySinglePress = true;
if (waitingForDoublePress){
keyDoublePress = true;}
waitingForDoublePress = true;
setTimeout(function() {
waitingForDoublePress = false;
keyDoublePress = false;
}, timeToWaitForDoublePress);
}
if (keyDoublePress){
trace('You logged a double press!')}
else if (keySinglePress) {
trace ('You logged a single press!');
}
if (keyEvent.keyCode == keyCodeToListenForUp)
{
keySinglePress = true;
if (waitingForDoublePress){
keyDoublePress = true;}
waitingForDoublePress = true;
setTimeout(function() {
waitingForDoublePress = false;
keyDoublePress = false;
}, timeToWaitForDoublePress);
}
if (keyDoublePress){
trace('You logged a double press!')}
else if (keySinglePress) {
trace ('You logged a single press!');
}
if (keyEvent.keyCode == keyCodeToListenForLeft)
{
keySinglePress = true;
if (waitingForDoublePress){
keyDoublePress = true;}
waitingForDoublePress = true;
setTimeout(function() {
waitingForDoublePress = false;
keyDoublePress = false;
}, timeToWaitForDoublePress);
}
if (keyDoublePress){
trace('You logged a double press!')}
else if (keySinglePress) {
trace ('You logged a single press!');
}
if (keyEvent.keyCode == keyCodeToListenForRight)
{
keySinglePress = true;
if (waitingForDoublePress){
keyDoublePress = true;}
waitingForDoublePress = true;
setTimeout(function() {
waitingForDoublePress = false;
keyDoublePress = false;
}, timeToWaitForDoublePress);
}
if (keyDoublePress){
trace('You logged a double press!')}
else if (keySinglePress) {
trace ('You logged a single press!');
}
}
//hide_text.addEventListener(MouseEvent.CLICK, stopMovie);
function ppState(event:MouseEvent){
if(pp){
stop();
hide_text.gotoAndStop(3);
//hide_text.gotoAndStop('stopText');
pp = false;
}else{
//hide_text.addEventListener(MouseEvent.CLICK, playMovie);
play();
hide_text.gotoAndStop(1);
//hide_text.gotoAndStop('playText');
pp = true;
}
}
hide_text.addEventListener(MouseEvent.CLICK, ppState);
function togglePlay(event:MouseEvent):void
{
(!played)? played = true : played = false;
(played)? myChannel=mySound.play():SoundMixer.stopAll();
(played)? toggle_btn.gotoAndStop(2):toggle_btn.gotoAndStop(1);
myChannel.addEventListener(Event.SOUND_COMPLETE,soundCompleted);
}
function soundCompleted(event:Event):void
{
played = false;
toggle_btn.gotoAndStop(1);
}
function nextLevel():void
{
currentLevel++;
trace("Next Level: " + currentLevel);
if(currentLevel == 2)
{
gotoLevel2();
}
}
function gotoLevel2():void
{
//gotoAndStop(2);
//frontenvironment2.gotoAndStop;
backenvironment.gotoAndStop(2);
frontenvironment.gotoAndStop(2);
gotoAndStop(frontenvironment2);
//scrollx = 0;
//scrolly = 0;
//backenvironment.gotoAndStop
//backenvironment.gotoAndStop
}
function gameLoop(loopEvent:Event):void
{
if(rightPressed && mc.currentLabel !="walkingRight" && upPressed == false && downPressed == false)
{
mc.gotoAndStop("walkingRight");
}
if(rightPressed && mc.currentLabel =="walkingRight")
{
if(mc.x < 800)
{
mc.x += mcSpeed;
}
else if (backenvironment.x > -650)
{
backenvironment.x -= mcSpeed;
frontenvironment.x -= mcSpeed;
}
}
if(keyDoublePress && mc.currentLabel =="walkingRight")
{
if(mc.x < 800)
{
mc.x += mcSpeed * 1.05;
}
else if (backenvironment.x > -650)
{
backenvironment.x -= mcSpeed;
frontenvironment.x -= mcSpeed;
}
}
if(leftPressed && mc.currentLabel !="walkingLeft" && upPressed == false && downPressed == false)
{
mc.gotoAndStop("walkingLeft");
}
if(leftPressed && mc.currentLabel =="walkingLeft")
{
if(mc.x > 200)
{
mc.x -= mcSpeed;
}
else if (backenvironment.x < -130)
{
backenvironment.x += mcSpeed;
frontenvironment.x += mcSpeed;
}
}
if(keyDoublePress && mc.currentLabel =="walkingLeft")
{
if(mc.x > 200)
{
mc.x -= mcSpeed * 1.05;
}
else if (backenvironment.x < -130)
{
backenvironment.x += mcSpeed;
frontenvironment.x += mcSpeed;
}
}
if(upPressed && mc.currentLabel != "walkingUp" && rightPressed == false && leftPressed == false)
{
mc.gotoAndStop("walkingUp");
}
if(upPressed && mc.currentLabel == "walkingUp")
{
if(mc.y > 200)
{
mc.y -= mcSpeed;10
}
else if (backenvironment.y < -10)
{
backenvironment.y += mcSpeed;
frontenvironment.y += mcSpeed;
}
}
if(keyDoublePress && mc.currentLabel =="walkingUp")
{
if(mc.y > 200)
{
mc.y -= mcSpeed * 1.05;10
}
else if (backenvironment.y < -10)
{
backenvironment.y += mcSpeed;
frontenvironment.y += mcSpeed;
}
}
if(downPressed && mc.currentLabel != "walkingDown" && rightPressed == false && leftPressed == false)
{
mc.gotoAndStop("walkingDown");
}
if (downPressed && mc.currentLabel == "walkingDown")
{
if(mc.y < 485)
{
mc.y += mcSpeed;
}
else if (backenvironment.y > -577)
{
backenvironment.y -= mcSpeed;
frontenvironment.y -= mcSpeed;
}
}
if (keyDoublePress && mc.currentLabel == "walkingDown")
{
if(mc.y < 485)
{
mc.y += (mcSpeed * 1.05);
}
else if (backenvironment.y > -577)
{
backenvironment.y -= mcSpeed;
frontenvironment.y -= mcSpeed;
}
}
//add more walking functionality here if needed (ex: multi-directional).
}
//Roshi's_Brain:
function onRoshi(e:Event):void
{
if(mc.hitTestObject(backenvironment.Roshi))
{
myText.text = "Master Roshi: R- Red? Oh dear... this is bad. I've barely introduced myself. I'm Master Roshi, headmaster of the Turtle School of Martial Arts!";
}
else
{
myText.text = "Master Roshi: Red... You have to find Goku. My back, it's delicate!";
roshiTimer ++;
if (roshiTimer > roshiDuration)
{
roshiDuration = 10 + Math.random() * 25;
roshiTimer = 0;
while (backenvironment.Roshi.currentLabel == RF[roshiFacing])
{
roshiFacing = Math.random() * 4;
}
backenvironment.Roshi.gotoAndStop(RF[roshiFacing]);
}
backenvironment.Roshi.x += RX[roshiFacing] * roshiSpeed;
backenvironment.Roshi.y += RY[roshiFacing] * roshiSpeed;
}
if(kameKeyCollected == false)
{ // if we still haven't collected the key
if(mc.hitTestObject(backenvironment.kameKey))
{ // and if the player collides with the key
backenvironment.kameKey.visible = false; // hide the key from view
kameKeyCollected = true; // set our Boolean to true
}
}
if(kameHouseOpen == false)
{ // if the door hasn't been opened yet
if(kameKeyCollected == true)
{ // and if the player has already collected the key
if(mc.hitTestObject(backenvironment.kameHouse))
{ // check if the door and the player are touching
// if all of these conditions are met...
backenvironment.kameHouse.gotoAndStop(2); // ...switch the door's image to its 2nd frame
kameHouseOpen = true; // ...set the variable to true
}
}
}
}
function keyDownHandler(keyEvent:KeyboardEvent):void
{
if(keyEvent.keyCode == Keyboard.RIGHT)
{
rightPressed = true;
}
else if(keyEvent.keyCode == Keyboard.LEFT)
{
leftPressed = true;
}
else if(keyEvent.keyCode == Keyboard.DOWN)
{
downPressed = true;
}
else if(keyEvent.keyCode == Keyboard.UP)
{
upPressed = true;
if(kameHouseOpen && mc.hitTestObject(backenvironment.kameHouse.kameHouseLocked))
{
nextLevel();
}
}
}
function keyUpHandler(keyEvent:KeyboardEvent):void
{
if(keyEvent.keyCode == Keyboard.RIGHT)
{
rightPressed = false;
mc.gotoAndStop("standingRight");
}
else if(keyEvent.keyCode == Keyboard.LEFT)
{
leftPressed = false;
mc.gotoAndStop("standingLeft");
}
else if (keyEvent.keyCode == Keyboard.DOWN)
{
downPressed = false;
mc.gotoAndStop("standingDown");
}
else if(keyEvent.keyCode == Keyboard.UP)
{
upPressed = false;
mc.gotoAndStop("standingUp");
}
}
Revised Code
///////////////////////////////////////////////////////////////////////////
///Dev Notes: Poke Ball Z (Ver. 0.3.8)//////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.Event;
import flash.display.Stage;
import flash.events.MouseEvent;
mc.gotoAndStop("standingRight");
toggle_btn.stop();
hide_text.stop();
stop();
//backenvironment.kamiHouse.stop();
var keyCodeToListenForDown = '40'; //downarrow key
var keyCodeToListenForUp = '38'; //uparrow key
var keyCodeToListenForLeft = '37'; //leftarrow key
var keyCodeToListenForRight = '39'; //rightarrow key
var keySinglePress:Boolean = false;
var keyDoublePress:Boolean = false;
var timeToWaitForDoublePress:Number = 300;
var waitingForDoublePress:Boolean = false;
var leftBumping:Boolean = false;
var rightBumping:Boolean = false;
var upBumping:Boolean = false;
var downBumping:Boolean = false;
var leftBumpPoint:Point = new Point(-30, -55);
var rightBumpPoint:Point = new Point(30, -55);
var upBumpPoint:Point = new Point(0, -120);
var downBumpPoint:Point = new Point(0, 0);
var pp:Boolean=true;
var played:Boolean=false;
var mySound:Sound = new MySound();
var myChannel:SoundChannel = new SoundChannel();
var rightPressed:Boolean = new Boolean(false);
var leftPressed:Boolean = new Boolean(false);
var upPressed:Boolean = new Boolean(false);
var downPressed:Boolean = new Boolean(false);
var mcSpeed:Number = 10;
var roshiTimer:int = 0;
var roshiDuration:int = 0;
var roshiFacing:int = 0;
var roshiSpeed:Number = 3
var RF:Array =
["roshiUpWalk", "roshiDownWalk",
"roshiLeftWalk", "roshiRightWalk",];
var RX:Array = [0, 0, -1, 1];
var RY:Array = [-1, 1, 0, 0];
var kameKeyCollected:Boolean = false;
var kameHouseOpen:Boolean = false;
var currentLevel:int = 1;
//kameHouse(2).prevBtn.addEventListener(MouseEvent.CLICK, prevSection);
addEventListener(Event.ENTER_FRAME, onRoshi);
toggle_btn.addEventListener(MouseEvent.CLICK, togglePlay);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
stage.addEventListener(Event.ENTER_FRAME, gameLoop);
stage.addEventListener(KeyboardEvent.KEY_DOWN, handleKeyDown);
//kameHouse(2).nextBtn.addEventListener(MouseEvent.CLICK, nextSection);
//function prevSection(event:MouseEvent):void
//{
//var thisLabel:String = pages.currentLabel;
//var thisLabelNum:String = thisLabel.replace("sct", "");
//var curNumber:Number = Number(thisLabelNum);
//var prevNum:Number = curNumber - 1;
//pages.gotoAndStop("sct" + prevNum);
//}
function handleKeyDown(keyEvent:KeyboardEvent)
{
if (keyEvent.keyCode == keyCodeToListenForDown)
{
keySinglePress = true;
if (waitingForDoublePress){
keyDoublePress = true;}
waitingForDoublePress = true;
setTimeout(function() {
waitingForDoublePress = false;
keyDoublePress = false;
}, timeToWaitForDoublePress);
}
if (keyDoublePress){
trace('You logged a double press!')}
else if (keySinglePress) {
trace ('You logged a single press!');
}
if (keyEvent.keyCode == keyCodeToListenForUp)
{
keySinglePress = true;
if (waitingForDoublePress){
keyDoublePress = true;}
waitingForDoublePress = true;
setTimeout(function() {
waitingForDoublePress = false;
keyDoublePress = false;
}, timeToWaitForDoublePress);
}
if (keyDoublePress){
trace('You logged a double press!')}
else if (keySinglePress) {
trace ('You logged a single press!');
}
if (keyEvent.keyCode == keyCodeToListenForLeft)
{
keySinglePress = true;
if (waitingForDoublePress){
keyDoublePress = true;}
waitingForDoublePress = true;
setTimeout(function() {
waitingForDoublePress = false;
keyDoublePress = false;
}, timeToWaitForDoublePress);
}
if (keyDoublePress){
trace('You logged a double press!')}
else if (keySinglePress) {
trace ('You logged a single press!');
}
if (keyEvent.keyCode == keyCodeToListenForRight)
{
keySinglePress = true;
if (waitingForDoublePress){
keyDoublePress = true;}
waitingForDoublePress = true;
setTimeout(function() {
waitingForDoublePress = false;
keyDoublePress = false;
}, timeToWaitForDoublePress);
}
if (keyDoublePress){
trace('You logged a double press!')}
else if (keySinglePress) {
trace ('You logged a single press!');
}
}
//hide_text.addEventListener(MouseEvent.CLICK, stopMovie);
function ppState(event:MouseEvent){
if(pp){
stop();
hide_text.gotoAndStop(3);
//hide_text.gotoAndStop('stopText');
pp = false;
}else{
//hide_text.addEventListener(MouseEvent.CLICK, playMovie);
play();
hide_text.gotoAndStop(1);
//hide_text.gotoAndStop('playText');
pp = true;
}
}
hide_text.addEventListener(MouseEvent.CLICK, ppState);
function togglePlay(event:MouseEvent):void
{
(!played)? played = true : played = false;
(played)? myChannel=mySound.play():SoundMixer.stopAll();
(played)? toggle_btn.gotoAndStop(2):toggle_btn.gotoAndStop(1);
myChannel.addEventListener(Event.SOUND_COMPLETE,soundCompleted);
}
function soundCompleted(event:Event):void
{
played = false;
toggle_btn.gotoAndStop(1);
}
function nextLevel():void
{
currentLevel++;
trace("Next Level: " + currentLevel);
if(currentLevel == 2)
{
gotoLevel2();
}
}
function gotoLevel2():void
{
//gotoAndStop(2);
//frontenvironment2.gotoAndStop;
backenvironment.gotoAndStop(2);
backenvironment.kameHouseOpen.gotoAndStop(1);
frontenvironment.gotoAndStop(2);
gotoAndStop(frontenvironment2);
//scrollx = 0;
//scrolly = 0;
//backenvironment.gotoAndStop
//backenvironment.gotoAndStop
}
function keyUpHandler(keyEvent:KeyboardEvent):void
{
if(keyEvent.keyCode == Keyboard.RIGHT)
{
rightPressed = false;
mc.gotoAndStop("standingRight");
}
else if(keyEvent.keyCode == Keyboard.LEFT)
{
leftPressed = false;
mc.gotoAndStop("standingLeft");
}
else if (keyEvent.keyCode == Keyboard.DOWN)
{
downPressed = false;
mc.gotoAndStop("standingDown");
}
else if(keyEvent.keyCode == Keyboard.UP)
{
upPressed = false;
mc.gotoAndStop("standingUp");
}
}
function keyDownHandler(keyEvent:KeyboardEvent):void
{
if(keyEvent.keyCode == Keyboard.RIGHT)
{
rightPressed = true;
}
else if(keyEvent.keyCode == Keyboard.LEFT)
{
leftPressed = true;
}
else if(keyEvent.keyCode == Keyboard.DOWN)
{
downPressed = true;
}
else if(keyEvent.keyCode == Keyboard.UP)
{
upPressed = true;
if(kameHouseOpen && mc.hitTestObject(backenvironment.kameHouse))
{
nextLevel();
}
}
}
function gameLoop(loopEvent:Event):void
{
if(rightPressed && mc.currentLabel !="walkingRight" && upPressed == false && downPressed == false)
{
mc.gotoAndStop("walkingRight");
}
if(rightPressed && mc.currentLabel =="walkingRight")
{
if(mc.x < 800)
{
mc.x += mcSpeed;
}
else if (backenvironment.x > -650)
{
backenvironment.x -= mcSpeed;
frontenvironment.x -= mcSpeed;
}
}
if(keyDoublePress && mc.currentLabel =="walkingRight")
{
if(mc.x < 800)
{
mc.x += mcSpeed * 1.05;
}
else if (backenvironment.x > -650)
{
backenvironment.x -= mcSpeed;
frontenvironment.x -= mcSpeed;
}
}
if(leftPressed && mc.currentLabel !="walkingLeft" && upPressed == false && downPressed == false)
{
mc.gotoAndStop("walkingLeft");
}
if(leftPressed && mc.currentLabel =="walkingLeft")
{
if(mc.x > 200)
{
mc.x -= mcSpeed;
}
else if (backenvironment.x < -130)
{
backenvironment.x += mcSpeed;
frontenvironment.x += mcSpeed;
}
}
if(keyDoublePress && mc.currentLabel =="walkingLeft")
{
if(mc.x > 200)
{
mc.x -= mcSpeed * 1.05;
}
else if (backenvironment.x < -130)
{
backenvironment.x += mcSpeed;
frontenvironment.x += mcSpeed;
}
}
if(upPressed && mc.currentLabel != "walkingUp" && rightPressed == false && leftPressed == false)
{
mc.gotoAndStop("walkingUp");
}
if(upPressed && mc.currentLabel == "walkingUp")
{
if(mc.y > 200)
{
mc.y -= mcSpeed;10
}
else if (backenvironment.y < -10)
{
backenvironment.y += mcSpeed;
frontenvironment.y += mcSpeed;
}
}
if(keyDoublePress && mc.currentLabel =="walkingUp")
{
if(mc.y > 200)
{
mc.y -= mcSpeed * 1.05;10
}
else if (backenvironment.y < -10)
{
backenvironment.y += mcSpeed;
frontenvironment.y += mcSpeed;
}
}
if(downPressed && mc.currentLabel != "walkingDown" && rightPressed == false && leftPressed == false)
{
mc.gotoAndStop("walkingDown");
}
if (downPressed && mc.currentLabel == "walkingDown")
{
if(mc.y < 485)
{
mc.y += mcSpeed;
}
else if (backenvironment.y > -577)
{
backenvironment.y -= mcSpeed;
frontenvironment.y -= mcSpeed;
}
}
if (keyDoublePress && mc.currentLabel == "walkingDown")
{
if(mc.y < 485)
{
mc.y += (mcSpeed * 1.05);
}
else if (backenvironment.y > -577)
{
backenvironment.y -= mcSpeed;
frontenvironment.y -= mcSpeed;
}
}
//add more walking functionality here if needed (ex: multi-directional).
}
//Roshi's_Brain:
function onRoshi(e:Event):void
{
if(mc.hitTestObject(backenvironment.Roshi))
{
myText.text = "Master Roshi: R- Red? Oh dear... this is bad. I've barely introduced myself. I'm Master Roshi, headmaster of the Turtle School of Martial Arts!";
}
else
{
myText.text = "Master Roshi: Red... You have to find Goku. My back, it's delicate!";
roshiTimer ++;
if (roshiTimer > roshiDuration)
{
roshiDuration = 10 + Math.random() * 25;
roshiTimer = 0;
while (backenvironment.Roshi.currentLabel == RF[roshiFacing])
{
roshiFacing = Math.random() * 4;
}
backenvironment.Roshi.gotoAndStop(RF[roshiFacing]);
}
backenvironment.Roshi.x += RX[roshiFacing] * roshiSpeed;
backenvironment.Roshi.y += RY[roshiFacing] * roshiSpeed;
}
if(kameKeyCollected == false)
{ // if we still haven't collected the key
if(mc.hitTestObject(backenvironment.kameKey))
{ // and if the player collides with the key
backenvironment.kameKey.visible = false; // hide the key from view
kameKeyCollected = true; // set our Boolean to true
}
}
if(kameHouseOpen == false)
{ // if the door hasn't been opened yet
if(kameKeyCollected == true)
{ // and if the player has already collected the key
if(mc.hitTestObject(backenvironment.kameHouse))
{ // check if the door and the player are touching
// if all of these conditions are met...
backenvironment.kameHouseOpen.gotoAndStop(1); // ...switch the door's image to its 2nd frame
kameHouseOpen = true; // ...set the variable to true
}
}
}
}
//function nextSection(event:MouseEvent):void
//{
//var thisLabel:String = currentLabel; //gets current frame label as string
//var thisLabelNum:String = thisLabel.replace("sct", ""); //cuts the leading letters off of the number
//var curNumber:Number = Number(thisLabelNum); //converts that string numbers to a real number
//if (curNumber < 5)
//{
//var nextNum:Number = curNumber + 1;
//gotoAndStop("scl" + nextNum);
//}
//}
New Error Code
You logged a single press!
Next Level: 2
ArgumentError: Error #2109: Frame label null not found in scene Scene 1.
at flash.display::MovieClip/gotoAndStop()
at pokemongameexperiment/gotoLevel2()
at pokemongameexperiment/nextLevel()
at pokemongameexperiment/keyDownHandler()
You logged a single press!
You logged a single press!
You logged a single press!
You logged a single press!
Next Level: 3
You logged a single press! //etc.
*Newgrounds Link to test the game as is...
https://www.newgrounds.com/dump/item/49a43c79e613ec32e547dc1ae8851978

ActionScript 3 Snake

Im trying to get a two player version of Snake running but i am having trouble getting the second snake to work, player 1 plays with w,a,s and d while player 2 uses the arrow keys. Player 1 with w,a,s and d is working player 2 with the arrows does not. Instead the arrow keys control player 1 as well as w,a,s and d.I think it has to do with the onEnterFrame function but i've been starring at it for days and i cannot see anything. Im fairly new to ActionScript as well so some hints to point me in the right direction is all i need, Thanks!
package{
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.Event; //used for ENTER_FRAME event
public class Main extends MovieClip{
const speed:int = 5;//speed of the snake
var vx:int;
var vy:int;
var gFood:Food;
var gFood2:Food2;
var head:SnakePart;
var head2:SnakePart2;
var SnakeDirection:String;
var Snake2Direction:String;
var snake:Array;
var snake2:Array;
public function Main(){
init();
}
function init():void {
//Initialize everything!
vx = 1; vy = 0;
snake = new Array();
snake2 = new Array();
SnakeDirection = "";
Snake2Direction = "";
//add food to the stage
addFood();
addFood2();
//add snakes head to the stage
head = new SnakePart();
head.x = stage.stageWidth/2;
head.y = stage.stageHeight/2;
snake.push(head);
addChild(head);
head2 = new SnakePart2();
head2.x = stage.stageWidth/14;
head2.y = stage.stageHeight/25;
snake2.push(head2);
addChild(head2);
stage.addEventListener(KeyboardEvent.KEY_UP , onKeyUp);
stage.addEventListener(KeyboardEvent.KEY_DOWN , onKeyDown);
addEventListener(Event.ENTER_FRAME , onEnterFrame);
//ENTER_FRAME listener is attached to main class and not to the stage directly
}
//This function will add food to the stage
function addFood():void {
gFood = new Food();
gFood.x = 50 + Math.random()*(stage.stageWidth-100);
gFood.y = 50 + Math.random()*(stage.stageHeight-100);
addChild(gFood);
}
function addFood2():void {
gFood2 = new Food2();
gFood2.x = 50 + Math.random()*(stage.stageWidth-100);
gFood2.y = 50 + Math.random()*(stage.stageHeight-100);
addChild(gFood2);
}
//this function will reset the game
function reset():void {
removeChild(gFood);
addFood();
head.x = stage.stageWidth/2;
head.y = stage.stageHeight/2;
vx = 1;vy = 0;
removeChild(gFood2);
addFood2();
head.x = stage.stageWidth/4;
head.y = stage.stageHeight/4;
vx = 1;vy = 0;
for(var i = snake.length-1;i>0;--i){
removeChild(snake[i]);
snake.splice(i,1);
}
}
function onKeyDown(event : KeyboardEvent) : void {
//handle player 1
if (event.keyCode == Keyboard.A) {
SnakeDirection = "a";
} else if (event.keyCode == Keyboard.D) {
SnakeDirection = "d";
} else if (event.keyCode == Keyboard.W) {
SnakeDirection = "w";
} else if (event.keyCode == Keyboard.S) {
SnakeDirection = "s";
}
//handle player 2
if (event.keyCode == Keyboard.LEFT) {
Snake2Direction = "left";
} else if (event.keyCode == Keyboard.RIGHT) {
Snake2Direction = "right";
} else if (event.keyCode == Keyboard.UP) {
Snake2Direction = "up";
} else if (event.keyCode == Keyboard.DOWN) {
Snake2Direction = "down";
}
}
function onKeyUp(event : KeyboardEvent) : void {
//handle player 1
if (event.keyCode == Keyboard.A || event.keyCode == Keyboard.D || event.keyCode == Keyboard.W || event.keyCode == Keyboard.S) {
SnakeDirection = "";
}
//handle player 2
if (event.keyCode == Keyboard.LEFT ||event.keyCode == Keyboard.RIGHT || event.keyCode == Keyboard.UP || event.keyCode == Keyboard.DOWN) {
Snake2Direction = "";
}
}
function onEnterFrame(event:Event):void {
//setting direction of velocity
if(SnakeDirection == "a" && vx != 1) {
vx = -1;
vy = 0;
}else if(SnakeDirection == "d" && vx != -1) {
vx = 1;
vy = 0;
}else if(SnakeDirection == "w" && vy != 1) {
vx = 0;
vy = -1;
}else if(SnakeDirection == "s" && vy != -1) {
vx = 0;
vy = 1;
}
//setting direction of velocity
if(Snake2Direction == "left" && vx != 1) {
vx = -1;
vy = 0;
}else if(Snake2Direction == "right" && vx != -1) {
vx = 1;
vy = 0;
}else if(Snake2Direction == "up" && vy != 1) {
vx = 0;
vy = -1;
}else if(Snake2Direction == "down" && vy != -1) {
vx = 0;
vy = 1;
}
//collison with stage
if(head.x - head.width/2 <= 0){
reset();
}
if(head.x + head.width/2 >= stage.stageWidth){
reset();
}
if(head.y - head.height/2 <= 0){
reset();
}
if(head.y + head.height/2 >= stage.stageHeight){
reset();
}
//move body of the snake
for(var i = snake.length-1;i>0;--i){
snake[i].x = snake[i-1].x;
snake[i].y = snake[i-1].y;
}
for(var i = snake2.length-1;i>0;--i){
snake2[i].x = snake2[i-1].x;
snake2[i].y = snake2[i-1].y;
}
//changing the position of snake's head
head.x += vx*speed;
head.y += vy*speed;
//collision with tail
for(var i = snake.length-1;i>=1;--i){
if(snake[0].x == snake[i].x && snake[0].y == snake[i].y){
reset();
break;
}
}
for(var i = snake2.length-1;i>=1;--i){
if(snake2[0].x == snake2[i].x && snake2[0].y == snake2[i].y){
reset();
break;
}
}
//collision with food player 1
if(head.hitTestObject(gFood)){
removeChild(gFood);
addFood();
var bodyPart = new SnakePart();
bodyPart.x = snake[snake.length - 1].x;
bodyPart.y = snake[snake.length - 1].y;
snake.push(bodyPart);
addChild(bodyPart);
}
if(head.hitTestObject(gFood2)){
removeChild(gFood2);
addFood2();
var bodyPart = new SnakePart();
bodyPart.x = snake[snake.length - 1].x;
bodyPart.y = snake[snake.length - 1].y;
snake.push(bodyPart);
addChild(bodyPart);
}
//collision with food player 2
if(head.hitTestObject(gFood)){
removeChild(gFood);
addFood();
var bodyPart = new SnakePart2();
bodyPart.x = snake2[snake2.length - 1].x;
bodyPart.y = snake2[snake2.length - 1].y;
snake2.push(bodyPart);
addChild(bodyPart);
}
if(head.hitTestObject(gFood2)){
removeChild(gFood2);
addFood2();
var bodyPart = new SnakePart2();
bodyPart.x = snake2[snake2.length - 1].x;
bodyPart.y = snake2[snake2.length - 1].y;
snake2.push(bodyPart);
addChild(bodyPart);
}
}
}
}
First,let me explain your mistakes in this code:
1.You have the same vx and vy for both snakes !! this means both snakes should go parallel and to the same direction !!
2.and problem 1 won't happen because you set head.x and y but not head2 for the other snake!
Just for being careless... :)
so:
1.add variables vx2 and vy2 for the poor second snake !
2.replace the second setting direction of velocity with this:
if(Snake2Direction == "left" && vx2 != 1) {
vx2 = -1;
vy2 = 0;
}else if(Snake2Direction == "right" && vx2 != -1) {
vx2 = 1;
vy2 = 0;
}else if(Snake2Direction == "up" && vy2 != 1) {
vx2 = 0;
vy2 = -1;
}else if(Snake2Direction == "down" && vy2 != -1) {
vx2 = 0;
vy2 = 1;
}
3.do anything you left for the second snake.(head2.x and y,collision for second snake, etc)
I  H☺P E  this helps !

actionscript break if statement to check next one

I'm making a bot for a simple tic tac toe game. Here is the problem, at botCheck function, when row 0 col 0 and row 0 col 1 is "O", then the "X" appear at the row 0 col 2, and when I tried to make another combination of "O" (ex. row 0 col 0 and row 1 col 1), it should check at different if statement, but my code seems to still check only at the first if statement which will keep tracing ("D") and stuck at that part.
So here is the question, at else{trace("D");} , is there any code that I can replace with to skip the first if statement and go to the second one so it can check for the other combinations of "O" ?
P.S. I've tried to use continue; but it only goes to the next loop and still stuck at the first if statement.
Thanks!
package
{
public class Bot
{
private var n:int = 0;
private var rndm:int;
private var v:int;//vertical
private var h:int;//horizontal
private var moving:Boolean = false;;
private var _main:Main;
public function Bot(main:Main):void
{
_main = main;
}
private function randomNumber(min:Number, max:Number):Number
{
return Math.floor(Math.random()*(1+max-min)+min);
}
public function botMove():void
{
botCheck();
if(n == 0 && moving == false)
{
rndm = randomNumber(0,2);
v = rndm;
rndm = randomNumber(0,2);
h = rndm;
if(_main.squareArray[v][h] == 0)
{
_main.squareArray[v][h] = 1;
_main.xoArray[v][h].push(_main.xo);
moving = true;
fillX();
n = 0;
_main.xo = "O";
}
else
{
botMove();
}
}
if(n == 1 && moving == false)
{
if(_main.squareArray[v][h] == 0)
{
_main.squareArray[v][h] = 1;
_main.xoArray[v][h].push(_main.xo);
moving = true;
fillX();
n = 0;
_main.xo = "O";
}
}
}
private function fillX():void
{
_main.x_ = new X ;
_main.xoContainer.addChild(_main.x_);
_main.x_.x = _main.gameWidth / _main.lebar *(1+(h))+ _main.gameWidth/(_main.lebar*4);
_main.x_.y = _main.gameHeight / _main.panjang * (1+(v))+_main.gameHeight/(_main.panjang*4);
_main.x_.width = _main.square.width / 2;
_main.x_.height = _main.square.height / 2;
}
private function botCheck():void
{
for(var a:int = 0; a<_main.panjang;a++)
{
if(n != 0)
{
break;
}
for(var b:int = 0;b<_main.lebar;b++)
{
if(_main.xoArray[a][b]=="O" && _main.xoArray[a][b+1] == "O")
{
if(b+2 < _main.lebar && _main.xoArray[a][b+2] == 0)
{
n = 1;
v = a;
h = b+2;
moving = false;
break;
}
else if(_main.xoArray[a][b-1] == 0)
{
n = 1;
v = a;
h = b-1;
moving = false;
break;
}
else
{
trace("D");
}
}
else if(_main.xoArray[a][b] == "O" && _main.xoArray[a+1][b] =="O")
{
if(a+2 < _main.panjang && _main.xoArray[a+2][b] == 0)
{
n = 1;
v = a+2;
h = b;
moving = false;
break;
}
else if(a != 0)
{
if(_main.xoArray[a-1][b] == 0)
{
n = 1;
v = a-1;
h = b;
moving = false;
break;
}
}
else
{
}
}
else if(_main.xoArray[a][b]=="O" && _main.xoArray[a+1][b+1] == "O")
{trace("B");
if(a+2 < _main.panjang && b+2 < _main.lebar && _main.xoArray[a+2][b+2] == 0)
{
n = 1;
v = a+2;
h = b+2;
moving = false;
break;
}
else if(a != 0)
{
if(_main.xoArray[a-1][b-1] == 0)
{
n = 1;
v = a-1;
h = b-1;
moving = false;
break;
}
}
else
{
}
}
else if(_main.xoArray[a][b+2]=="O" && _main.xoArray[a+1][b+1] == "O")
{trace("A");
if(a+2 < _main.lebar && _main.xoArray[a+2][b] == 0)
{
n = 1;
v = a+2;
h = b;
moving = false;
break;
}
}
else if(_main.xoArray[a][b] == "O" && _main.xoArray[a+1][b-1] == "O")
{
if(a != 0 && b+1 < _main.lebar && _main.xoArray[a-1][b+1] == 0)
{
n = 1;
v = a-1;
h = b+1;
moving = false;
break;
}
}
else
{
n = 0;
moving = false;
}
}
}
}
}
}
If you would like to check through all the if statements within the for loop, simply remove the "else"s from the other if statements.
Thus, your first if statement is fine, but the next if statement would go from
else if(_main.xoArray[a][b] == "O" && _main.xoArray[a+1][b] =="O")
to simply
if(_main.xoArray[a][b] == "O" && _main.xoArray[a+1][b] =="O")
(just omitting the else).
Repeat that for all of the other outermost "else if"'s in your loop.
Now, I see at the bottom you have a final "else" that sets n to 0 and moving to false. If you make the changes listed above, you may remove that else block, and instead put those statements in the else block (n = 0; moving = false) at the very beginning of the for loop. Therefore, unless any of the if statements are triggered, n will equal 0 and moving will equal false, which is the intended result.
You can also get rid of all of the empty else {} blocks within the for loop; they don't contribute anything anyway. Let me know if you have any questions :)

Argument error 1063 in AS3

so I have been working on a game called rock scissors paper lizard spock.
I got this error:
ArgumentError: Error #1063: Argument count mismatch on FlashGame_fla::MainTimeline/backtoBanana(). Expected 0, got 1.
this is my main code:
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.text.TextFormat;
rulesButton.addEventListener(MouseEvent.CLICK, toggleRule);
gameRules.addEventListener(MouseEvent.CLICK, toggleRule);
gameRules.visible = false;
gameRules.buttonMode = true;
function toggleRule(evt:MouseEvent):void
{
gameRules.visible = ! gameRules.visible;
}
menuButton.addEventListener(MouseEvent.CLICK, Click_backtoMain);
function Click_backtoMain(event:MouseEvent):void
{
gotoAndStop(213);
}
var isRolling:Boolean = false; //defalt is "false"
var pDieVal:int = 0;
var gDieVal:int = 0;
var pScore:int = 0;
var gScore:int = 0;
var pRolls:int = 0;
pDieMC.stop();
gDieMC.stop();
msgDisplay.text = "Click on the banana \nbutton to roll the die!";
pScoreDisplay.text = "0";
gScoreDisplay.text = "0";
rollButton.addEventListener(MouseEvent.CLICK, rollDie);
rollButton.addEventListener(MouseEvent.CLICK, dieRoll);
bananaWinLose.visible = false;
gameOverBananaMC.visible = false;
toMenuBtn.visible = false;
rollAgainBtn.visible = false;
function rollDie(evt:MouseEvent): void
{
if (isRolling)
{
//change flag to show die is NOT rolling
isRolling = false;
//change the label on the button to "BANANA!"
buttonDisplay.text = "BANANA!";
// STOP the dice animations
pDieVal= Math.ceil(Math.random() * pDieMC.totalFrames);
pDieMC.gotoAndStop(pDieVal);
gDieVal = Math.ceil(Math.random() * gDieMC.totalFrames);
gDieMC.gotoAndStop(gDieVal);
//set message display to an empty string
msgDisplay.text = "";
whoWon();
score();
}
else
{
//change flag to show die is rolling
isRolling = true;
//change the label on the button to "Stop"
buttonDisplay.text = "POPADAM!";
//PLAY the dice animations
pDieMC.play();
gDieMC.play();
//clear the message display
msgDisplay.text = "";
}
}
function whoWon():void
{
// is it a tie?
if (pDieVal == gDieVal)
{
msgDisplay.text = "Papoi?! It's a tie!";
}
else
{
// assume the player has lost
var hasPlayerWon:Boolean = false;
// determine if the player wins
if (pDieVal == 1 && (gDieVal == 4 || gDieVal == 5))
{
hasPlayerWon = true;
}
else if (pDieVal == 2 && (gDieVal == 1 || gDieVal == 5))
{
hasPlayerWon = true;
}
else if (pDieVal == 3 && (gDieVal == 1 || gDieVal == 2))
{
hasPlayerWon = true;
}
else if (pDieVal == 4 && (gDieVal == 3 || gDieVal == 2))
{
hasPlayerWon = true;
}
else if (pDieVal == 5 && (gDieVal == 3 || gDieVal == 4))
{
hasPlayerWon = true;
}
// display the results to the player
if (hasPlayerWon)
{
msgDisplay.text = "Yay! You win!";
}
else
{
msgDisplay.text = "Boo! Stuart wins!";
}
}
}
function dieRoll(evt:MouseEvent):void
{
trace("calculating pRolls");
if (pRolls == 20)
{
rpslsWon();
}
else
{
//increment pRolls by 1
pRolls++;
}
}
function score():void
{
//if player wins, his/her score increases by 1
if (msgDisplay.text == "Yay! You win!")
{
pScore = pScore + 1
pScoreDisplay.text = pScore.toString();
//if player loses, computer score increases by 1
}
else if (msgDisplay.text == "Boo! Stuart wins!")
{
gScore = gScore + 1
gScoreDisplay.text = gScore.toString();
//if neither wins, their scores remain unchange
}
else
{
pScore = pScore
gScore = gScore
}
}
function rpslsWon():void
{
gameOverBananaMC.visible = true;
bananaWinLose.visible = true;
bananaWinLose.text = "Kampai! You are totally bananas!! \nYour Score: " + pScore;
toMenuBtn.visible = true;
rollAgainBtn.visible = true;
toMenuBtn.addEventListener(MouseEvent.CLICK, Click_backtoMain);
rollAgainBtn.addEventListener(MouseEvent.CLICK, backtoBanana);
}
function backtoBanana():void
{
pScore = 0;
gotoAndStop("menu");
gotoAndStop("banana");
}
so the error appears in the function backtoBanana(), I can't seem to fix it.
Can someone help me? Thanks alot.
The callback function for the MouseEvent-listener will be passed a MouseEvent. Change
function backtoBanana():void
to
function backtoBanana(event:MouseEvent):void
just like your other callback function:
function Click_backtoMain(event:MouseEvent):void

SpaceBar Character issues in AS3

Im working on a virtual keyboard, but my space key is giving me some issues. When its pressed, it creates the space but it dosent physically show. When I hit a normal letter or number key, the space is now visible with the letter in front of it. The keyboard and space code are nearly identical.
function _keys(event:MouseEvent):void
{
textSelect.setSelection(textSelect.length, textSelect.length);
if(electoff.currentFrame == 2)
{
ajWidth(event);
}
if(terminalinput.currentFrame == 2)
{
TrWidth(null);
}
if (control == "on" && menu.visible == false )
{
if (! shift)
{
textSelect.appendText(letterButtonSmall[event.target.name]);
}
else
{
textSelect.appendText(letterButtonCaps[event.target.name]);
shift = false;
}
savedTxt = textSelect.text;
textSelect.setSelection(textSelect.length, textSelect.length);
if(textSelect.width <= 134.05 && textSelect == inputClips.inputTxt )
{
textSelect.autoSize = TextFieldAutoSize.LEFT;
textSelect.x = 1.2;
}
if (textSelect.width >= 134.05 && textSelect == inputClips.inputTxt)
{
textSelect.autoSize = TextFieldAutoSize.LEFT;
textSelect.x = 1.2 - (textSelect.width-134.05);
}
}
textSelect.setSelection(textSelect.length, textSelect.length);
if(electoff.currentFrame == 2)
{
ajWidth(event);
}
if(terminalinput.currentFrame == 2)
{
TrWidth(null);
}
focuser();
strehrows3();
_fontSize();
}
//spaces
key_space.addEventListener(MouseEvent.CLICK, spaceClickListener);
function spaceClickListener(e:MouseEvent):void
{
strehrows3();
textSelect.setSelection(textSelect.length,textSelect.length);
if (electoff.currentFrame == 2)
{
ajWidth(null);
}
if (terminalinput.currentFrame == 2)
{
TrWidth(null);
}
if (control == "on" && menu.visible == false )
{
if (! shift)
{
textSelect.appendText(" ");
}
else
{
textSelect.appendText(" ");
shift = false;
}
savedTxt = textSelect.text;
textSelect.setSelection(textSelect.length,textSelect.length);
if (textSelect.width <= 134.05 && textSelect == inputClips.inputTxt )
{
textSelect.autoSize = TextFieldAutoSize.LEFT;
textSelect.x = 1.2;
}
if (textSelect.width >= 134.05 && textSelect == inputClips.inputTxt)
{
textSelect.autoSize = TextFieldAutoSize.LEFT;
textSelect.x = 1.2-(textSelect.width-134.05);
}
}
textSelect.setSelection(textSelect.length,textSelect.length);
if (electoff.currentFrame == 2)
{
ajWidth(null);
}
if (terminalinput.currentFrame == 2)
{
TrWidth(null);
}
focuser();
strehrows3();
_fontSize();
}
Now I suspect the autoSize is responsible for my problems but I cant be sure.
Wondering on some creative fixes may work, Ive been contemplating using a blank symbol if there is such a thing.