Example of game colors in as3 - actionscript-3

How can you put names
Make sure if you put names on the text dynamic and the rest of the colors
This is a game about colors where the name of the color will appear on top and you have to try to guess which color you will have 3 lives
stop();
//var and text information
texto.text = "Vermelho";
var vidas = 3;
vida.text = "Vidas: " + vidas;
//buttons function to be pressed
vermelho.addEventListener(MouseEvent.CLICK, clicked);
Azul.addEventListener(MouseEvent.CLICK, clicked1);
Verde.addEventListener(MouseEvent.CLICK, clicked2);
Amarelo.addEventListener(MouseEvent.CLICK, clicked3);
Rosa.addEventListener(MouseEvent.CLICK, clicked4);
Laranja.addEventListener(MouseEvent.CLICK, clicked5);
//function to validate if the text is equal to the button
function clicked(clickInfo){
//If click on red go to blue
if(clickInfo.target == vermelho){
trace("Correto");
texto.text = "Azul";
vermelho.visible = false;
}else{
vidaa();
vida.text = "Vidas: " + vidas;
trace("Incorecto");
}
}
function clicked1(clickInfo){
//If click on blue go to green
if(clickInfo.target == Azul && texto.text == "Azul"){
trace("Correto");
texto.text = "Verde";
Azul.visible = false;
}else{
vidaa();
vida.text = "Vidas: " + vidas;
trace("Incorecto");
}
}
function clicked2(clickInfo){
//If click on green go to yellow
if(clickInfo.target == Verde && texto.text == "Verde"){
trace("Correto");
texto.text = "Amarelo";
Verde.visible = false;
}else{
vidaa();
vida.text = "Vidas: " + vidas;
trace("Incorecto");
}
}
function clicked3(clickInfo){
//If click on yellow go to pink
if(clickInfo.target == Amarelo && texto.text == "Amarelo"){
trace("Correto");
texto.text = "Rosa";
Amarelo.visible = false;
}else{
vidaa();
vida.text = "Vidas: " + vidas;
trace("Incorecto");
}
}
function clicked4(clickInfo){
//If click on pink go to orange
if(clickInfo.target == Rosa && texto.text == "Rosa"){
trace("Correto");
texto.text = "Laranja";
Rosa.visible = false;
}else{
vidaa();
vida.text = "Vidas: " + vidas;
trace("Incorecto");
}
}
function clicked5(clickInfo){
//If click on orange go to win the game
if(clickInfo.target == Laranja && texto.text == "Laranja"){
trace("Correto");
texto.text = "Parabéns";
Laranja.visible = false;
}else{
vidaa();
vida.text = "Vidas: " + vidas;
trace("Incorecto");
}
}
function vidaa(){
vidas -=1;
if (vidas == 0){
gotoAndStop(2);
}
}

Something like this (completely untested though :)
// all colors in the order they will appear
var colors:Array = ["Vermelho", "Azul", "Verde", "Amarelo"] // add all other colors here
// assign a name to each button that is exactly the same as in the colors array - on click you will read that name and see if it matching the current color
// I believe there is a way to set the name in the Flash IDE as well in the object properties, but I don't remember anymore
vermelho.name = "Vermelho";
vermelho.addEventListener(MouseEvent.CLICK, onClick);
vermelho.name = "Azul";
Azul.addEventListener(MouseEvent.CLICK, onClick);
Verde.name = "Verde";
Verde.addEventListener(MouseEvent.CLICK, onClick);
// current color index in the array (first color "Vermelho" is at position 0, we will start at -1 so the next color will be 0)
var currentIndex:int = -1;
// start the game, this will show the first color
showNextColor();
function onClick(event:MouseEvent)
{
// check if the button name matches the current color
if(event.target.name == colors[currentIndex])
{
trace("Correto");
event.target.visible = false;
showNextColor();
}
else
{
vidaa();
vida.text = "Vidas: " + vidas;
trace("Incorecto");
}
}
// gets the current color from the array and displays it
private function showNextColor()
{
// check if we have any colors left to show in the array
if(currentIndex < colors.length - 1)
{
// if yes increase the index and show next color
currentIndex++;
texto.text = colors[currentIndex];
}
else
{
// otherwise the user have guessed all colors, do something here
texto.text = "You are awesome!";
}
}

Related

as3 error: ReferenceError: Error #1069: Property keyCode not found on flash.display.Shape and there is no default value

