Quiz Game

I want to create a program like a quizgame. it should read the question from a file, display them. then the user should pick the correct answer.
i have the textfile in this format:
question=What is my Name??
answer.1=Lukas
answer.2=Pedro
answer.3=Juan
answer.4=Alejandro
answer.correct=Lukas
here is my code:
*          The Quiz                                   *
*          by Ionstorms                             *
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.util.Properties;
public class QuizGame extends JFrame implements ActionListener {
     Container MyBox = getContentPane();
     JPanel textareaPanel = new JPanel();
     JPanel buttonsPanel = new JPanel();
     JTextArea textarea = new JTextArea(15,30);
     JScrollPane scroll = new JScrollPane( textarea);
     JButton Answer1 = new JButton( "Answer 1");
     JButton Answer2 = new JButton( "Answer 2");
     JButton Answer3     = new JButton( "Answer 3");
     JButton Answer4 = new JButton( "Answer 4");
     JButton NextQuestion = new JButton( "Next Question");
     JButton Exit = new JButton ( "Exit");
     String AppExit = "";
     String question = "";
     String answer1 = "";
     String answer2 = "";
     String answer3 = "";
     String answer4 = "";
     String correctAnswer = "";
     String userAnswer = "";
     public QuizGame()
          super ("The Quiz");
          setSize(400,500);
          JOptionPane.showMessageDialog(null, "Welcome to \"The Quiz\" PRE-Alpha");
     public void GUI()
           MyBox.setLayout(new BorderLayout());
          MyBox.setBackground(Color.black);
          MyBox.add(textareaPanel, BorderLayout.NORTH);
          MyBox.add(buttonsPanel, BorderLayout.CENTER);
          buttonsPanel.setLayout(new GridLayout(2,3));
          textareaPanel.add(textarea);
          textarea.setEditable(false);
          buttonsPanel.setBackground(Color.black);
          buttonsPanel.add(Answer1, BorderLayout.CENTER );
          buttonsPanel.add(Answer3, BorderLayout.CENTER);
          buttonsPanel.add(NextQuestion, BorderLayout.WEST);
          buttonsPanel.add(Answer2, BorderLayout.WEST);
          buttonsPanel.add(Answer4, BorderLayout.WEST);
          buttonsPanel.add(Exit, BorderLayout.EAST);
          Answer1.addActionListener(this);
          Answer2.addActionListener(this);
          Answer3.addActionListener(this);
          Answer4.addActionListener(this);
          NextQuestion.addActionListener(this);
          Exit.addActionListener(this);
     public void Properties()
          Properties questionProperties = new Properties();
          FileReader questionIn = new FileReader(new File("P:\\Quiz\\QuizGame\\question.txt"));
          questionProperties.read(questionIn);
          String question = questionProperties.getProperty("question.txt");
          String answer1 = questionProperties.getProperty("answer.1");
          String answer2 = questionProperties.getProperty("answer.2");
          String answer3 = questionProperties.getProperty("answer.3");
          String answer4 = questionProperties.getProperty("answer.4");
          String correctAnswer = questionProperties.getProperty("answer.correct");
          textarea.append(question+"\n\n"+answer1+"\n"+answer2+"\n"+answer3+"\n"+answer4);
     public void actionPerformed(ActionEvent event)
          if ( event.getActionCommand().equals("Answer 1"))
               userAnswer = answer1;
               if (userAnswer.equals(correctAnswer))
                    JOptionPane.showMessageDialog(null, "Correct!");
               else
                    JOptionPane.showMessageDialog(null, "You're wrong!");
          if ( event.getActionCommand().equals("Answer 2"))
               userAnswer = answer2;
               if (userAnswer.equals(correctAnswer))
                    JOptionPane.showMessageDialog(null, "Correct!");
               else
                    JOptionPane.showMessageDialog(null, "You're wrong!");
          if ( event.getActionCommand().equals("Answer 3"))
               userAnswer = answer3;
               if (userAnswer.equals(correctAnswer))
                    JOptionPane.showMessageDialog(null, "Correct!");
               else
                    JOptionPane.showMessageDialog(null, "You're wrong!");
          if ( event.getActionCommand().equals("Answer 4"))
               userAnswer = answer4;
               if (userAnswer.equals(correctAnswer))
                    JOptionPane.showMessageDialog(null, "Correct!");
               else
                    JOptionPane.showMessageDialog(null, "You're wrong!");
          if ( event.getActionCommand().equals("Exit"))
               JOptionPane.showMessageDialog(null, "Thank you for using\"The Quiz\"");
               System.exit(0);
          if ( event.getActionCommand().equals("Next Question"))
               JOptionPane.showMessageDialog(null, "Still Working on it!");
     public void init()
     public static void main(String args[])
          QuizGame object = new QuizGame();
          object.GUI();
          object.Properties();
          object.setVisible(true);
}and here is the error message:
--------------------Configuration: QuizGame - JDK version 1.4 <Default>--------------------
P:\Quiz\QuizGame\QuizGame.java:80: cannot resolve symbol
symbol : method read (java.io.FileReader)
location: class java.util.Properties
          questionProperties.read(questionIn);
