Current date wont update - swing
I have 2 buttons one to log in and the other to log out. I would like both of them to show different times but for some reason unknown to me they do not. and when all the info is saved to a file it says null where there's no information. If there is a way to change that it would be greatly appreciated.
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
public class MainGUI extends JFrame {
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date date = new Date();
String[] columnNames = {"ID", "NAME", "COURSE", "Professor", "Reason for Tutor", "Login Time", "Logout Time"};
Object[][] data = new Object[25][7];
// table
JTable table = new JTable(data, columnNames) {
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
JFrame frame, frame1;
JPanel buttonPanel, buttonPanel2, tablePanel, addPanel, editPanel;
JLabel labelID, labelName, labelCourse, labelProfessor, labelHelp, labelDate, labelDate2;
JTextField txtID, txtName, txtCourse, txtProfessor, txtHelp, txtDate, txtDate2;
JButton btnAdd, btnEdit, btnDelete, btnSort, btnSave, btnAddInput, btnCancel;
int keyCode, rowIndex, rowNumber, noOfStudents;
MainGUI.ButtonHandler bh = new MainGUI.ButtonHandler();
public MainGUI() {
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.getSelectionModel().addListSelectionListener(new MainGUI.RowListener());
table.getColumnModel().getColumn(1).setPreferredWidth(150);
table.getColumnModel().getColumn(3).setPreferredWidth(100);
table.getColumnModel().getColumn(4).setPreferredWidth(200);
table.getColumnModel().getColumn(5).setPreferredWidth(150);
table.getColumnModel().getColumn(6).setPreferredWidth(150);
table.getTableHeader().setResizingAllowed(false);
table.getTableHeader().setReorderingAllowed(false);
JScrollPane scrollPane = new JScrollPane(table);
btnAdd = new JButton("Login");
btnAdd.addActionListener(bh);
btnEdit = new JButton("EDIT");
btnEdit.addActionListener(bh);
btnEdit.setEnabled(false);
btnDelete = new JButton("DELETE");
btnDelete.addActionListener(bh);
btnDelete.setEnabled(false);
btnSort = new JButton("Logout");
btnSort.addActionListener(bh);
btnSave = new JButton("SAVE");
btnSave.addActionListener(bh);
btnSave.setActionCommand("Save");
btnAddInput = new JButton("Login");
btnAddInput.addActionListener(bh);
btnAddInput.setActionCommand("AddInput");
btnCancel = new JButton("Cancel");
btnCancel.addActionListener(bh);
labelID = new JLabel("ID");
labelName = new JLabel("NAME");
labelCourse = new JLabel("Course");
labelProfessor = new JLabel("Professor");
labelHelp = new JLabel("Reason for Tutoring");
labelDate = new JLabel("Login");
labelDate2 = new JLabel("Logout");
txtID = new JTextField(20);
txtName = new JTextField(20);
txtCourse = new JTextField(20);
txtProfessor = new JTextField(20);
txtHelp = new JTextField(20);
txtDate = new JTextField(20);
txtDate2 = new JTextField(20);
txtID.setDocument(new MainGUI.JTextFieldLimit(15));
txtID.addKeyListener(keyListener);
tablePanel = new JPanel();
tablePanel.setLayout(new BoxLayout(tablePanel, BoxLayout.PAGE_AXIS));
tablePanel.setBorder(BorderFactory.createEmptyBorder(10, 2, 0, 10));
tablePanel.add(table.getTableHeader());
tablePanel.add(table);
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
c.fill = GridBagConstraints.HORIZONTAL;
buttonPanel.add(btnAdd, c);
c.gridx = 0;
c.gridy = 1;
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
buttonPanel.add(btnEdit, c);
c.gridx = 0;
c.gridy = 2;
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
buttonPanel.add(btnDelete, c);
c.gridx = 0;
c.gridy = 3;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
c.fill = GridBagConstraints.HORIZONTAL;
buttonPanel.add(btnSort, c);
c.gridx = 0;
c.gridy = 4;
c.ipady = 20;
c.insets = new Insets(10, 10, 10, 10);
c.fill = GridBagConstraints.HORIZONTAL;
buttonPanel.add(btnSave, c);
frame = new JFrame("Tutoring Database");
frame.setVisible(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.add(tablePanel, BorderLayout.CENTER);
frame.add(buttonPanel, BorderLayout.EAST);
frame.pack();
addPanel = new JPanel();
addPanel.setLayout(new GridBagLayout());
c.insets = new Insets(1, 0, 1, 1);
c.gridx = 0;
c.gridy = 0;
addPanel.add(labelID, c);
c.gridy = 1;
addPanel.add(labelName, c);
c.gridy = 2;
addPanel.add(labelCourse, c);
c.gridy = 3;
addPanel.add(labelProfessor, c);
c.gridy = 4;
addPanel.add(labelHelp, c);
c.gridy = 5;
addPanel.add(labelDate, c);
c.gridy = 6;
addPanel.add(labelDate2, c);
// text fields
c.gridx = 1;
c.gridy = 0;
c.ipady = 1;
addPanel.add(txtID, c);
c.gridy = 1;
c.ipady = 1;
addPanel.add(txtName, c);
c.gridy = 2;
c.ipady = 1;
addPanel.add(txtCourse, c);
c.gridy = 3;
c.ipady = 1;
addPanel.add(txtProfessor, c);
c.gridy = 4;
c.ipady = 1;
addPanel.add(txtHelp, c);
c.gridy = 5;
c.ipady = 1;
addPanel.add(txtDate, c);
c.gridy = 5;
c.ipady = 1;
addPanel.add(txtDate2, c);
buttonPanel2 = new JPanel();
buttonPanel2.setLayout(new GridLayout(1, 1));
buttonPanel2.add(btnAddInput);
buttonPanel2.add(btnCancel);
frame1 = new JFrame("Student Database");
frame1.setVisible(false);
frame1.setResizable(false);
frame1.setDefaultCloseOperation(HIDE_ON_CLOSE);
frame1.add(addPanel, BorderLayout.CENTER);
frame1.add(buttonPanel2, BorderLayout.PAGE_END);
frame1.pack();
}// end
KeyListener keyListener = new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
keyCode = e.getKeyCode();
if (!(keyCode >= 48 && keyCode <= 57) && !(keyCode >= 96 && keyCode <= 105)
&& !(keyCode >= 37 && keyCode <= 40) && !(keyCode == 127 || keyCode == 8)) {
txtID.setEditable(false);
}
}
#Override
public void keyReleased(KeyEvent e) {
txtID.setEditable(true);
}
};
class RowListener implements ListSelectionListener {
#Override
public void valueChanged(ListSelectionEvent event) {
if (event.getValueIsAdjusting()) {
rowIndex = table.getSelectedRow();
if (data[rowIndex][0] == null || data[rowIndex][0] == "") {
btnEdit.setEnabled(false);
btnDelete.setEnabled(false);
} else {
btnEdit.setEnabled(true);
btnDelete.setEnabled(true);
}
}
}
}
class ButtonHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Login")) {
txtID.setText("");
txtName.setText("");
txtCourse.setText("");
txtProfessor.setText("");
txtHelp.setText("");
txtDate.setText(dateFormat.format(date));
frame1.setTitle("Add Student data"); // title bar name for add
frame1.setVisible(true);
} else if (e.getActionCommand().equals("EDIT")) {
txtID.setText(data[rowIndex][0] + "");
txtName.setText(data[rowIndex][1] + "");
txtCourse.setText(data[rowIndex][2] + "");
txtProfessor.setText(data[rowIndex][3] + "");
txtHelp.setText(data[rowIndex][4] + "");
txtDate.setText(data[rowIndex][5] + "");
txtID.setEditable(false);
frame1.setTitle("Edit Student data");
btnAddInput.setActionCommand("Edit2");
btnAddInput.setText("ACCEPT");
frame1.setVisible(true);
} else if (e.getActionCommand().equals("DELETE")) {
int confirm = JOptionPane.showConfirmDialog(frame, "ARE YOU SURE?", "CONFIRM",
JOptionPane.YES_NO_OPTION);
if (confirm == 0) {
rowIndex = table.getSelectedRow();
rowNumber = 0;
noOfStudents--;
for (int i = 0; i <= 10; i++) {
if (rowIndex != i && i <= noOfStudents) {
data[rowNumber][0] = data[i][0];
data[rowNumber][1] = data[i][1];
data[rowNumber][2] = data[i][2];
data[rowNumber][3] = data[i][3];
data[rowNumber][4] = data[i][4];
data[rowNumber][5] = data[i][5];
rowNumber++;
} else if (rowIndex != i && i > noOfStudents) {
data[rowNumber][0] = "";
data[rowNumber][1] = "";
data[rowNumber][2] = "";
data[rowNumber][3] = "";
data[rowNumber][4] = "";
data[rowNumber][5] = "";
rowNumber++;
}
}
if (noOfStudents == 1000) {
btnAdd.setEnabled(false);
}
else {
btnAdd.setEnabled(true);
}
if (noOfStudents == 0) {
btnDelete.setEnabled(false);
btnEdit.setEnabled(false);
} else {
btnDelete.setEnabled(true);
btnEdit.setEnabled(true);
}
rowIndex = table.getSelectedRow();
if (data[rowIndex][0] == null || data[rowIndex][0] == "") {
btnEdit.setEnabled(false);
btnDelete.setEnabled(false);
} else {
btnEdit.setEnabled(true);
btnDelete.setEnabled(true);
}
table.updateUI();
}
} else if (e.getActionCommand().equals("AddInput")) {
if (txtID.getText().isEmpty() || txtName.getText().isEmpty()
|| txtCourse.getText().isEmpty()// /
|| txtProfessor.getText().isEmpty() || txtHelp.getText().isEmpty()) {
JOptionPane.showMessageDialog(null, "PLEASE FILL IN THE BLANKS.", "ERROR!",
JOptionPane.ERROR_MESSAGE);
}
else {
int dup = 0;
for (int i = 0; i < 10; i++) {
if (txtID.getText().equals(data[i][0])) {
JOptionPane.showMessageDialog(null, "ID NUMBER ALREADY EXISTS.", "ERROR!",
JOptionPane.ERROR_MESSAGE);
dup++;
}
}
if (dup == 0) {
rowIndex = table.getSelectedRow();
data[noOfStudents][0] = txtID.getText();
data[noOfStudents][1] = txtName.getText();
data[noOfStudents][2] = txtCourse.getText();
data[noOfStudents][3] = txtProfessor.getText();
data[noOfStudents][4] = txtHelp.getText();
data[noOfStudents][5] = txtDate.getText();
table.updateUI();
frame1.dispose();
noOfStudents++;
if (noOfStudents == 50){
btnAdd.setEnabled(false);
}
else {
btnAdd.setEnabled(true);
}
if (data[rowIndex][0] == null) {
btnEdit.setEnabled(false);
btnDelete.setEnabled(false);
} else {
btnEdit.setEnabled(true);
btnDelete.setEnabled(true);
}
}
}
table.updateUI();
}else if(e.getActionCommand().equals("Save")){
try {
PrintWriter out = new PrintWriter("Tutor.txt");
for(int i = 0; i < 25; i++)
{
for(int j = 0; j < 7; j++)
{
out.print(data[i][j]);
out.print(", ");
if(j == 6){
out.println();
}
} out.flush();
}} catch (FileNotFoundException ex) {
}
} else if (e.getActionCommand().equals("Logout")) {
int confirm = JOptionPane.showConfirmDialog(frame, "ARE YOU SURE?", "CONFIRM",
JOptionPane.YES_NO_OPTION);
if (confirm == 0) {
rowIndex = table.getSelectedRow();
rowNumber = 0;
txtDate2.setText(dateFormat.format(date));
}
}
if (txtID.getText().isEmpty() || txtName.getText().isEmpty()
|| txtCourse.getText().isEmpty() || txtProfessor.getText().isEmpty()
|| txtHelp.getText().isEmpty()|| txtHelp.getText().isEmpty()) {
} else {
data[rowIndex][0] = txtID.getText();
data[rowIndex][1] = txtName.getText();
data[rowIndex][2] = txtCourse.getText();
data[rowIndex][3] = txtProfessor.getText();
data[rowIndex][4] = txtHelp.getText();
data[rowIndex][5] = txtDate.getText();
data[rowIndex][6] = txtDate2.getText();
frame1.dispose();
}
table.updateUI();
}
}
class JTextFieldLimit extends PlainDocument {
private int limit;
JTextFieldLimit(int limit) {
super();
this.limit = limit;
}
JTextFieldLimit(int limit, boolean upper) {
super();
this.limit = limit;
}
#Override
public void insertString(int offset, String str, AttributeSet attr)
throws BadLocationException {
if (str == null) {
return;
}
if ((getLength() + str.length()) <= limit) {
super.insertString(offset, str, attr);
}
}
}
public static void main(String[] args) {
new MainGUI();
}
}
Simple answer withing swimming through your ocean of code, you need to create a new date in your actionPerformed whenever you want to show the updated date
example
public void actionPerforemd(ActionEvent e){
...
date = new Date();
// do something with date
...
}
Related
How do I remove eventlisteners and objects from an array upon game completion?
I have written a drag and drop game and, for the most part, it works. It runs and does what I need it to do. However, I cannot figure out two things. How to remove the toy objects from the screen and re-add them after game over. How to remove the event listeners for dragging/collision action after game over has initiated. At the moment, after score is displayed you can still drop items in the toybox and make the score rise even when game over has been displayed. Does anyone have any idea what I am doing wrong? I would love to figure this out but it is driving me crazy. Any help would be great. Here is my code ... package { import flash.display.MovieClip; import flash.events.Event; import flash.events.MouseEvent; import flash.text.TextField; import flash.text.TextFormat; import flash.utils.Timer; import flash.events.TimerEvent; import flash.text.Font; import flash.filters.GlowFilter; public class MainGame extends MovieClip { const BG_SPEED:int = 5; const BG_MIN:int = -550; const BG_MAX:int = 0; const PBG_SPEED:int = 3; var bg:BackGround = new BackGround; var paraBg:ParaBg = new ParaBg; var toybox:TargetBox = new TargetBox; var toy:Toy = new Toy; var tryAgain:TryAgain = new TryAgain; var cheer:Cheer = new Cheer; var eightBit:EightBit = new EightBit; var countDown:Number = 30; var myTimer:Timer = new Timer(1000, 30); var myText:TextField = new TextField; var myText2:TextField = new TextField; var myTextFormat:TextFormat = new TextFormat; var myTextFormat2:TextFormat = new TextFormat; var font1:Font1 = new Font1; var kids:Kids = new Kids; var count:int = 0; var finalScore:int = 0; var score:Number = 0; var toy1:Toy1 = new Toy1; var toy2:Toy2 = new Toy2; var toy3:Toy3 = new Toy3; var toy4:Toy4 = new Toy4; var toy5:Toy5 = new Toy5; var toy6:Toy6 = new Toy6; var toy7:Toy7 = new Toy7; var toy8:Toy8 = new Toy8; var toy9:Toy9 = new Toy9; var toy10:Toy10 = new Toy10; var toy11:Toy11 = new Toy11; var toy12:Toy12 = new Toy12; var toy13:Toy13 = new Toy13; var toy14:Toy14 = new Toy14; var toy15:Toy15 = new Toy15; var toy16:Toy16 = new Toy16; var toy17:Toy17 = new Toy17; var toy18:Toy18 = new Toy18; var toy19:Toy19 = new Toy19; var toy20:Toy20 = new Toy20; var toyArray:Array = new Array(toy1, toy2, toy3, toy4, toy5, toy6, toy7, toy8, toy9, toy10, toy11, toy12, toy13, toy14, toy15, toy16, toy17, toy18, toy19, toy20); public function mainGame():void { trace("HI"); eightBit.play(0, 9999); addChildAt(paraBg, 0); addChildAt(bg, 1); addChildAt(kids, 2); kids.x = 310; kids.y = 200; addChild(toy); toy.x = 306; toy.y = 133; addChild(toybox); toybox.x = 295; toybox.y = 90; function addToys(xpos:int, ypos:int) { addChild(toyArray[i]); toyArray[i].x = xpos; toyArray[i].y = ypos; } for (var i:int = 0; i < toyArray.length; i++) { addToys(1140 * Math.random() + 20, 170 * Math.random() + 230); } } public function bgScroll (e:Event) { stage.addEventListener(MouseEvent.MOUSE_UP, arrayDrop); myTimer.addEventListener(TimerEvent.TIMER, countdown); myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, timerDone); myTimer.start(); e.target.addEventListener(Event.ENTER_FRAME, collision); if (stage.mouseX > 600 && bg.x > BG_MIN) { bg.x -= BG_SPEED; paraBg.x -= PBG_SPEED; for (var m:int=0; m< toyArray.length; m++) { (toyArray[m] as MovieClip).x -=BG_SPEED } } else if (stage.mouseX < 50 && bg.x < BG_MAX) { bg.x += BG_SPEED; paraBg.x += PBG_SPEED; for (var j:int=0; j< toyArray.length; j++) { (toyArray[j] as MovieClip).x +=BG_SPEED } } for (var k:int = 0; k < toyArray.length; k++) { toyArray[k].addEventListener(MouseEvent.MOUSE_DOWN, arrayGrab); } bg.addEventListener(Event.ENTER_FRAME, bgScroll); } // End of BGScroll public function collision (e:Event) { for (var l:int=0; l< toyArray.length; l++) { if (toyArray[l].hitTestObject(toy)) { removeChild(toyArray[l]); toyArray[l].x=100000; toybox.gotoAndPlay(2); cheer.play(1, 1); score = score + 10; trace(score); } if (score == 200) { timerDone(); myTimer.stop(); } } } public function arrayGrab(e:MouseEvent) { e.target.startDrag(); } public function arrayDrop(e:MouseEvent) { stopDrag(); } public function resetGame(e:Event):void { trace("CLICK"); countDown = 30; myText.text = "0" + countDown.toString(); myTimer.addEventListener(TimerEvent.TIMER_COMPLETE, timerDone); myTimer.reset(); removeChild(tryAgain); myText2.visible = false; score = 0; } public function countdown(e:TimerEvent):void { if (countDown > 0) { countDown--; } if (countDown < 10) { myText.text = "0" + countDown.toString(); myText.x = 270; displayText(); } else if (countDown < 20 && countDown > 9) { myText.text = countDown.toString(); myText.x = 280; displayText(); } else { myText.text = countDown.toString(); myText.x = 270; displayText(); } } // end of countdown function public function displayText():void { myText.filters = [new GlowFilter(0x00FF00, 1.0, 5, 5, 4)]; addChild(myText); myText.width = 500, myText.height = 50, myText.y = 10; myTextFormat.size = 50, myTextFormat.font = font1.fontName; myText.setTextFormat(myTextFormat); } public function displayText2():void { myText2.filters = [new GlowFilter(0xFF0000, 1.0, 5, 5, 4)]; addChild(myText2); myText2.width = 500, myText2.height = 35, myText2.x = 204, myText2.y = 200; myTextFormat2.size = 30, myTextFormat2.font = font1.fontName; myText2.setTextFormat(myTextFormat2); } public function timerDone(e:TimerEvent=null):void { if (countDown == 0) { count = 0; finalScore = score; } else { count = (30) - (myTimer.currentCount); finalScore = (count * 10) + (score); } myText.text = "GAME OVER!"; myText.x = 195; displayText(); myText2.text = "Your score = " + (finalScore); displayText2(); addChild(tryAgain); tryAgain.x = 300; tryAgain.y = 300; tryAgain.addEventListener(MouseEvent.CLICK, resetGame); } } // End of class } //End of package
Nevermind ... solved it. Easiest was was to change function addToys(xpos:int, ypos:int) { addChild(toyArray[i]); toyArray[i].x = xpos; toyArray[i].y = ypos; } To function addToys(xpos:int, ypos:int) { stage.addChild(toyArray[i]); toyArray[i].x = xpos; toyArray[i].y = ypos; } And then, in the timerDone function I added thisif statement ... for (var m = 0; m < toyArray.length; m++) { if (stage.contains(toyArray[m])) { stage.removeChild(toyArray[m]); } Worked a treat!
Error #1069: Property y not found on Number and there is no default value
I'm getting the following error with the code shown below TypeError: Error #1010: A term is undefined and has no properties I'm new at using classes so it could be a messy code, but i really need help xD. I've already read a tutorial about classes that someone gave me here in another question I had, but i'm still having problems with these classes... lol package { import flash.display.Sprite; import flash.display.Stage; public class Notas { public var stage:Stage; public var velocidad:int = 5; public var barra:Sprite = new Sprite(); public var puntaje:int; public var i:int = 0; public var contador:int = 0; public var j:int = 0; public var notaS:Array = new Array(16); public var notaD:Array = new Array(16); public var notaF:Array = new Array(16); public var notaSPACE:Array = new Array(16); public var notaJ:Array = new Array(16); public var notaK:Array = new Array(16); public var notaL:Array = new Array(16); public function Notas(escenario:Stage) { stage = escenario; } public function Inicializar():void { asignarNotas(); barra = drawRect(0xFF0000, 1280, 10, 0, 650); stage.addChild(barra); crearNotaS(0xFFFFFF, 30, 10, 0, 0); } public function Destruir():void { for (i = 0; i < notaS.length; i++) { if (notaS[i].y < 720 || barra.hitTestObject(notaS[i])) { stage.removeChild(notaS[i]); puntaje += 1; trace (puntaje); } } } public function crearNotaS(color:int, ancho:int, alto:int, x:int, y:int):void { for (i = 0; i < notaS.length; i++) { if (notaS[i] == 1 && i == 0) { notaS[i] = drawRect(color, ancho, alto, x, y); stage.addChild(notaS[i]); notaS[i].y = -alto / 2; } else if (notaS[i] == 0) { j += 1 } else if (notaS[i] == 1 && i > 0) { notaS[i] = drawRect(color, ancho, alto, x, notaS[i].y + alto * j); stage.addChild(notaS[i]); } } } public function drawRect(color:uint, ancho:int, alto:int, x:int, y:int):Sprite { var dj:Sprite = new Sprite(); dj.graphics.beginFill(color,1); dj.graphics.drawRect(0,0,ancho,alto); dj.graphics.endFill(); dj.x = x; dj.y = y; return(dj); } public function asignarNotas():void { notaS[0] = 1 notaS[1] = 1 notaS[2] = 1 notaS[3] = 1 notaS[4] = 1 notaS[5] = 1 notaS[6] = 1 notaS[7] = 1 notaS[8] = 1 notaS[9] = 1 notaS[10] = 1 notaS[11] = 1 notaS[12] = 1 notaS[13] = 1 notaS[14] = 1 notaS[15] = 1 } public function moverNotas():void { for (i = 0; i < notaS.length; i++) { if (notaS[i] != 0) { notaS[i].y += velocidad; } } } } }
Error 1180, Flash
So, the same college project as last time, and this time im having a trouble with undefined methods. The entirity of my code is below package { import flash.display.MovieClip; import flash.events.MouseEvent; public class Lesson_05 extends MovieClip { private static const boardWidth:uint = 4; private static const boardHeight:uint = 2; private static const cardHorizontalSpacing:Number = 52; private static const cardVerticalSpacing:Number = 52; private static const boardOffsetX:Number = 171; private static const boardOffsetY:Number = 148; private var firstCard:Card; private var secondCard:Card; private var cardsLeft:uint; var startPage:StartPage_1; var matchPage:MatchPage_1; var guessPage:GuessPage_1; var startMessage:String; var mysteryNumber:uint; var currentGuess:uint; var guessesRemaining:uint; var guessesMade:uint; var gameStatus:String; var gameWon:Boolean; public function Lesson_05():void { startPage = new StartPage_1(); matchPage = new MatchPage_1(); guessPage = new GuessPage_1(); addChild(startPage); startPage.matchButton.addEventListener(MouseEvent.CLICK,onMatchButtonClick); startPage.guessButton_1.addEventListener(MouseEvent.CLICK,onGuessButtonClick_1); guessPage.matchButton.addEventListener(MouseEvent.CLICK,onMatchButtonClick_Guess); //Output Errors #2025 when added this line; guessPage.startButton.addEventListener(MouseEvent.CLICK,onStartButtonClick); matchPage.startButton.addEventListener(MouseEvent.CLICK,onStartButtonClick_Match); matchPage.guessButton_1.addEventListener(MouseEvent.CLICK,onGuessButtonClick_Match_1); } function onMatchButtonClick(event:MouseEvent):void { addChild(matchPage); removeChild(startPage); match(); } function onGuessButtonClick_1(event:MouseEvent):void { addChild(guessPage); removeChild(startPage); guess(); } function onMatchButtonClick_Guess(event:MouseEvent):void { addChild(matchPage); removeChild(guessPage); match(); } function onStartButtonClick(event:MouseEvent):void { addChild(startPage); removeChild(guessPage); } function onStartButtonClick_Match(event:MouseEvent):void { addChild(startPage); removeChild(matchPage); } function onGuessButtonClick_Match_1(event:MouseEvent):void { addChild(guessPage); removeChild(matchPage); guess(); } function guess():void { startMessage = "I am thinking of a number between 1 and 20"; mysteryNumber = Math.ceil(Math.random()*20); guessesRemaining = 10; guessesMade = 0; gameStatus = ""; gameWon = false; guessPage.output_txt.text = startMessage; guessPage.input_txt.text = ""; guessPage.input_txt.backgroundColor = 0xFFCCCCCC; guessPage.input_txt.restrict = "0-9"; guessPage.stage.focus = guessPage.input_txt; guessPage.guessButton_2.enabled = true; guessPage.guessButton_2.alpha = 1; guessPage.againButton_1.visible = false; guessPage.guessButton_2.addEventListener(MouseEvent.CLICK,onGuessButtonClick_2); } function onGuessButtonClick_2(event:MouseEvent):void { guessesRemaining--; guessesMade++; gameStatus = "Guesses Remaining: " + guessesRemaining + ", GuessesMade:" + guessesMade; currentGuess = uint(guessPage.input_txt.text); if (currentGuess > mysteryNumber) { guessPage.output_txt.text = "That's too high!" + "\n" + gameStatus; checkGameOver(); } else if (currentGuess < mysteryNumber) { guessPage.output_txt.text = "That's too low!" + "\n" + gameStatus; checkGameOver(); } else { //guessPage.output_txt.text = "Well Done! You got it!"; gameWon = true; endGame(); } function checkGameOver():void { if (guessesRemaining < 1) { endGame(); } } function endGame():void { if (gameWon) { guessPage.output_txt.text = "Yes, it's " + mysteryNumber + "!" + "\n" + "It only took you " + guessesMade + " guesses!"; } else { guessPage.output_txt.text = "Sorry, you've run out of guesses!" + "\n" + "The correct number was " + mysteryNumber + "."; } guessPage.guessButton_2.removeEventListener(MouseEvent.CLICK,onGuessButtonClick_2); guessPage.guessButton_2.enabled = false; guessPage.guessButton_2.alpha = 0.5; guessPage.againButton_1.visible = true; guessPage.againButton_1.addEventListener(MouseEvent.CLICK,onAgainButtonClick_1); } function onAgainButtonClick_1(event:MouseEvent):void { guess(); guessPage.againButton_1.removeEventListener(MouseEvent.CLICK,onAgainButtonClick_1); } function match():void { var cardlist:Array = new Array(); for (var i:uint=0; i<boardWidth*boardHeight/2; i++) { cardlist.push(i); cardlist.push(i); } cardsLeft = 0; for (var x:uint=0; x<boardWidth; x++) { for (var y:uint=0; y<boardHeight; y++) { var c:Card = new Card(); c.stop(); c.x = x * cardHorizontalSpacing + boardOffsetX; c.y = y * cardVerticalSpacing + boardOffsetY; var r:uint = Math.floor(Math.random() * cardlist.length); c.cardface = cardlist[r]; cardlist.splice(r,1); c.addEventListener(MouseEvent.CLICK,clickCard); addChild(c); cardsLeft++; } } } function clickCard(event:MouseEvent) { var thisCard:Card = (event.target as Card); if (firstCard ==null) { firstCard = thisCard; firstCard.gotoAndStop(thisCard.cardface+2); } else if (firstCard ==thisCard) { firstCard.gotoAndstop(1); firstCard = null; } else if (secondCard == null) { secondCard = thisCard; secondCard.gotoAndStop(thisCard.cardface+2); if (firstCard.cardface == secondCard.cardface) { removeChild(firstCard); removeChild(secondCard); firstCard = null; secondCard = null; cardsLeft -= 2; if (cardsLeft ==0) { } } } else { firstCard.gotoAndStop(1); secondCard.gotoAndStop(1); secondCard = null; firstCard = thisCard; firstCard.gotoAndStop(thisCard.cardface+2); } } } } } and the problems I'm getting are: 1180: Call to a possibly undefined method match. I have very little knowledge with AS3, and have spent more than 2 hours trying to resolve this problem. Thanks in advance guys, PS any links to tutorials etc are massively appreciated
You misplaced close braces'}' of the function onGuessButtonClick_2. Use the below code and check it. package { import flash.display.MovieClip; import flash.events.MouseEvent; public class Lesson_05 extends MovieClip { private static const boardWidth:uint = 4; private static const boardHeight:uint = 2; private static const cardHorizontalSpacing:Number = 52; private static const cardVerticalSpacing:Number = 52; private static const boardOffsetX:Number = 171; private static const boardOffsetY:Number = 148; private var firstCard:Card; private var secondCard:Card; private var cardsLeft:uint; var startPage:StartPage_1; var matchPage:MatchPage_1; var guessPage:GuessPage_1; var startMessage:String; var mysteryNumber:uint; var currentGuess:uint; var guessesRemaining:uint; var guessesMade:uint; var gameStatus:String; var gameWon:Boolean; public function Lesson_05():void { startPage = new StartPage_1(); matchPage = new MatchPage_1(); guessPage = new GuessPage_1(); addChild(startPage); startPage.matchButton.addEventListener(MouseEvent.CLICK,onMatchButtonClick); startPage.guessButton_1.addEventListener(MouseEvent.CLICK,onGuessButtonClick_1); guessPage.matchButton.addEventListener(MouseEvent.CLICK,onMatchButtonClick_Guess); //Output Errors #2025 when added this line; guessPage.startButton.addEventListener(MouseEvent.CLICK,onStartButtonClick); matchPage.startButton.addEventListener(MouseEvent.CLICK,onStartButtonClick_Match); matchPage.guessButton_1.addEventListener(MouseEvent.CLICK,onGuessButtonClick_Match_1); } function onMatchButtonClick(event:MouseEvent):void { addChild(matchPage); removeChild(startPage); match(); } function onGuessButtonClick_1(event:MouseEvent):void { addChild(guessPage); removeChild(startPage); guess(); } function onMatchButtonClick_Guess(event:MouseEvent):void { addChild(matchPage); removeChild(guessPage); match(); } function onStartButtonClick(event:MouseEvent):void { addChild(startPage); removeChild(guessPage); } function onStartButtonClick_Match(event:MouseEvent):void { addChild(startPage); removeChild(matchPage); } function onGuessButtonClick_Match_1(event:MouseEvent):void { addChild(guessPage); removeChild(matchPage); guess(); } function guess():void { startMessage = "I am thinking of a number between 1 and 20"; mysteryNumber = Math.ceil(Math.random()*20); guessesRemaining = 10; guessesMade = 0; gameStatus = ""; gameWon = false; guessPage.output_txt.text = startMessage; guessPage.input_txt.text = ""; guessPage.input_txt.backgroundColor = 0xFFCCCCCC; guessPage.input_txt.restrict = "0-9"; guessPage.stage.focus = guessPage.input_txt; guessPage.guessButton_2.enabled = true; guessPage.guessButton_2.alpha = 1; guessPage.againButton_1.visible = false; guessPage.guessButton_2.addEventListener(MouseEvent.CLICK,onGuessButtonClick_2); } function onGuessButtonClick_2(event:MouseEvent):void { guessesRemaining--; guessesMade++; gameStatus = "Guesses Remaining: " + guessesRemaining + ", GuessesMade:" + guessesMade; currentGuess = uint(guessPage.input_txt.text); if (currentGuess > mysteryNumber) { guessPage.output_txt.text = "That's too high!" + "\n" + gameStatus; checkGameOver(); } else if (currentGuess < mysteryNumber) { guessPage.output_txt.text = "That's too low!" + "\n" + gameStatus; checkGameOver(); } else { //guessPage.output_txt.text = "Well Done! You got it!"; gameWon = true; endGame(); } } function checkGameOver():void { if (guessesRemaining < 1) { endGame(); } } function endGame():void { if (gameWon) { guessPage.output_txt.text = "Yes, it's " + mysteryNumber + "!" + "\n" + "It only took you " + guessesMade + " guesses!"; } else { guessPage.output_txt.text = "Sorry, you've run out of guesses!" + "\n" + "The correct number was " + mysteryNumber + "."; } guessPage.guessButton_2.removeEventListener(MouseEvent.CLICK,onGuessButtonClick_2); guessPage.guessButton_2.enabled = false; guessPage.guessButton_2.alpha = 0.5; guessPage.againButton_1.visible = true; guessPage.againButton_1.addEventListener(MouseEvent.CLICK,onAgainButtonClick_1); } function onAgainButtonClick_1(event:MouseEvent):void { guess(); guessPage.againButton_1.removeEventListener(MouseEvent.CLICK,onAgainButtonClick_1); } function match():void { var cardlist:Array = new Array(); for (var i:uint=0; i<boardWidth*boardHeight/2; i++) { cardlist.push(i); cardlist.push(i); } cardsLeft = 0; for (var x:uint=0; x<boardWidth; x++) { for (var y:uint=0; y<boardHeight; y++) { var c:Card = new Card(); c.stop(); c.x = x * cardHorizontalSpacing + boardOffsetX; c.y = y * cardVerticalSpacing + boardOffsetY; var r:uint = Math.floor(Math.random() * cardlist.length); c.cardface = cardlist[r]; cardlist.splice(r,1); c.addEventListener(MouseEvent.CLICK,clickCard); addChild(c); cardsLeft++; } } } function clickCard(event:MouseEvent) { var thisCard:Card = (event.target as Card); if (firstCard ==null) { firstCard = thisCard; firstCard.gotoAndStop(thisCard.cardface+2); } else if (firstCard ==thisCard) { firstCard.gotoAndstop(1); firstCard = null; } else if (secondCard == null) { secondCard = thisCard; secondCard.gotoAndStop(thisCard.cardface+2); if (firstCard.cardface == secondCard.cardface) { removeChild(firstCard); removeChild(secondCard); firstCard = null; secondCard = null; cardsLeft -= 2; if (cardsLeft ==0) { } } } else { firstCard.gotoAndStop(1); secondCard.gotoAndStop(1); secondCard = null; firstCard = thisCard; firstCard.gotoAndStop(thisCard.cardface+2); } } } } Hope it helps.
Your match() function is inside the onGuessButtonClick_2(MouseEvent) function. So when you try it from anywhere else that is not the inside of the onGuessButtonClick_2 function, flash gets confused because it cannot find the function match() because it is only callable inside the onGuessButtonClick_2() function.
1180 errors are caused by Flash being dead. 1180 Error: Flash is Dead, please convert your code to HTML5 or do it natively. okthxbai Adobe
Error 1007- Instantiation attempted on a non-constructor
New error for me- can't see why this is problem - It compiles then fails with Error 1007 Despite changing considerable amounts of code- its still the same error Clearing the debugger window allows it to run everything but tile.as. As per Pulsar's request here is the entire code for the two problem files. This is in Main.as package { import flash.display.Bitmap; import flash.display.Sprite; import flash.events.*; import flash.ui.Keyboard; //import board; import flash.accessibility.AccessibilityImplementation; import flash.display.Bitmap; import flash.display.MovieClip; import flash.text.TextField; import flash.text.TextFormat; import flash.display.Sprite; import flash.utils.ByteArray; import flash.events.MouseEvent; import flash.text.AntiAliasType; import flash.utils.describeType; import boxsprite; import flash.net.*; import flash.display.Stage; import board; import flash.events.KeyboardEvent; import flash.ui.KeyboardType; import Set; import tile; /** * ... * #author Michael */ public class Main extends Sprite { [Embed(source="../lib/Board.jpg")] private var boardClass :Class; public function Main():void {if (stage) init(); else addEventListener(Event.ADDED_TO_STAGE, init); } private var t1:Sprite; private var t2:Sprite; private var t3:Sprite; private var t4:Sprite; private var t5:Sprite; private var t6:Sprite; private var t7:Sprite; private var base:Sprite; private var tilex:Sprite; private var boardonScreen:Bitmap; private var box1:Sprite; private function init():void { removeEventListener(Event.ADDED_TO_STAGE, init); boardonScreen= new boardClass() as Bitmap; boardonScreen.x = 0; boardonScreen.y = 0; stage.addChild(boardonScreen); box1 = new boxsprite(); box1.x = 480; box1.y = 0; stage.addChild(box1); base = new tile(); base.x =672; base.y = 448; stage.addChild(base); t1 = new tile(); t1.x = 480; t1.y = 448; stage.addChild(t1); t2 = new tile(); t2.x = 480; t2.y = 416; stage.addChild(t2); t3 = new tile(); t3.x = 480; t3.y = 384; stage.addChild(t3); t4 = new tile(); t4.x = 480; t4.y = 352; stage.addChild(t4); t5 = new tile(); t5.x = 480; t5.y = 320; stage.addChild(t5); t6 = new tile(); t6.x = 480; t6.y = 288; stage.addChild(t6); t7 = new tile(); t7.x = 480; t7.y = 256; stage.addChild(t7);}}} In the file: tiles.as package { import fl.transitions.*; import fl.transitions.easing.*; import flash.display.Bitmap; import flash.display.Sprite; import flash.events.*; import flash.events.MouseEvent; import flash.text.TextField; import flash.text.*; import flash.utils.*; import lob; import flash.events.KeyboardEvent; import flash.ui.Keyboard; import Math; import Main; import boxsprite; import StatusBox; import Set; ///These import functions are used to ease the button back into place after a drag public class tile extends Sprite { private var kana:String; private var value:uint; //private const backingcolour:uint = 0xe0e0e0; private var type:uint; private var isSetBox:Boolean; private static var valueaggreg:uint; //value of kanjitile static private var ret:Boolean; //do you return tiles from board static private var yplace:uint = 0; private var xx:int; private var yy:uint; private var initialx:uint; private var initialy:uint; private var finalx:uint; private var finaly:uint; private var id:uint; private var selectghostList:Vector.<String>=new<String>["ま,マ","む,ム","も,モ","か,カ","く,ク","こ,コ","な,ナ","ぬ,ヌ","の,ノ","ば,バ","ぶ,ブ","ぼ,ボ","は,ハ","ふ,フ","ほ,ホ","ぱ,パ","ぷ,プ","ぽ,ポ"]; private var selectkanaList:Vector.<String>=new <String>["みゃ,ミャ", "みゅ,ミャ", "みょ,ミョ", "きゃ,キャ", "きゅ,キュ", "きょ,キョ", "にゃ,ニャ", "にゅ,ニュ", "にょ,ニョ", "びゃ,びゃ", "びゅ,ビュ", "びょ,ビョ", " ひゃ,ヒャ", "ひゅ,ヒュ", "ひょ,ヒョ", "ぴゃ,ピャ", "ぴゅ,ピュ", "ぴょ,ピョ"]; private var selectghostvalueList:Vector.<uint> = new <uint>[2, 2, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2]; private const multiplier:Array = [["TW","1","1","DL","1","1","1","TW","1","1","1","DL","1","1","TW"],["1","DW","1","1","1","TL","1","1","1","TL","1","1","1","DW","1"],["1","1","DW","1","1","1","DL","1","DL","1","1","1","DW","1","1"],["DL","1","1","DW","1","1","1","DL","1","1","1","DW","1","1","DL"],["1","1","1","1","DW","1","1","1","1","1","DW","1","1","1","1"],["1","TL","1","1","1","TL","1","1","1","TL","1","1","1","TL","1"],["1","1","DL","1","1","1","DL","1","DL","1","1","1","DL","1","1"],["TW","1","1","DL","1","1","1","DL","1","1","1","DL","1","1","TW"],["1","1","DL","1","1","1","DL","1","DL","1","1","1","DL","1","1"],["1","TL","1","1","1","TL","1","1","1","TL","1","1","1","TL","1"],["1","1","1","1","DW","1","1","1","1","1","DW","1","1","1","1"],["DL","1","1","DW","1","1","1","DL","1","1","1","DW","1","1","DL"],["1","1","DW","1","1","1","DL","1","DL","1","1","1","DW","1","1"],["1","DW","1","1","1","TL","1","1","1","TL","1","1","1","DW","1"],["TW","1","1","DL","1","1","1","TW","1","1","1","DL","1","1","TW"]]; private var vis:Boolean = true; //visibility private var isSet:Boolean; [Embed(source = "C:/Users/Makiko/Desktop/Michael/Games/Test/New Project/lib/Tile.png")] private var tileClass:Class private var kanaList:Vector.<String> = new <String>["あ,ア", "あ,ア", "え,エ", "え,エ", "い,イ", "い,イ", "お,オ", "お,オ", "う,ウ", "う,ウ", "う,ウ", "う,ウ", "か,カ", "か,カ", "け,ケ", "け,ケ", "き,キ", "き,キ", "く,ク", "く,ク", "こ,コ", "こ,コ", "さ,サ", "さ,サ", " し,シ", " し,シ", "す,ス", "す,ス", "そ,ソ", "そ,ソ", "す,ス", "す,ス", "た,タ", "た,タ", "て,テ", "て,テ", " ち,チ", " ち,チ", "と,ト", "と,ト", "つ,ツ", "つ,ツ", "ら,ラ", "ら,ラ", "れ,レ", "れ,レ", "り,リ", "り,リ", "ろ,ロ", "ろ,ロ", "る,ル", "る,ル", "だ,ダ", "で,デ", "じ,ジ", "ど/ド", "ず,ズ", "ざ,ザ", "ぜ,ゼ", "ぞ/ゾ", "な,ナ", "ね,ネ", "に,二", "の,ノ", "ぬ,ヌ", "じゃ,ジャ", "じゅ,ジュ", "じょ,ジョ", "ん,ン", "しゃ,シャ", "しゅ,シュ", "しょ,ショ", "や,ヤ", "ゆ,ユ", "よ,ヨ", "は,ハ", "ひ,ヒ", "ふ,フ", "へ,ヘ", "ほ,ホ", "ば,バ", "ば,バ", "ぶ,ブ", "ぶ,ブ", "び,ビ", "び,ビ", "ぼ,ボ", "ぼ,ボ", "べ,ベ", "べ,ベ", "ぱ,パ", "ぴ/ピ", "ぷ,プ", "ぺ,ペ", "ぽ,ポ", "ま,マ", "み,ミ", " む,ム", "め,メ", "も,モ", "を/ヲ", "みゃ,ミャ", "みゅ,ミャ", "みょ,ミョ", "きゃ,キャ", "きゅ,キュ", "きょ,キョ", "にゃ,ニャ", "にゅ,ニュ", "にょ,ニョ", "びゃ,びゃ", "びゅ,ビュ", "びょ,ビョ", "ひゃ,ヒャ", "ひゅ,ヒュ", "ひょ,ヒョ", "ぴゃ,ピャ", "ぴゅ,ピュ", "ぴょ,ピョ", "っ,ッ", "っ,ッ"]; private var valueList:Vector.<uint>= new <uint>[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 10, 10, 5, 5, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 20, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 1, 1]; // Lists of Kana that can be replaced in the replace mode and the substitute Kana and Values //Start list of playerHand contents as I don't know if Null is 0 private var playernumber:uint; //total number of players private var allplayersHand:Array = [[], [], [], [],[], []]; private var playerRound:uint = 1; //which player private var round:uint = 1; //round of the game private var aplayersHand:Array; // hand of the current player private var mode:uint; private var tileImage:Bitmap; private static var idvar:uint; static private var first:Boolean = true; private var special:Boolean = false; static private var handstatus:Vector.<String>; //handstatus types are idle: free, ret: ready to return to stock, set: set on board, rem: ready to removed, not public function tile() { addEventListener(Event.ADDED_TO_STAGE, standarddisplay) } private function standarddisplay(e:Event=void) : void {trace("Project is running fine!"); removeEventListener(Event.ADDED_TO_STAGE, standarddisplay); tileImage = new tileClass as Bitmap; addChild(tileImage); //Draws the japanese letter on the tile var kanafield:TextField = new TextField(); kanafield.width = 40; kanafield.height = 20; kanafield.x = -2; kanafield.y = -5; kanafield.text == ""; trace(kanafield.text); kanafield.wordWrap = true; kanafield.background = true; var kanafieldformat:TextFormat = new TextFormat(); kanafieldformat.size = 12; kanafieldformat.font = "Arial"; kanafield.setTextFormat(kanafieldformat); this.addChild(kanafield); kanafield.mouseEnabled = false; //Draw the number on the tile valuefield= new TextField(); valuefield.width = 30; valuefield.height = 10; valuefield.x = 0; var valuefieldformat:TextFormat = new TextFormat; valuefieldformat.size = 7; valuefield.text = ""; valuefield.y = 15; valuefield.background = false; valuefield.setTextFormat(valuefieldformat); this.addChild(valuefield); valuefield.mouseEnabled = false; //Add an event listener to the tile on the stage checktype(); } private function checktype():void {if (first != true) { id = idvar; idvar += 1; value = playerhandvalue[id]; stage.addEventListener(KeyboardEvent.KEY_DOWN,keyboardinput); this.addEventListener(StatusBox.STATUSBOXCHANGED,moderesponse); this.addEventListener(StatusBox.HIDE, SetAlpha); isSetBox = false } else { special = true; first = false; this.addEventListener(Set.BOX_SET_CHANGED,btr) init();}} private function init():void { trace("starting"); stage.addEventListener(KeyboardEvent.KEY_DOWN, myKeyDown); stage.addEventListener(MouseEvent.MOUSE_UP, dnp);} private function dnp(e:MouseEvent):void { stage.removeEventListener(KeyboardEvent.KEY_DOWN,myKeyDown); stage.removeEventListener(MouseEvent.MOUSE_UP, dnp); trace(playernumber); create(); } private function myKeyDown(e2:KeyboardEvent):void { if (e2.keyCode == Keyboard.NUMBER_1) {playernumber = 1; trace(playernumber);} else if (e2.keyCode == Keyboard.NUMBER_2) {playernumber = 2; trace(playernumber) else if (e2.keyCode == Keyboard.NUMBER_3) {playernumber = 3; trace(playernumber);} else if (e2.keyCode == Keyboard.NUMBER_4) {playernumber = 4; trace(playernumber); } else if (e2.keyCode == Keyboard.NUMBER_5) {playernumber = 5; trace(playernumber);} else if (e2.keyCode == Keyboard.NUMBER_6) {playernumber = 6; } else {playernumber = 1;}} private function create():void { var listLength:uint; var row:uint aplayersHand = allplayersHand[playerRound]; for (var i:uint = (aplayersHand.length-1); i <= 6; i+=1) { listLength = kanaList.length; row = int(Math.random() * listLength); trace (row); trace(i); aplayersHand[i] = [0, kanaList[row], valueList[row],] trace (aplayersHand); trace (aplayersHand[i]); kanaList.splice(row,1); valueList.splice(row, 1); playerhandkana.push(kanaList[row]); playerhandvalue.push(valueList[row]);} dispatchEvent( new StatusBox(StatusBox.STATUSBOXCHANGED, 1)); } private function moderesponse(e:StatusBox):void { mode = e.mode; cleanup(); if (special == false) { if (mode == 1) { this.visible = true; this.kanafield.visible = true; this.valuefield.visible = true; this.x = 480; this.y = (480 - (id*32)); kana = playerhandkana[id]; value = playerhandvalue[id]; kanafield.text = kana; valuefield.text = String(value); this.addEventListener(MouseEvent.MOUSE_DOWN, draglocation); } else if (mode == 4) {if (handstatus[id] == "rem") {handstatus[id] = "idle"; } } } else if (special == true) { if (mode == 8) {stage.addEventListener(KeyboardEvent.KEY_DOWN, keyboardinput); for (var i:uint = 0; (handstatus.length - 1); i += 1) {if (handstatus[i] == "ret") {kanaList.push(playerhandkana[i]); valueList.push(playerhandvalue[i]); endgame = true;} } if (endgame == true) { dispatchEvent(new StatusBox(StatusBox.STATUSBOXCHANGED, 9, false, false));} else {{var cfh:Boolean = checkforwordtype(horzword); var cfv:Boolean = (checkforwordtype(vertword)); var hl2:uint; if ((handstatus.length > 1 && (cfh == false) && (cfv == false))) {dispatchEvent(new StatusBox(StatusBox.STATUSBOXCHANGED, 10, false, false));} if (generalx.length == 0) {for (var j:uint = 0; (handstatus.length - 1); i += 1) {if (handstatus[i] == "set") {hl2 += 1 } } if (hl2 == 1) {dispatchEvent(new StatusBox(StatusBox.STATUSBOXCHANGED, 10, false, false)); }} if ((cfh == true) && (cfv == true)) {dispatchEvent(new StatusBox(StatusBox.STATUSBOXCHANGED, 10, false, false)); } else if (cfh == true) {calctotalscore(valuehor, valuevert);} else if (cfv == true) {calctotalscore(valuevert, valuehor); } } } for (var k:uint = 0; k < (handstatus.length - 1); k += 1) { if(handstatus[i] == "idle" || "rem") { var o:uint=0 allplayersHand[playernumber][o] = [kana, value]; o += 1; }}} else if (mode == 9) {if (ret == true) { ret = false; for (var m:uint = 0; m < (handstatus.length - 1); m += 1) { if(handstatus[i] == "set") { var p:uint=0 allplayersHand[playernumber][p] = [kana, value]; p += 1; }} dispatchEvent(new StatusBox(StatusBox.STATUSBOXCHANGED, 1, false, false));} else { setinplace(); dispatchEvent(new StatusBox(StatusBox.STATUSBOXCHANGED, 1, true, true)); } } else if (mode == 10) {isSet = false; isSetBox = false; this.visible = false; create();}}} private function btr(e:Set):void {if (e.valueex > 0) { if (e.kanaex == "kanji") {kanafield.type = TextFieldType.INPUT; value += e.valueex; valuefield.text = String(value);} else if (e.kanaex == "k+" ) {value += e.valueex; valuefield.text = String(value);} else if (e.kanaex == "k-") {value-= e.valueex; valuefield.text = String(value);} else if (e.kanaex == "nokanji") {kanafield.type = TextFieldType.DYNAMIC; value = 0; kana = ""; valuefield.text = "";}} else {if (kana == "") { if (e.valueex == 0) {kana =selectghostList[selectkanaList.indexOf(e.kanaex, 0)]; value = selectghostvalueList[selectkanaList.indexOf(kana, 0)]; kanafield.text = kana; valuefield.text = String(value);} else {kana = ""; value = 0; kanafield.text = ""; valuefield.text = "";}}}} private var error:String; private function SetAlpha(e:StatusBox):void { if (isSetBox == true) {this.alpha = 0; this.mouseEnabled = false; } } static private var scorelist:Array = [[]]; private function setinplace():void { if (isSet==true) { /*var lob1:Sprite = new lob(kana, value); lob1.x = xx; lob1.y = yy; stage.addChild(lob1);*/ removeEventListener(StatusBox.SETDOWN, setinplace); stage.removeChild(this);} else {stage.removeChild(this);} } static private var turnscore:uint; static private function calctotalscore(main:Vector.<uint>,side:Vector.<uint>):uint { var tws:uint; var twm:uint; var amws:uint; var asws:uint; for (var i:uint = 0; (handstatus.length - 1); i += 1) {if (handstatus[i] == "set") { if (side[i] > 0) {asws += (side[i] + (exclusionvalue[i] * LM[i])) * WM[i]; } amws += main[i] + (exclusionvalue[i] * LM[i]) twm += WM[i] generalx.push(exclusionx[i]); generaly.push(exclusiony[i]); generalkana.push(exclusionkana[i]); generalvalue.push(exclusionvalue[i]);}} exclusionx = new Vector.<uint> exclusiony = new Vector.<uint> exclusionkana = new Vector.<String> exclusionvalue= new Vector.<uint> tws = (asws + amws) * twm; return tws;} private function checkforwordtype(wordcheck:Vector.<Boolean>):Boolean { for (var i:uint = 0; handstatus.length - 1; i += 1) { var check:Boolean = false; if (handstatus[i] == "set") {if (wordcheck[i] == true) {check = true;}}} return check;} private var endgame:Boolean; private var playerhandkana:Vector.<String> = new Vector.<String>(7); private var playerhandvalue:Vector.<uint> = new Vector.<uint>(7); private var valuefield:TextField; private function keyboardinput(e:KeyboardEvent):void { if (mode == 2 || 3 || 4 || 5||8) {if (e.keyCode == Keyboard.I) { vis = !vis; if ((isSet=false)&&(isSetBox=false)) {this.visible = vis; this.kanafield.visible = vis; this.valuefield.visible = vis;}}} if (mode == 8) {if (e.keyCode == Keyboard.R) {ret = !ret; }}} private var kanafield:TextField = new TextField(); static private var generalx:Vector.<uint>; static private var generaly:Vector.<uint>; static private var generalkana:Vector.<String>; static private var generalvalue:Vector.<uint>; static private var exclusionx:Vector.<uint>; static private var exclusiony:Vector.<uint>; static private var exclusionvalue:Vector.<uint>; static private var exclusionkana:Vector.<String>; private function addExclusion():void {exclusionx[id]=xx; exclusiony[id] = yy; exclusionkana[id] = kana; exclusionvalue[id] = value; } private function removeExclusion():void { exclusionvalue[id] = 0; exclusionkana[id] = "0"; exclusionx[id] = 0; exclusiony[id] = 0; } //The initial event performed when the button is first clicked; private function draglocation(e:MouseEvent):void { removeEventListener(MouseEvent.MOUSE_DOWN, draglocation); initialx = this.x; initialy = this.y; if (isSet==false ||isSetBox == false) { stage.addChild(this) this.startDrag(); this.addEventListener(MouseEvent.MOUSE_UP, clickcheck);} } private function clickcheck(e:Event):void { if (isSetBox==false || isSet == false) { this.stopDrag(); removeEventListener(MouseEvent.MOUSE_UP, clickcheck);} finalx = this.x; finaly = this.y; if ((((finaly - initialy) ^ 2 + (finalx - initialx) ^ 2)^0.5) < 5) {HandleDoubleClick(); } } private function HandleDoubleClick():void {if (this.x < 480 && this.y < 480) {if (isSet == false) {isSet = true; this.stopDrag(); xx= int((this.x+16) / 32); this.x = 32*xx; yy= int((this.y+16) / 32); this.y = (32 * yy); for (var i:uint = 0; i < (exclusionx.length-1); i += 1) {if (xx == exclusionx[i] && yy == exclusiony[i]) {notSet = true }} if (generalx.length > 0) {var notSet:Boolean; for (var q:uint = 0; q < (generalx.length - 1); q += 1) {if (xx == generalx[q] && yy == generaly[q]) {notSet = true } else {notSet=false}}} if (notSet == false) {handstatus[id] = "set"; addExclusion(); notSet = true; } else {isSet = false;}} else { handstatus[id] = "idle"; removeExclusion();}} else if (this.x > 480 && this.y < 480 && this.x < 704) {if (isSetBox == false) {setonbox(); } else {takeoffbox(); }} } static private var killsetBox: Boolean; static private var WM:Vector.<uint>; static private var LM:Vector.<uint>; static private var horzword:Vector.<Boolean>; static private var vertword:Vector.<Boolean>; static private var idtoreplace:uint; private function rawscore(calcx:int, calcy:int):uint { var xincr:uint = 1; var yincr:uint = 1; var value:uint = 0; while ((Number(boardarray[xx + (calcx * xincr)][yy + calcy * yincr])) != 0) { value += (boardarray[xx + (calcx * xincr)][yy + calcy * yincr]); xincr += 1; yincr += 1; } if (value == 0) { for (var i:uint = 0; exclusionx.length - 1;i+=1) { if (((exclusionx[i] == exclusionx[id]+calcx) && (exclusiony[i] == exclusiony[id] + calcy))) {if (Math.abs(calcx) == 1) { horzword[id] = true;} else {vertword[id] = true; } } } } return value; } static private var valuehor:Vector.<uint>; static private var valuevert:Vector.<uint>; static private var boardarray:Array=new Array[[]]; private function checkscore():void { switch(multiplier[exclusionx[id], exclusiony[id]]) {case "TW": WM[id] = 3; LM[id] = 1; break; case "DW": WM[id] = 2; LM[id] = 1; break; case "TL": LM[id] = 3; WM[id] = 1; break; case "DL": LM[id] = 2; WM[id] = 1; break; default: LM[id] = 1; WM[id] = 1;} valuehor[id] = rawscore(1, 0) + rawscore( -1, 0); valuevert[id] = rawscore(0, 1) + rawscore(0, -1); } private function cleanup():void { if (mode == 2 || 3 || 4 || 5) { yplace = 0; if (killsetBox=false) {isSetBox = false; handstatus[id] = "idle"; } else {if (isSetBox ==true) { this.visible = false; this.kanafield.visible = false; this.valuefield.visible = false; handstatus[id] = "not"; killsetBox = false; } } }} private var first:Boolean = true; private function kanachange(e:Set):void { if (id==handstatus.indexOf(e.kanaex,0)) {kana = e.kanaex; value = e.valueex; kanafield.text = kana; valuefield.text = String(value); playerhandkana[id] = e.kanaex; playerhandvalue[id] = e.valueex;} else { kana = ""; value = 0; handstatus[id] = "not";}} private function setonbox():void {addEventListener(Set.BOARD_SET_CHANGED, kanachange); if (mode==3) {isSetBox = true; this.x = 480; this.y = 448 - (yplace * 32); handstatus[id] = "ret";} else if (mode == 4) { if (yplace == 0) {dispatchEvent(new Set(Set.BOX_SET_CHANGED, kana, 0)); isSetBox = true; this.x = 480; this.y = 448 - (yplace * 32); handstatus[id] = "rem";} } else if (mode == 5) { { isSetBox = true; this.x = 480; this.y = 448 - (yplace * 32);} if (yplace == 0) {dispatchEvent(new Set(Set.BOX_SET_CHANGED, "kanji", value)); } else if (yplace > 0) {dispatchEvent(new Set(Set.BOX_SET_CHANGED, "k+", value)); } yplace += 1; }} private function takeoffbox():void { removeEventListener(Set.BOARD_SET_CHANGED, kanachange); isSetBox = false; if (mode == 3) { handstatus[id] = "idle"; isSetBox=false} else if (mode ==4) { if (yplace == 1) {dispatchEvent(new Set(Set.BOX_SET_CHANGED, kana, 1)); isSetBox = false; handstatus[id] = "idle" } else if (mode == 5) { if (yplace == 1) {dispatchEvent(new Set(Set.BOX_SET_CHANGED, "nokanji", value)); } else if (yplace > 1) {dispatchEvent(new Set(Set.BOX_SET_CHANGED, "k-", value)); }} handstatus[id] = "idle"; yplace-= 1; }} private function goodX(inX:Number):Number {if (inX < 0) {return 0;} if (inX > (stage.stageWidth) ) {return (stage.stageWidth); }return inX;} private function goodY(inY:Number):Number { if (inY < 0) {return 0; } if (inY > stage.stageHeight) {return stage.stageHeight;} return inY; } private function turn1():void {if (playerRound > playernumber) {playerRound = 1; round += 1; } } }}
Your constructor shouldn't have a return type. Try: public function tile(i:uint,kana1:String,value1:uint, type1:uint) { id = i; kana = kana1; value = value1; type = type1; addEventListener(Event.ADDED_TO_STAGE, go); // this function will be called when you create a new tile object } Also, another potential problem in the future is your init method doesn't have any parameters so it will throw an error if your Event.ADDED_TO_STAGE triggers the init method. Try: private function init(e:Event = null):void
Action Script 3. How to add timer?
I'm creating Flash "memory" game, Idea to discover 2 equal cards. But when I choose 1, if second card is wrong It discover only for half second, but this is not enough. I need to make that second card will be shown for 2-3 seconds. How can I add timer? Here is part of code: else { trace("wrong"); _message = "wrong"; message_txt.text = _message; _firstCard.gotoAndPlay("flipBack"); event.currentTarget.gotoAndPlay("flipBack"); _firstCard.addEventListener(MouseEvent.CLICK, checkCards); event.currentTarget.addEventListener(MouseEvent.CLICK, checkCards); _firstCard = undefined; } Thank you for answers. UPDATED WITH FULL CODE package { import flash.display.MovieClip; import Card; import Boarder; import BlueBoard; import flash.events.MouseEvent; import RedBoard; import Snow; public class MemoryGame extends MovieClip { private var _card:Card; private var _boarder:Boarder; private var _blueBoard:BlueBoard; private var _cardX:Number; private var _cardY:Number; private var _firstCard:*; private var _totalMatches:Number; private var _currentMatches:Number; private var _redBoard:RedBoard; private var _snow:Snow; private var _cards:Array; public var _message:String; public function MemoryGame() { _cards = new Array(); _totalMatches = 4; _currentMatches = 0; createCards(); } private function createCards():void { _cardX = 45; _cardY = 10; for(var i:Number = 0; i < 2; i++) { _card = new Card(); addChild(_card); _boarder = new Boarder(); _card.setType(_boarder); _card.x = _cardX; _card.y = _cardY; _cardX += _card.width + 50; _card.addEventListener(MouseEvent.CLICK, checkCards); _cards.push(_card); } for(var j:Number = 0; j < 2; j++) { _card = new Card(); addChild(_card); _blueBoard = new BlueBoard(); _card.setType(_blueBoard); _card.x = _cardX; _card.y = _cardY; _cardX += _card.width + 50; _card.addEventListener(MouseEvent.CLICK, checkCards); _cards.push(_card); } _cardX = 45; _cardY = _card.height + 30; for(var k:Number = 0; k < 2; k++) { _card = new Card(); addChild(_card); _redBoard = new RedBoard(); _card.setType(_redBoard); _card.x = _cardX; _card.y = _cardY; _cardX += _card.width + 50; _card.addEventListener(MouseEvent.CLICK, checkCards); _cards.push(_card); } for(var l:Number = 0; l < 2; l++) { _card = new Card(); addChild(_card); _snow = new Snow(); _card.setType(_snow); _card.x = _cardX; _card.y = _cardY; _cardX += _card.width + 50; _card.addEventListener(MouseEvent.CLICK, checkCards); _cards.push(_card); } randomizeCards(_cards); } private function checkCards(event:MouseEvent):void { event.currentTarget.removeEventListener(MouseEvent.CLICK, checkCards); if(_firstCard == undefined) { _firstCard = event.currentTarget; } else if(String(_firstCard._type) == String(event.currentTarget._type)) { trace("match"); _message = "match"; message_txt.text = _message; _firstCard = undefined; _currentMatches ++; if(_currentMatches >= _totalMatches) { trace("YOU WIN !!!"); _message = "YOU WIN !!!"; message_txt.text = _message; } } else { trace("wrong"); _message = "wrong"; message_txt.text = _message; _firstCard.gotoAndPlay("flipBack"); event.currentTarget.gotoAndPlay("flipBack"); _firstCard.addEventListener(MouseEvent.CLICK, checkCards); event.currentTarget.addEventListener(MouseEvent.CLICK, checkCards); _firstCard = undefined; } } private function randomizeCards(cards:Array):void { var randomCard1:Number; var randomCard2:Number; var card1X:Number; var card1Y:Number; for(var i:Number = 0; i < 10; i++) { randomCard1 = Math.floor(Math.random() * cards.length); randomCard2 = Math.floor(Math.random() * cards.length); card1X = cards[randomCard1].x; card1Y = cards[randomCard1].y; cards[randomCard1].x = cards[randomCard2].x; cards[randomCard1].y = cards[randomCard2].y cards[randomCard2].x = card1X; cards[randomCard2].y = card1Y; } } } }
You can use http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/utils/Timer.html. BTW, do note that Timer constructor's default 2nd parameter is 0 implying that the timer would run indefinitely. Be sure to mark that as 1 for your case. You need to move code in your 'else' block to another function and setup the timer instead in the else block. The final code would look something like this: else { trace("wrong"); _message = "wrong"; message_txt.text = _message; _secondCard = event.currentTarget;//You need to have this variable defined alongwith _firstCard var timer:Timer = new Timer(2000, 1); timer.addEventListener(TimerEvent.TIMER_COMPLETE, flipBack); timer.start(); } and the function would have: protected function flipBack(event:TimerEvent):void { _firstCard.gotoAndPlay("flipBack"); _sedondCard.gotoAndPlay("flipBack"); _firstCard.addEventListener(MouseEvent.CLICK, checkCards); _secondCard.addEventListener(MouseEvent.CLICK, checkCards); _firstCard = _secondCard = undefined; } HTH.
If it's only to wait a certain amount of time, you can use setTimeout (flash.utils) http://livedocs.adobe.com/flash/9.0_fr/ActionScriptLangRefV3/flash/utils/package.html#setTimeout()