I am following a tutorial on building a rhythm game in as3 here, and I am very new to the language. On running the swf, I get the following error in the output:
ReferenceError: Error #1069: Property keyCode not found on flash.display.Shape and there is no default value.
at source_fla::MainTimeline/makeLvl()[source_fla.MainTimeline::frame10:116]
I have tried some previous solutions posted to the same error, but I have not been able to resolve the issue.
Here is the source code:
stop();
stage.focus = stage;
//VARIABLES
//sTime is the current frame that is being played
//Once it reaches sTempo, then it will be reset
//and a note will be created
var sTime:int = 0;
//sTempo is how many frames it takes before
//a note is created. Because it's 12, and
//the frame rate is 24, it will take a half of a second
//for a note to be made
var sTempo:Number = 12;
//sNote is the current arrow of the level that is created
//0 makes no arrow
//1 makes a left arrow
//2 makes an up arrow
//3 makes a down arrow
//4 makes a right arrow
var sArrow:int = 0;
//arrowSpeed is how fast the arrow moves up the screen
var arrowSpeed:Number = 10;
//gameIsOver is whether the game's over
var gameIsOver:Boolean = false;
//the score variable
var score:int = 0;
//either perfect, great, nice, or good
var scoreString:String = '';
var combo:int = 0;
var mcHealth:Number = 0;
//Booleans checking if the arrows are touching the receptor
var touchLeft:Boolean = false;
var touchUp:Boolean = false;
var touchDown:Boolean = false;
var touchRight:Boolean = false;
function beginCode():void{
addEventListener(Event.ENTER_FRAME, makeLvl);
//make the level array longer
lvlArrayAll[lvlCurrent].push(0,0,0,0,0);
}
function makeLvl(e:Event):void{
//code here will create the level
if(sTime < sTempo){
//if the required time hasn't reached the limit
//then update the time
sTime ++;
} else {
//if the time has reached the limit
//then reset the time
sTime = 0;
//if an actual arrow can be made
if(lvlArrayAll[lvlCurrent][sArrow] != 0){
var currentArrow:MovieClip; //this will hold the current arrow
if(lvlArrayAll[lvlCurrent][sArrow] == 1){
//place a left note onto the stage
currentArrow = new arrowLeft();
//set the _x value of the note so that it is in the
//right place to touch the receptor
currentArrow.x = 105 ;
//set the note's y coordinate off of the stage
//so that the user can't see it when it appears
currentArrow.y = 0;
//setting the key that needs to be pressed
currentArrow.keyCode = 68;
addChild(currentArrow);//add it to stage
} else if(lvlArrayAll[lvlCurrent][sArrow] == 2){
//place an up note onto the stage
currentArrow = new arrowUp();
currentArrow.x = 230;
currentArrow.y = 0;
currentArrow.keyCode = 70;
addChild(currentArrow);
} else if(lvlArrayAll[lvlCurrent][sArrow] == 3){
//place a down note onto the stage
currentArrow = new arrowDown();
currentArrow.x = 355;
currentArrow.y = 0;
currentArrow.keyCode = 74;
addChild(currentArrow);
} else if(lvlArrayAll[lvlCurrent][sArrow] == 4){
//place a right note onto the stage
currentArrow = new arrowRight();
currentArrow.x = 480;
currentArrow.y = 0;
currentArrow.keyCode = 75;
addChild(currentArrow);
}
}
//get the next arrow if it the song isn't finished
if(sArrow < lvlArrayAll[lvlCurrent].length){
sArrow ++;
} else {
//if the song is finished, then reset the game
gotoAndStop('win');
gameIsOver = true;
//then remove this enter_frame listener
removeEventListener(Event.ENTER_FRAME, makeLvl);
}
}
//checking if mcReceptor is touching any arrows
//first we reset the variables we got last time just in case they aren't true anymore
touchLeft = false;
touchUp = false;
touchDown = false;
touchRight = false;
//this for loop will be used for the hit testing
for(var i:int = 0;i<numChildren;i++){
var target:Object = getChildAt(i);
if(target.keyCode != null && target.hitTestObject(mcReceptor)){//if the object is an arrow and the receptor is touching it
if(target.keyCode == 68){//if left arrow
touchLeft = true;
} else if(target.keyCode == 70){//if up arrow
touchUp = true;
} else if(target.keyCode == 74){//if down arrow
touchDown = true;
} else if(target.keyCode == 75){//if right arrow
touchRight = true;
}
}
}
//changing the score text
mcTxt.txtScore.text = 'Score: '+score;
mcTxt.txtCombo.text = 'Combo: '+combo;
mcTxt.txtScoreString.text = scoreString;
}
//this function will change the health depending on how much health change
//it needs, positive or negative
function changeHealth(healthDiff:Number):void{
healthDiff = 100;//only changes in percentages
//checking if the health is already at it's full
//or will be full after this hit
if(mcHealth + healthDiff >= 100){
mcHealth = 100;
} else if(mcHealth + healthDiff <= 0){
//checking if the health will be equal or below 0
gotoAndStop('lose');
gameIsOver = true;
removeEventListener(Event.ENTER_FRAME, makeLvl);
} else {
//if there are no problems
mcHealth += healthDiff;
}
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, checkKeys);
function checkKeys(event:KeyboardEvent):void{
//if the left key is down and no left arrows are touching the receptor
if(event.keyCode == 68 && !touchLeft){
changeHealth(-10);//make the health go down
combo = 0;
scoreString = 'Bad';
} else if(event.keyCode == 70 && !touchUp){//and so on
changeHealth(-10);
combo = 0;
scoreString = 'Bad';
} else if(event.keyCode == 74 && !touchDown){
changeHealth(-10);
combo = 0;
scoreString = 'Bad';
} else if(event.keyCode == 75 && !touchRight){
changeHealth(-10);
combo = 0;
scoreString = 'Bad';
}
}
beginCode();
Can someone tell me why this error is occurring? Thank you.
While iterating numChildren, it's necessary to check the object is an arrow or not.
Maybe you can distinguish it by having keyCode property or not.
Try to use Object.hasOwnProperty(property name) method.
if (target.hasOwnProperty("keyCode")){
// access target.keyCode here.
}
Or this might works too.
if (target is arrowLeft || target is arrowUp || target is arrowDown || target is arrowRight){
// the target should be arrow class
// access target.keyCode here.
}
//this for loop will be used for the hit testing
for(var i:int = 0;i<numChildren;i++){
var target:Object = getChildAt(i);
if (target.hasOwnProperty("keyCode")){ // If the object is an arrow, that object should has keyCode property.
if(target.keyCode != null && target.hitTestObject(mcReceptor)){//if the object is an arrow and the receptor is touching it
if(target.keyCode == 68){//if left arrow
touchLeft = true;
} else if(target.keyCode == 70){//if up arrow
touchUp = true;
} else if(target.keyCode == 74){//if down arrow
touchDown = true;
} else if(target.keyCode == 75){//if right arrow
touchRight = true;
}
}
}
}

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