^
1 error
Process completed.

Well for a start the method is called load not read and secondly it takes an InputStream not a Reader.
The code should read
Properties questionProperties = new Properties();
FileInputStream questionIn = new FileReader(new File("P:\\Quiz\\QuizGame\\question.txt"));
BufferedInputStream bis = new BufferedInputStream(questionIn);
questionProperties.load(bis);

Similar Messages

  • Flash quiz game

    Hi
    I'm making a flash quiz game like instructed in this tutorial. http://www.tu-world.com/flash/flash_tutorial_08.php
    After anwsering, it goes to the next frame, really simple. How is it possible that a anwser would be 50% correct?
    Write actionscript for every button:
    on (release){
    gotoAndPlay("02");
    For RIGHT answer write:
    on (release){
    gotoAndPlay("02");
    score++;
    Last frame AS percent=score/4*100 + "%";
    Best regards
    Ekri

    Hei
    The anwsers in my quiz are 50% correct (half a point) if he/she anwser a question that is close, but not tottaly correct.Or for example
    How clean is your room?
    I clean my room every day 100%
    I clean my house once a week 50%
    Never 0%

  • [HELP] Online Multiplayer Quiz Game!

    Hi, I am wondering if it is possible to make online multiplayer quiz game.
    With that I mean over the LAN network.
    Like it use the bluetooth and you connect to it.
    Like the quiz is to answer 0-20 on german and when you click check it will send the answer to the other phone. Like if my mom have it and says whats wrong and right you know. It would be neat if you did help me!
    Thanks, Sander over here!
    In ActionScript 3 to Air for IOS.

    multiplayer games are for advanced programmers.
    the easiest way to start multiplayer gaming with flash is it use adobe's rtmfp peer-to-peer connections.  here's an excerpt from a book (Flash Game Development: In a Social, Mobile and 3D World) i wrote:
    Multiplayer Games
    With multiplayer games data needs to be communicated among the players.  When a player makes a move (changing the game state) the updated game state needs to be communicated to all the other players. In addition, that communication needs to occur in a timely manner. 
    With turn based games (like card games) that communication among players can take as long as few seconds without degrading the game experience. With real time games (like shooter games), even a 250 millisecond delay in communicating game state leads to a significantly degraded player experience. Consequently, real time multiplayer games require substantial expertise to successfully develop and deploy.
    There are two fundamentally different ways that communication among players can be accomplished. Players can communicate via a server (server based games) or they can communicate directly from player to player (peer-to-peer) games.
    Server Based Multiplayer Games
    Generally, the code in each player’s Flash game handles the player’s input, transmits player data to the server, receives other players' data and displays the game state. The server receives player data, validates the data, updates and maintains game state and transmits each player’s data to the other players.
    The code used on the server cannot be ActionScript so you will need to learn a server-side coding language like php or c#.  Server-side coding is beyond the scope of this book so I will not cover server based multiplayer games except to say you need to have advanced coding skills in, at least, two languages (ActionScript and a server-side language) to create these game types.
    Peer-to-peer games
    Since Flash player 10, you can create multiplayer games without the need of an intermediary server to facilitate player communication.  The Flash player can use a protocol (Adobe's Real-Time Media Flow Protocol) that allows direct peer-to-peer communication.
    Instead of using server-side code to handle the game logic and coordinate game state among players, each peer in the network handles their own game logic and game state and communicates that directly to their peers and each peer updates their game state based on the data received from others.
    To use peer-to-peer networking each peer must connect with an Adobe server.  Peer-to-peer communication does not go through that server (or it that would not be peer-to-peer) but peers must stay connected with the Adobe server in order to communicate with each other.
    To communicate with the Adobe server you should use your own server URL and developer key. That URL and key can be obtained at http://www.adobe.com/cfusion/entitlement/index.cfm?e=cirrus.

  • New ipod 20gb music quiz game

    I was playing the music quiz game last night and today i go to play it again it comes up saying "error no music found" the music on my ipod is working just fine so I dont know what it is. can someone help me?

    what exactly happens when i reset my ipod?
    Resetting your iPod is exactly the same thing as rebooting your PC. It simply restarts the Operating System (OS) of the iPod. No files are touched.
    Updating involves loading a new version of the OS onto the iPod. Again, no user files are touched.
    Restoring completely wipes the iPod clean and puts it back to the original factory condition. All user files are deleted. The version of the Updater software you use will determine the OS version that gets reloaded into the iPod.

  • Help on quiz/game

    So I haven't really coded anything in actionscript for over a year so I am pretty rusty.  However, as the school year is approaching I came up with a cool idea for a game/quiz for my students.  I would like to be able to create a quiz like the one at this link: http://espn.go.com/free-online-games/trivia/namemlbplayer
    Any help on how to get started or get this going would be great.  Thanks.
    Jeremy

    ok, so, I Finally got around to finishing this and am having problems with the scoring feature.  here is my code
    var correctNum:int=0;
    var questionIndex:int=00;
    var question_tf:TextField=new TextField();
    addChild(question_tf);
    question_tf.multiline=true;
    question_tf.width=300;
    question_tf.x=10;
    question_tf.y=100;
    var answer_tf:TextField=new TextField();
    addChild(answer_tf);
    answer_tf.type="input";
    answer_tf.border=true;
    answer_tf.width=200;
    answer_tf.multiline=false;
    answer_tf.x=350;
    answer_tf.y=100;
    var questionA:Array=["the distance a number is from zero", "the number of square units needed to cover a surface", "the length of the outer boundary of a circle", "a whole number greater than 1 that has more than two factors", "the distance across a circle through its center", "a mathematical sentence that includes an equal sign", "shows how many times a number is to be multiplied", "mathematical sentence containing numbers and at least one operation", "the numbers you multiply together to get another number", "a table for organizing a set of data that shows the number or pieces of data that fall within given intervals or categories", "the greatest number that is a factor of two or more numbers", "a positive or negative whole number and zero", "the least of the nonzero common multiples of a group of numbers", "the average of a set of numbers", "the number in the middle of a set of data when the data is arranged in numerical order", "the value in a set of data that appears most often", "the product of a number and a whole number", "addition, subtraction, multiplication, division", "the rules to follow when more than one operation is used in a numerical expression, PEMDAS", "the distance around a closed geometric figure", "a whole number greater than 1 that has exactly two factors, 1 and itself", "the ratio of the number of ways a certain event can occur to the number of possible outcomes", "an equation that shows 2 ratios are equivalent", "the distance from the center to any point on a circle", "the difference between the highest and the lowest number in a data set", "a comparison of two numbers by division", "a number that can be written as a fraction", "the steepness of a line", "a rate with a denominator of 1", "a symbol that represents a quantity in an algebraic equation"];
    var answerA:Array=["absolute value", "area", "circumference", "composite", "diameter", "equation", "exponent", "expression", "factor", "frequency table", "greatest common factor", "integer", "least common multiple", "mean", "median", "mode", "multiple", "operations", "order of operations", "perimeter", "prime", "probability", "proportion", "radius", "range", "ratio", "rational number", "slope", "unit rate", "variable"];
    var numberA:Array=[];
    for(var i:int=0;i<questionA.length;i++){
    numberA.push(i);
    shuffle(numberA);
    submitBtn.addEventListener(MouseEvent.CLICK,submitF);
    nextQuestionF();
    function nextQuestionF():void{
    answer_tf.text="";
    question_tf.text=questionA[numberA[questionIndex]];
    function submitF(e:MouseEvent):void{
    if(answer_tf.text.toLowerCase()==answerA[questionIndex]){
      correctNum++;
    questionIndex++;
    if(questionIndex<questionA.length){
      nextQuestionF();
    } else {
      endQuizF();
    function endQuizF():void {
    removeChild(answer_tf);
    question_tf.text="You answered "+correctNum+" questions correctly and "+(questionA.length-correctNum)+" questions incorrectly";
    function shuffle(a:Array){
    var p:int;
    var t:*;
    var ivar:int;
    for (ivar = a.length-1; ivar>=0; ivar--) {
      p=Math.floor((ivar+1)*Math.random());
      t = a[ivar];
      a[ivar] = a[p];
      a[p] = t;
    The scoring does not work.  I can't find the problem.  Any help would be appreciated.
    Thanks.

  • Coding question for quiz game

    Hi,
    I want to create a quiz where the user can narrow down the list of possible questions by choosing from several menus.  Eg: User chooses "Cities", "Northern Hemisphere" and "Europe" which narrows the list of possible questions.  The code then needs to determine which questions are valid or invalid and then randomly ask the user only the valid questions.
    Firstly, in Actionscript, how can the program narrow the valid list.  Secondly, how can it randomly choose questions only from the remaining valid list?
    Should I be using Arrays?  An external database?
    Thanks, Andrew.

    OK, I'll give it my best shot.  I'm still re-familiarising myself with Actionscript syntax so I'll just use crude pseudocode (pigeon VB).  By the way, this program is not actually a quiz, it's a guitar fretboard training program.
    Let's say I start out with about 130 button symbols that represent each note on the fretboard.  Each one is linked to a different unique boolean variable eg: var_E1, var_F1, var_F#1 etc.
    The user can select from two menus; scale and fret position which are linked to two variables var_scale and var_fret which will change certain buttons to "true" and others to "false"
    allbuttons.active = false (this disables all buttons before the quiz starts)
         if scalemenu.selection = var_Gmajor then; (this selects the appropriate scale)
              if positionmenu.selection = var_3rdposition then;  (this selects the appropriate position)
                       var_G1 = true
                       var_A1 = true
                       var_B1 = true
                       var_C1 = true
                       var_D1 = true
                       var_E1 = true
                       var_F# = true
                       var_G2 = true
              end;
    end;
    (This is the part I'm not too sure how to do)
    command;
         determine all variables that are true; (is there a function that does this?)
             create list of all true variables; (in a temporary array?)
                   select a random item from this list and store it in var_question;
                        questiondisplaybox.text = var_question  (display the question)
                   if answer = correct then
                        answerdisplaybox.text = "correct"  (This tells the user if they're right or not)
                        var_score = var_score + 1;   (This adds to the users score tally)
                   end
    end;
    I hope that's not too crude.  Like I said, the part I don't know how to do is to determine all the variables that are true, create a temporary list of these variables, then display one of them randomly.
    Andrew.

  • How to Display a game score throughout the Scenes

    Hi there Actionscript geniuses. I have stumble upon this problem. As a novice in actionscript in particular and programming in general, I am very pleased that I manage to pull this scoreboard script ( listed below), for my quiz game. The script is simple, it adds points when clicking on the right button, and subtract points when clicking on the wrong button. The problem is that while this script works great on my first scene, it doesn't work on my next scene anymore. The buttons are not working and the score board is back to zero, it's as if the script does not exists. In both scenes the buttons and the text objects are the same symbols, as well the Instance names. The script resides inside actionscript .as file. What is missing or wrong in this script or concept?
    I understand the dilemmas regarding using scenes, some people love them and some hate them. I also notice that Adobe itself warns about the use of scenes, but never the less, because of the current level of my flash pro cc 14 knowledge, I incline to use them.
    package {
      import flash.display.MovieClip
      import flash.events.MouseEvent;
      public class scoreMe2 extends MovieClip {
      public function scoreMe2() {
      //Scoreboard starts here:
      var score: uint;
      function init(): void {
      score = 100;
      scorecounter.text = "SCORE:" + score.toString();
      clip.buttonMode = true;
      clip.addEventListener(MouseEvent.CLICK, on_press1);
      gButton.buttonMode = true;
      gButton.addEventListener(MouseEvent.CLICK, on_press2);
      button_2.buttonMode = true;
      button_2.addEventListener(MouseEvent.CLICK, fl_ClickToGoToScene);
      //Positive button adding points
      function on_press1(event: MouseEvent): void {
      updateScore();
      function updateScore(): void {
      gotoAndStop(2);
      score += 100;
      scorecounter.text = "SCORE:" + score.toString()
      function fl_ClickToGoToScene(event: MouseEvent): void {
      MovieClip(this.root).gotoAndPlay(1, "Scene 2");
      //Negative button subtracting points
      function on_press2(event: MouseEvent): void {
      score += -20;
      scorecounter.text = "SCORE:" + score.toString();
      init();
      //Scoreboard ends here:

    It's not really a matter of love or hate, it's a matter of practicality.  Scenes work well for uscripted animations that flow from one section to the next.  When you start involving coding and navigation you are heading into a troublesome realm if you choose to use scenes.  They are simply problematic when you start to try to use them with code.
    Your best bet is to create separate movieclips as your scenes and place them along the timeline of the first scene.  That way you can easily have all your variables at the ready by having them in a layer that extends the length of the timeline needed.  You should be able to convert to this somewhat easily if you just copy the scene timelines into movieclips.

  • Ipod nano 5th gen games...

    i want to get the ipod nano 5th gen with the camera, but does it come with the music quiz game?

    No.

  • The logos game wont work

    As you have probable heard of the new thing, the logo quiz game, which is pretty popular. mine wont work.. i have been using it a lot lately coz it is fun, but then the other day i couldnt open it? i press it and then it goes onto it, and before i even start playing it just goes straight out of it again.
    but is there a way i could fix it without deleteing the app and removing all the data i have played on the game? please help!

    Try here:
    iOS: Troubleshooting applications purchased from the App Store

  • Help me with this quiz

    I am developing a quiz game, He will get the questions to an xml, I would create a random, but this have  to select different answers without repeat.
    I need make a code  to tell me how many nodes have xml, and after I select a node at random and return me, but then this never happens again.
    someone help me?

    Harry tanks for your help,
    but still unable to resolve, soo in my first frame i have this code
    function onQuizData(success)
        var quizNode = this.firstChild;
        var quizTitleNode = quizNode.firstChild;
        title = quizTitleNode.firstChild.nodeValue;
        var i = 0;// o numero complexo i=0
        var itemsNode = quizNode.childNodes[1];
        while (itemsNode.childNodes[i])
            var itemNode = itemsNode.childNodes[i];
            var questionNode = itemNode.childNodes[0];
            quizItems[i] = new QuizItem(questionNode.firstChild.nodeValue);
            var a = 1;
            var answerNode = itemNode.childNodes[a++];
            while (answerNode)
                var isCorrectAnswer = false;
                if (answerNode.attributes.correct == "y")
                    isCorrectAnswer = true;
                } // end if
                quizItems[i].addAnswer(answerNode.firstChild.nodeValue, isCorrectAnswer);
                answerNode = itemNode.childNodes[a++];
            } // end while
            ++i;
        } // end while
        gotoAndPlay(_currentframe + 1);
    } // End of the function
    var quizItems = new Array();
    var myData = new XML();
    myData.ignoreWhite = true;
    myData.onLoad = onQuizData;
    myData.load("questionario/questionario.xml");
    stop ();
    -- 2º frame--
    this frame contain the variable to the frame where I have the quiz
    var valores = quizItems.length;
    var currentQuestionNumber = 1;
    var numOfQuestionsAnsweredCorrectly = 0;
    var numOfQuestionsAnsweredIncorrectly = 0;
    var d1 = 1;
    trace(valores);
    --3ºframe--
    this is the frame where i wont select the aleatory response without repeat
    if (numeracao < quizItems.length)
    var array:Array = new Array(quizItems.length);
    currentQuestionNumber = Math.round(Math.random() * valores);
    else if (numeracao > quizItems.length){
    gotoAndStop(22);
    trace(currentQuestionNumber);
    var currentQuizItem = quizItems[currentQuestionNumber - 1];
    var hasAnswered = false;
    question = currentQuizItem.getQuestion();
    var i = 1;
    while (i <= currentQuizItem.getNumOfAnswers())
        _root["answer" + i] = currentQuizItem.getAnswer(i - 1);
        _root["answer" + i + "textBox"]._visible = true;
        _root["answer" + i + "Button"]._visible = true;
        _root["answer" + i + "Mark"]._visible = true;
        ++i;
    } // end while
    while (i <= 4)
        _root["answer" + i + "textBox"]._visible = false;
        _root["answer" + i + "Button"]._visible = false;
        _root["answer" + i + "Mark"]._visible = false;
        ++i;
    } // end while
    stop ();

  • Help needed with creating Flash game

    Hello,
    I need to create Flash educational/quiz game for one of my clients. It would be based on concept like these ones for example:
    Example 1
    http://go.ucsusa.org/game/
    Example 2
    http://www.zdravlje.hr/igre/stop-aids/
    Note: when you open this link you will see two text boxs which you first must fill. On the left side text box "Upišite ime" means "Type your name" and right one "Upišite godinu svog rođenja" means "Year of birth"
    What is interesting about this type of games is that they are classic games (for example game Labirint where you have to find way out), but during play pop-up questions starts to appear to test end user knowledge abot certain topic (in example 2 topic is about AIDS/HIV). In case of my client, topic is about Eco environment.
    Here is where my trouble starts;) : I found many useful free tutorials how to create simple flash game (most interesting example I found is this one http://www.strille.net/tutorials/snake/index.php)  BUT I dont know how make that system of popup questions appear during game similar to Example 1 and Example 2?
    Any help is appreciated and thanks in advance for promt reply.
    Greetings,
    Adnan

    Update: I have just read all instructions in Snake tutorial which helped be better realize how Snake game works.
    a) This is what I plan to realize for my client:
    1. Snake game which end users will play and during play pop-up/quiz quesions will appear on topic Eco environment;
    2. For example when end user earns 50 points he must answer some of the random questions like "Q:How many ton of waste are produced by US livestock each year" with three answers A1: "1 milion" A2: "1 bilion" A3: "2 bilion" and after user scores 100 points then another question pops up and so on. This is all true if all answers are correct but in case he answer some question wrong than game can start from begining or another solution could be he looses -50 or -100 points.
    3. At the end, user which gains most points wins.
    b) This is what I have done till now:
    I have this file http://www.strille.net/tutorials/snake/snakeGameWithHighscore.zip which I partly understand how it works with my Flash knowladge.
    All functions and main game engine is in layer code:
    "// Snake Game by Strille, 2004, www.strille.net
    blockSize = 8;   // the block width/height in number of pixels
    gameHeight = 30; // the game height in number of blocks
    gameWidth  = 45; // the game width in number of blocks
    replaySpeed = 1;
    SNAKE_BLOCK = 1; // holds the number used to mark snake blocks in the map
    xVelocity = [-1, 0, 1, 0]; // x velocity when moving left, up, right, down
    yVelocity = [0, -1, 0, 1]; // y velocity when moving left, up, right, down
    keyListener = new Object(); // key listener
    keyListener.onKeyDown = function() {
        var keyCode = Key.getCode(); // get key code
        if (keyCode > 36 && keyCode < 41) { // arrow keys pressed (37 = left, 38 = up, 39 = right, 40 = down)...
            if (playRec) {
                if (keyCode == 37 && replaySpeed > 1) {
                    replaySpeed--;
                } else if (keyCode == 39 && replaySpeed < 10) {
                    replaySpeed++;
            } else if (game.onEnterFrame != undefined) { // only allow moves if the game is running, and is not paused
                if (keyCode-37 != turnQueue[0]) { // ...and it's different from the last key pressed
                    turnQueue.unshift(keyCode-37); // save the key (or rather direction) in the turnQueue
        } else if (keyCode == 32) { // start the game if it's not started (32 = SPACE)
            if (!gameRunning || playRec) {
                startGame(false);
        } else if (keyCode == 80) { // pause/unpause (80 = 'P')
            if (gameRunning && !playRec) {
                if (game.onEnterFrame) { // pause
                    delete game.onEnterFrame; // remove main loop
                    textMC.gotoAndStop("paused");
                } else { // exit pause mode
                    game.onEnterFrame = main; // start main loop
                    textMC.gotoAndStop("hide");
    Key.addListener(keyListener);
    function startGame(pRec) {
        x = int(gameWidth/2); // x start position in the middle
        y = gameHeight-2;     // y start position near the bottom
        map = new Array(); // create an array to store food and snake
        for (var n=0;n<gameWidth;n++) { // make map a 2 dimensional array
            map[n] = new Array();
        turnQueue = new Array(); // a queue to store key presses (so that x number of key presses during one frame are spread over x number of frames)
        game.createEmptyMovieClip("food", 1); // create MC to store the food
        game.createEmptyMovieClip("s", 2); // create MC to store the snake
        scoreTextField.text = "Score: 0"; // type out score info
        foodCounter = 0; // keeps track of the number of food movie clips
        snakeBlockCounter = 0; // keeps track of the snake blocks, increased on every frame
        currentDirection = 1; // holds the direction of movement (0 = left, 1 = up, 2 = right, 3 = down)
        snakeEraseCounter = -1; // increased on every frame, erases the snake tail (setting this to -3 will result in a 3 block long snake at the beginning)
        score = 0; // keeps track of the score
        ticks = lastRec = 0;
        recPos = recFoodPos = 0;
        playRec = pRec;
        if (!playRec) {
            textMC.gotoAndStop("hide"); // make sure no text is visible (like "game over ")
            highscores.enterHighscoreMC._visible = false;
            statusTextField.text = "";
            recTurn = "";
            recFrame = "";
            recFood = "";
            game.onEnterFrame = main; // start the main loop
        } else {
            if (loadedRecordingNumber != -1) {
                var n = getLoadedRecordingNumberHighscorePos(loadedRecordingNumber);
                statusTextField.text = "Viewing " + highscores[n].name.text + "'s game (score " + highscores[n].score.text + ")";
            } else {
                statusTextField.text = "Viewing your game";
            game.onEnterFrame = replayMain; // start the main loop
        placeFood("new"); // place a new food block
        gameRunning = true; // flag telling if the game is running. If true it does not necessarily mean that main is called (the game could be paused)
    function main() { // called on every frame if the game is running and it's not paused
        if (playRec) {
            if (ticks == lastRec+parseInt(recFrame.charAt(recPos*2)+recFrame.charAt(recPos*2+1), 36)) {
                currentDirection = parseInt(recTurn.charAt(recPos));
                lastRec = ticks;
                recPos++;
        } else if (turnQueue.length) { // if we have a turn to perform...
            var dir = turnQueue.pop(); // ...pick the next turn in the queue...
            if (dir % 2 != currentDirection % 2) { // not a 180 degree turn (annoying to be able to turn into the snake with one key press)
                currentDirection = dir; // change current direction to the new value
                recTurn += dir;
                var fn = ticks-lastRec;
                if (fn < 36) {
                    recFrame += " "+new Number(fn).toString(36);
                } else {
                    recFrame += new Number(fn).toString(36);
                lastRec = ticks;
        x += xVelocity[currentDirection]; // move the snake position in x
        y += yVelocity[currentDirection]; // move the snake position in y
        if (map[x][y] != SNAKE_BLOCK && x > -1 && x < gameWidth && y > -1 && y < gameHeight) { // make sure we are not hitting the snake or leaving the game area
            game.s.attachMovie("snakeMC", snakeBlockCounter, snakeBlockCounter, {_x: x*blockSize, _y: y*blockSize}); // attach a snake block movie clip
            snakeBlockCounter++; // increase the snake counter
            if (map[x][y]) { // if it's a not a vacant block then there is a food block on the position
                score += 10; // add points to score
                scoreTextField.text = "Score: " + score; // type out score info
                snakeEraseCounter -= 5; // make the snake not remove the tail for five loops
                placeFood(map[x][y]); // place the food movie clip which is referenced in the map map[x][y]
            map[x][y] = SNAKE_BLOCK; // set current position to occupied
            var tailMC = game.s[snakeEraseCounter]; // get "last" MC according to snakeEraseCounter (may not exist)
            if (tailMC) { // if the snake block exists
                delete map[tailMC._x/blockSize][tailMC._y/blockSize]; // delete the value in the array m
                tailMC.removeMovieClip(); // delete the MC
            snakeEraseCounter++; // increase erase snake counter   
        } else { // GAME OVER if it is on a snake block or outside of the map
            if (playRec) {
                startGame(true);
            } else {
                gameOver();
            return;
        ticks++;
    function replayMain() {
        for (var n=0;n<replaySpeed;n++) {
            main();
    function gameOver() {
        textMC.gotoAndStop("gameOver"); // show "game over" text
        delete game.onEnterFrame; // quit looping main function
        gameRunning = false; // the game is no longer running
        enterHighscore();
    function placeFood(foodMC) {
        if (playRec) {
            var xFood = parseInt(recFood.charAt(recFoodPos*3)+recFood.charAt(recFoodPos*3+1), 36);
            var yFood = parseInt(recFood.charAt(recFoodPos*3+2), 36);
            recFoodPos++;
        } else {
            do {
                var xFood = random(gameWidth);
                var yFood = random(gameHeight);
            } while (map[xFood][yFood]); // keep picking a spot until it's a vacant spot (we don't want to place the food on a position occupied by the snake)
            if (xFood < 36) {
                recFood += " "+new Number(xFood).toString(36);
            } else {
                recFood += new Number(xFood).toString(36);
            recFood += new Number(yFood).toString(36);
        if (foodMC == "new") { // create a new food movie clip
            foodMC = game.food.attachMovie("foodMC", foodCounter, foodCounter);
            foodCounter++;
        foodMC._x = xFood*blockSize; // place the food
        foodMC._y = yFood*blockSize; // place the food
        map[xFood][yFood] = foodMC; // save a reference to this food movie clip in the map
    //- Highscore functions
    loadHighscores();
    enterHighscoreKeyListener = new Object();
    enterHighscoreKeyListener.onKeyDown = function() {
        if (Key.getCode() == Key.ENTER) {
            playerName = highscores.enterHighscoreMC.nameTextField.text;
            if (playerName == undefined || playerName == "") {
                playerName = "no name";
            saveHighscore();
            Key.removeListener(enterHighscoreKeyListener);
            Key.addListener(keyListener);
            highscores.enterHighscoreMC._visible = false;
            loadedRecordingNumber = -1;
            startGame(true);
    function enterHighscore() {
        if (score >= lowestHighscore) {
            highscores.enterHighscoreMC._visible = true;
            highscores.enterHighscoreMC.focus();
            Key.removeListener(keyListener);
            Key.addListener(enterHighscoreKeyListener);
        } else {
            loadedRecordingNumber = -1;
            startGame(true);
    function getLoadedRecordingNumberHighscorePos(num) {
        for (var n=0;n<10;n++) {
            if (num == highscores[n].recFile) {
                return n;
    function loadHighscores() {
        vars = new LoadVars();
        vars.onLoad = function(success) {
            for (var n=0;n<10;n++) {
                var mc = highscores.attachMovie("highscoreLine", n, n);
                mc._x = 5;
                mc._y = 5+n*12;
                mc.place.text = (n+1) + ".";
                mc.name.text = this["name"+n];
                mc.score.text = this["score"+n];
                mc.recFile = parseInt(this["recFile"+n]);
            lowestHighscore = parseInt(this.score9);
            if (!gameRunning) {
                loadRecording(random(10));
            delete this;
        if (this._url.indexOf("http") != -1) {
            vars.load("highscores.txt?" + new Date().getTime());
        } else {
            vars.load("highscores.txt");
    function loadRecording(num) {
        vars = new LoadVars();
        vars.onLoad = function(success) {
            if (success && this.recTurn.length) {
                recTurn = this.recTurn;
                recFrame = this.recFrame;
                recFood = this.recFood;
                startGame(true);
            } else {
                loadRecording((num+1)%10);
                return;
            delete this;
        loadedRecordingNumber = num;
        if (this._url.indexOf("http") != -1) {
            vars.load("rec"+loadedRecordingNumber+".txt?" + new Date().getTime());
        } else {
            vars.load("rec"+loadedRecordingNumber+".txt");
    function saveHighscore() {
        sendVars = new LoadVars();
        for (var n in _root) {
            if (_root[n] != sendVars) {
                sendVars[n] = _root[n];
        returnVars = new LoadVars();
        returnVars.onLoad = function() {
            if (this.status == "ok") {
                loadHighscoresInterval = setInterval(function() {
                    loadHighscores();
                    clearInterval(loadHighscoresInterval);
                }, 1000);
            delete sendVars;
            delete this;
        sendVars.sendAndLoad("enterHighscore.php", returnVars, "POST");
    function startClicked() {
        if (!gameRunning || playRec) {
            if (highscores.enterHighscoreMC._visible) {
                Key.removeListener(enterHighscoreKeyListener);
                Key.addListener(keyListener);
                highscores.enterHighscoreMC._visible = false;
            startGame(false);
    function viewGame(lineMC) {
        loadRecording(lineMC.recFile);
        statusTextField.text = "Loading " + lineMC.name.text + "'s game...";
    Now what is left to do is somehow to iclude educational quiz in this game/code. First idea that came to me is same thing Ned suggested: to create some unique movie clip which would contain all data/questions lined up but main problem for me is how to "trigger" that movie clip to play only AFTER end user clicks on "Start game" or SPACE to restart? Not sure how to solve this issue?

  • Training Software (with quiz ability)

    Is there a training sw program (with quiz ability) I could use to deliver online training to others that would be compatible with my iMac w/ Microsoft Office for Apple??

    Maureen,
    Keynote would be the closest thing in the iWork suite to being able to do what you seem to be looking for. Check out this tutorial on the MacMost site describing how to create a quiz in KN.
    http://macmost.com/creating-quiz-games-in-iwork-keynote.html
    Jerry

  • MultiPlayer Game Lobby

    hi guys,
    I've got an plan for a simple 2 player quiz game against a
    timer to test Adobe's new services. I have ideas how I might be
    able to use Stratus to send xml questions to opponent (as
    bytearray?) and get the 2 clients sending each other notifications
    as to when questions are anwsered. However How would I set up a
    Lobby so players can actually find each other? would I need a
    Cocomo account for the lobby? and then use Stratus for gameplay? or
    would you suggest doing the whole thing in Cocomo? I'm a little
    unsure how Stratus can be used for 'Mulitplayer Games' as
    suggested? Any pointers would be ace, thxs paddy ;)

    You don't really need "real-time" info for lobbies IMHO. Any
    server-side system (such as PHP) should be able to do something
    like this. You maintain a simple database of "games" and present
    this list to the player. If fact, in most situations you'll want to
    maintain a lit of current games and some game state variables
    throughout the life of a game so some kind of server-side
    persistent storage is probably a good thing.
    Each game would have a separate state ("playing", "waiting
    for players" etc...). A player can make a new game so you make a
    new DB entry with the game name/id, a status of "waiting for
    players" and the player details (so those attempting to join can
    establish a connection). Make a lobby screen that queries and lists
    all games with a state of "waiting for players" and simply have
    clients on the lobby screen auto "refresh" the list every 5
    seconds. Once a player selects a game to join you establish the
    connection and either change the state of the game in the DB or
    remove the entry from the table.

  • [Package Quiz] How well do you know your installed packages?

    Hi,
    While checking around and having fun with pyalpm library (alpm wrapper for python), I created a really simple quiz game. It askes you questions about installed packages on your system. Get it! (only 2.4 kbs)
    It doesn't have a aur page because I don't know how to do that stuff . In order to be able to run it you will need to have pyqt and pyalpm installed. Then just run gui.py
    Have fun!
    Yaşar Arabacı
    Edit: updated link
    Last edited by yasar11732 (2011-07-15 17:45:58)

    caminoix wrote:
    Haha, that's a funny idea!
    I think you'll need to work a little on the difficulty of questions if you plan to continue the project.
    – Some are too hard: installed size in the first place, that was a good guess of yours, but packagers and some dependencies are pretty tough, too.
    – Some are too easy: the what package installed … questions can be mostly guessed by filenames
    But personally, what I'd welcome most is some info on some of the more obscure packages. This way I could learn a bit about my system while having fun. Installed size is not terribly useful. A little description of the actual purpose of the package would be more enlightening. An example: gtk3 is described as "The GTK+ Toolkit (v3)". It is true, I know. But if your game told me that it's a set of libraries for building graphical user interfaces which is most notably used by Gnome and XFCE, and which is essentially responsible for the look and feel of their applications, I'd be actually smarter than before.
    Some packages that I feel would be good candidates for this kind of description are: apr, attr, babl, damageproto, gegl, jack, libxau, neon, orc, speex, tdb. xcb-util.
    First of all, thanks for your feedback. I agree that installed size questions too hard too. I might just remove them, it is quite easy. But about the descriptions, I directly use the package description on the system. The one you get when you issue pacman -Qi somepackage. Otherwise it would require tons of time adding description for all the packages.
    I guess next thing I would do for this project is to balance the difficulties.

  • IPod stuck in Music Quiz mode

    The strangest thing happened to me the other day. I was playing the music quiz game, quit, and tried to simply listen to some music. To my shock, however, my iPod continued to only play the 10-second clip from the quiz game for each song. The first song of any playlist I selected would start at the beginning and play for 10 seconds, and the rest would just pick up at some point in the middle. I managed to fix the situation by entering and exiting the quiz game again, but I remain completely baffled by this little experience. Has anything like this happened to anyone else out there? Does anyone know how it could have happened, or how to make it happen voluntarily?

    this happened to me a couple of years ago with a 4g b/w. same solution too.

Maybe you are looking for

  • ERecruitment:  Unregistered Application Wizard (hrrcf_a_reg_applwzd_unreg)

    We have an issue where if you provide URL of application group to candidate, adn you have not registered, you get logon after filling in personal information (First, Last, Email Address x 2).  The candidate record is created, but the application wiza

  • Reading data in a tab in an excel sheet

    Hi, I would like to read the data in an excel sheet and upload into an internal table for processing. I was able to do it using function module ALSM_EXCEL_TO_INTERNAL_TABLE but I am not able to read a particular tab. My excel sheet has tabls like A,

  • Zen Touch: problem with touch pad and formatt

    Hi guys! I have a Zen Touch 20gb but I'm experiencing big problems with my touch pad: it really doesn't work fine, precision is almost none, to poit the desired voice in any menu I have to work hard. If the menu is longer it is almost impossible to n

  • Oracle CASE statement logic

    Hi all, I have to compare the value of a varchar variable using a CASE statement and display the corresponding output. But when the following code is being executed, and i gave the value of dayrange as anything other than number, i am getting the err

  • Pricing Requisition and PO

    Hi, There is a specific requirement in our project to price requisition and PO based on customers(Customers defined in Accounts receivables) specific pricing. Client(Who is implementing Oracle Applications) negotiates special cost for a customer or g