AS3/AIR check if TouchPhase.ENDED is over object

I am developing an iOS/Android app that requires slide out panels and touch events. Is it possible to get if a user touches an object but then releases off the object?
var touch:Touch = e.getTouch(this);
if(touch.phase == TouchPhase.BEGAN)
{
trace("Tab toggle begin");
}
if(touch.phase == TouchPhase.ENDED)
{
//If not over object do something
}
Yes it is.
This code should help you. It may be more than you need but it works. :)
Taken from Adobe website:
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
var mySprite:Sprite = new Sprite();
mySprite.graphics.beginFill(0x336699);
mySprite.graphics.drawRect(0,0,40,40);
addChild(mySprite);
var myTextField:TextField = new TextField();
addChild(myTextField);
myTextField.width = 200;
myTextField.height = 20;
var touchMoveID:int = 0;
mySprite.addEventListener(TouchEvent.TOUCH_BEGIN, onTouchBegin);
function onTouchBegin(event:TouchEvent) {
if(touchMoveID != 0) {
myTextField.text = "already moving. ignoring new touch";
return;
}
touchMoveID = event.touchPointID;
myTextField.text = "touch begin" + event.touchPointID;
stage.addEventListener(TouchEvent.TOUCH_MOVE, onTouchMove);
stage.addEventListener(TouchEvent.TOUCH_END, onTouchEnd);
}
function onTouchMove(event:TouchEvent) {
if(event.touchPointID != touchMoveID) {
myTextField.text = "ignoring unrelated touch";
return;
}
mySprite.x = event.stageX;
mySprite.y = event.stageY;
myTextField.text = "touch move" + event.touchPointID;
}
function onTouchEnd(event:TouchEvent) {
if(event.touchPointID != touchMoveID) {
myTextField.text = "ignoring unrelated touch end";
return;
}
touchMoveID = 0;
stage.removeEventListener(TouchEvent.TOUCH_MOVE, onTouchMove);
stage.removeEventListener(TouchEvent.TOUCH_END, onTouchEnd);
myTextField.text = "touch end" + event.touchPointID;
}

AS3 Appending text at Caret

Working on a virtual keyboard using flash pro, and im somewhat stuck.
I have a way to control the carat so you can scroll through the text field but I'd like to be able to punch in letters exactly where the carat is using code.
Below is my keyboard controls
// keyboard controls
for (var i=0; i<lettersSmall.length; i++)
{
this["key_" + lettersSmall.charAt(i)].addEventListener(MouseEvent.MOUSE_UP,_keys);
letterButtonSmall["key_" + lettersSmall.charAt(i)] = lettersSmall.charAt(i);
letterButtonCaps["key_" + lettersSmall.charAt(i)] = lettersCaps.charAt(i);
}
function _keys(event:MouseEvent):void
{
curTextPos = textSelect.caretIndex;
strehrows3();
stage.focus = textSelect;
textSelect.setSelection(curTextPos,curTextPos);
if (electoff.currentFrame == 2)
{
ajWidth(event);
}
if (terminalinput.currentFrame == 2)
{
TrWidth(null);
}
if (control == "on" && menu1.visible == false )
{
if (! shift)
{
textSelect.appendText(letterButtonSmall[event.target.name]);
inputMaxWidth = textSelect.width;
}
else
{
textSelect.appendText(letterButtonCaps[event.target.name]);
shift = false;
inputMaxWidth = textSelect.width;
}
savedTxt = textSelect.text;
textSelect.setSelection(textSelect.length,textSelect.length);
if (textSelect.width <= 134.05)
{
//textSelect.autoSize = TextFieldAutoSize.LEFT;
textSelect.x = 1.2;
}
if (textSelect.width >= 134.05)
{
//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();
textSelect.width = inputMaxWidth;
}
You could do it this way:
var inputStr:String = event.target.name; //This looks like it's value of your key pressed?
var caret:int = textSelect.textField.caretIndex;
var afterCaretText:String = textSelect.text.substr(caret);
var beforeCaretText:String = textSelect.text.substr(0,caret);
textSelect.text = beforeCaretText + inputStr + afterCaretText;
You could do this all in one line without creating the four variables, but I think it's easier to understand what's going on like this.

Attempt at title... Spawning movie clips according to X/Y axis of mouse AND changing each MC copies' frame position

This is hard to explain.
My aim is to spawn sheep(symbol) each time i click placed according to the mouse's X/Y axis... . I want it to spawn copies of the sheep BUT i also want each copy to be a different image.. (each time the mouse is clicked, it will change the image inside the sheep's symbol (placed on different frames).
If anyone can help I will appreciate it so much!
This is the code:
stage.addEventListener (MouseEvent.CLICK, makeABox);
var i:Number = 1;
function makeABox(e:Event):void {
var newSheep:myMC = new myMC();
addChild(newSheep);
newSheep.x = stage.mouseX;
newSheep.y = stage.mouseY;
i++;
}
var numPressed:Number = 0;
stage.addEventListener(MouseEvent.CLICK, countUp);
function countUp(evt:MouseEvent):void {
numPressed++;
if (numPressed == 1) {
sheep.gotoAndPlay(1);
}
else if (numPressed == 2) {
sheep.gotoAndPlay(2);
}
else if (numPressed == 3) {
sheep.gotoAndPlay(3);
}
else if (numPressed == 4) {
sheep.gotoAndPlay(4);
}
else if (numPressed == 5) {
sheep.gotoAndPlay(5);
}
else if (numPressed == 6) {
sheep.gotoAndPlay(6);
}
else if (numPressed == 7) {
sheep.gotoAndPlay(7);
}
if(numPressed >= 7) numPressed = 0;
}
Replace all the code you posted in your question with this:
stage.addEventListener (MouseEvent.CLICK, addSheep);
var sheepCounter:int = 1;
function addSheep(event:MouseEvent):void {
//create new sheep
var newSheep:myMC = new myMC();
//position it at mouse click
newSheep.x = stage.mouseX;
newSheep.y = stage.mouseY;
//set frame of sheep to display
newSheep.gotoAndStop(sheepCounter);
//add sheep to display list
addChild(newSheep);
//update counter
sheepCounter++;
if (sheepCounter==8)
{
sheepCounter = 1;
}
}