Search Results

Search found 36 results on 2 pages for 'gameover'.

Page 1/2 | 1 2  | Next Page >

  • Opinions on collision detection objects with a moving scene

    - by Evan Teran
    So my question is simple, and I guess it boils down to how anal you want to be about collision detection. To keep things simple, lets assume we're talking about 2D sprites defined by a bounding box. In addition, let's assume that my sprite object has a function to detect collisions like this: S.collidesWith(other); Finally the scene is moving and "walls" in the scene can move, an object may not touch a wall. So a simple implementation might look like this (psuedo code): moveWalls(); moveSprite(); foreach(wall as w) { if(s.collidesWith(w)) { gameover(); } } The problem with this is that if the sprite and wall move towards each other, depending on the circumstances (such as diagonal moment). They may pass though each other (unlikely but could happen). So I may do this instead. moveWalls(); foreach(wall as w) { if(s.collidesWith(w)) { gameover(); } } moveSprite(); foreach(wall as w) { if(s.collidesWith(w)) { gameover(); } } This takes care of the passing through each other issue, but another rare issue comes up. If they are adjacent to each other (literally the next pixel) and both the wall and the sprite are moving left, then I will get an invalid collision since the wall moves, checks for collision (hit) then the sprite is moved. Which seems unfair. In addition, to that, the redundant collision detection feels very inefficient. I could give the player movement priority alleviating the first issue but it is still checking twice. moveSprite(); foreach(wall as w) { if(s.collidesWith(w)) { gameover(); } } moveWalls(); foreach(wall as w) { if(s.collidesWith(w)) { gameover(); } } Am I simply over thinking this issue, should this just be chalked up to "it'll happen rare enough that no one will care"? Certainly looking at old sprite based games, I often find situations where the collision detection has subtle flaws, but I figure by now we can do better :-P. What are people's thoughts?

    Read the article

  • Problems with createImage(int width, int height)

    - by Jonathan
    I have the following code, which is run every 10ms as part of a game: private void gameRender() { if(dbImage == null) { //createImage() returns null if GraphicsEnvironment.isHeadless() //returns true. (java.awt.GraphicsEnvironment) dbImage = createImage(PWIDTH, PHEIGHT); if(dbImage == null) { System.out.println("dbImage is null"); //Error recieved return; } else dbg = dbImage.getGraphics(); } //clear the background dbg.setColor(Color.white); dbg.fillRect(0, 0, PWIDTH, PHEIGHT); //draw game elements... if(gameOver) { gameOverMessage(dbg); } } The problem is that it enters the if statement which checks for the Image being null, even after I attempt to define the image. I looked around, and it seems that createImage() will return null if GraphicsEnvironment.isHeadless() returns true. I don't understand exactly what the isHeadless() method's purpose is, but I thought it might have something to do with the compiler or IDE, so I tried on two, both of which get the same error (Eclipse, and BlueJ). Anyone have any idea what the source of the error is, and how I might fix it? Thanks in advance Jonathan ................................................................... EDIT: I am using java.awt.Component.createImage(int width, int height). The purpose of this method is to ensure the creation of, and edit an Image that will contain the view of the player of the game, that will later be drawn to the screen by means of a JPanel. Here is some more code if this helps at all: public class Sim2D extends JPanel implements Runnable { private static final int PWIDTH = 500; private static final int PHEIGHT = 400; private volatile boolean running = true; private volatile boolean gameOver = false; private Thread animator; //gameRender() private Graphics dbg; private Image dbImage = null; public Sim2D() { setBackground(Color.white); setPreferredSize(new Dimension(PWIDTH, PHEIGHT)); setFocusable(true); requestFocus(); //Sim2D now recieves key events readyForTermination(); addMouseListener( new MouseAdapter() { public void mousePressed(MouseEvent e) { testPress(e.getX(), e.getY()); } }); } //end of constructor private void testPress(int x, int y) { if(!gameOver) { gameOver = true; //end game at mousepress } } //end of testPress() private void readyForTermination() { addKeyListener( new KeyAdapter() { public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); if((keyCode == KeyEvent.VK_ESCAPE) || (keyCode == KeyEvent.VK_Q) || (keyCode == KeyEvent.VK_END) || ((keyCode == KeyEvent.VK_C) && e.isControlDown()) ) { running = false; //end process on above list of keypresses } } }); } //end of readyForTermination() public void addNotify() { super.addNotify(); //creates the peer startGame(); //start the thread } //end of addNotify() public void startGame() { if(animator == null || !running) { animator = new Thread(this); animator.start(); } } //end of startGame() //run method for world public void run() { while(running) { long beforeTime, timeDiff, sleepTime; beforeTime = System.nanoTime(); gameUpdate(); //updates objects in game (step event in game) gameRender(); //renders image paintScreen(); //paints rendered image to screen timeDiff = (System.nanoTime() - beforeTime) / 1000000; sleepTime = 10 - timeDiff; if(sleepTime <= 0) //if took longer than 10ms { sleepTime = 5; //sleep a bit anyways } try{ Thread.sleep(sleepTime); //sleep by allotted time (attempts to keep this loop to about 10ms) } catch(InterruptedException ex){} beforeTime = System.nanoTime(); } System.exit(0); } //end of run() private void gameRender() { if(dbImage == null) { dbImage = createImage(PWIDTH, PHEIGHT); if(dbImage == null) { System.out.println("dbImage is null"); return; } else dbg = dbImage.getGraphics(); } //clear the background dbg.setColor(Color.white); dbg.fillRect(0, 0, PWIDTH, PHEIGHT); //draw game elements... if(gameOver) { gameOverMessage(dbg); } } //end of gameRender() } //end of class Sim2D Hope this helps clear things up a bit, Jonathan

    Read the article

  • game speed problem

    - by Meko
    HI..I made a little game.But this game works on every computer with different speed.I think it is about resolution.I used every thing in paintcomponent.and If I change screen size the game goes slower or faster.And if i run this game on another computer wich has different resolution it also works different. This is my game http://rapidshare.com/files/364597095/ShooterGame.2.6.0.jar and here code public class Shooter extends JFrame implements KeyListener, Runnable { JFrame frame = new JFrame(); String player; Font startFont, startSubFont, timerFont,healthFont; Image img; Image backGround; Graphics dbi; URL url1 = this.getClass().getResource("Images/p2.gif"); URL url2 = this.getClass().getResource("Images/p3.gif"); URL url3 = this.getClass().getResource("Images/p1.gif"); URL url4 = this.getClass().getResource("Images/p4.gif"); URL urlMap = this.getClass().getResource("Images/zemin.jpg"); Player p1 = new Player(5, 150, 10, 40, Color.GREEN, url3); Computer p2 = new Computer(750, 150, 10, 40, Color.BLUE, url1); Computer p3 = new Computer(0, 0, 10, 40, Color.BLUE, url2); Computer p4 = new Computer(0, 0, 10, 40, Color.BLUE, url4); ArrayList<Bullets> b = new ArrayList<Bullets>(); ArrayList<CBullets> cb = new ArrayList<CBullets>(); Thread sheap; boolean a, d, w, s; boolean toUp, toDown; boolean GameOver; boolean Level2; boolean newGame, resart, pause; int S, E; int random; int cbSpeed = 0; long timeStart, timeEnd; int timeElapsed; long GameStart, GameEnd; int GameScore; int Timer = 0; int timerStart, timerEnd; public Shooter() { sheap = new Thread(this); sheap.start(); startFont = new Font("Tiresias PCFont Z", Font.BOLD + Font.ITALIC, 32); startSubFont = new Font("Tiresias PCFont Z", Font.BOLD + Font.ITALIC, 25); timerFont = new Font("Tiresias PCFont Z", Font.BOLD + Font.ITALIC, 16); healthFont = new Font("Tiresias PCFont Z", Font.BOLD + Font.ITALIC, 16); setTitle("Shooter 2.5.1"); setBounds(350, 250, 800, 600); // setResizable(false); setBackground(Color.black); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); addKeyListener(this); a = d = w = s = false; toUp = toDown = true; GameOver = true; newGame = true; Level2 = false; S = E = 0; setVisible(true); } public void paint(Graphics g) { img = createImage(getWidth(), getHeight()); dbi = img.getGraphics(); paintComponent(dbi); g.drawImage(img, 0, 0, this); } public void paintComponent(Graphics g) { repaint(); timeStart = System.currentTimeMillis(); backGround = Toolkit.getDefaultToolkit().getImage(urlMap); g.drawImage(backGround, 0, 0, null); g.setColor(Color.red); g.setFont(healthFont); g.drawString("" + player + " Health : " + p1.health, 30, 50); g.setColor(Color.red); g.drawString("Computer Health : " + (p2.health + p3.health + p4.health), 600, 50); g.setColor(Color.BLUE); g.setFont(timerFont); g.drawString("Time : " + Timer, 330, 50); if (newGame) { g.setColor(Color.LIGHT_GRAY); g.setFont(startFont); g.drawString("Well Come To Shoot Game", 200, 190); g.drawString("Press ENTER To Start", 250, 220); g.setColor(Color.LIGHT_GRAY); g.setFont(startSubFont); g.drawString("Use W,A,S,D and Space For Fire", 200, 250); g.drawString("GOOD LUCK", 250, 280); newGame(); } if (!GameOver) { for (Bullets b1 : b) { b1.draw(g); } for (CBullets b2 : cb) { b2.draw(g); } update(); // Here MOvements for Player and For Fires } if (p1.health <= 0) { g.setColor(p2.col); g.setFont(startFont); g.drawString("Computer Wins ", 200, 190); g.drawString("Press Key R to Restart ", 200, 220); GameOver = true; } else if (p2.health <= 0 && p3.health <= 0 && p4.health <= 0) { g.setColor(p1.col); g.setFont(startFont); g.drawString(""+player+" Wins ", 200, 190); g.drawString("Press Key R to Resart ", 200, 220); GameOver = true; g.setColor(Color.MAGENTA); g.drawString(""+player+"`s Score is " + Timer, 200, 120); } if (Level2) { if (p3.health >= 0) { p3.draw(g); for (CBullets b3 : cb) { b3.draw(g); } } else { p3.x = 1000; } if (p4.health >= 0) { p4.draw(g); for (CBullets b4 : cb) { b4.draw(g); } } else { p4.x = 1000; } } if (p1.health >= 0) { p1.draw(g); } if (p2.health >= 0) { p2.draw(g); } else { p2.x = 1000; } } public void update() { if (w && p1.y > 54) { p1.moveUp(); } if (s && p1.y < 547) { p1.moveDown(); } if (a && p1.x > 0) { p1.moveLeft(); } if (d && p1.x < 200) { p1.moveRight(); } random = 1 * (int) (Math.random() * 100); if (random > 96) { if (p2.health >= 0) { CBullets bo = p2.getCBull(); bo.xVel =-1-cbSpeed; cb.add(bo); } if (Level2) { if (p3.health >= 0) { CBullets bo1 = p3.getCBull(); bo1.xVel = -2-cbSpeed; cb.add(bo1); } if (p4.health >= 0) { CBullets bo2 = p4.getCBull(); bo2.xVel = -4-cbSpeed; cb.add(bo2); } } } if (S == 1) { if (p1.health >= 0) { Bullets bu = p1.getBull(); bu.xVel = 5; b.add(bu); S += 1; } } //Here Also Problem .. When COmputer have More fire then it gaves Array Exeption . Or Player have More Fire for (int i = cb.size() -1; i = 0 ; i--) { boolean bremoved = false; for (int j = b.size() -1 ; j =0 ; j--) { if (b.get(j).rect.intersects(cb.get(i).rect) || cb.get(i).rect.intersects(b.get(j).rect)) { bremoved = true; b.remove(j); } } if(bremoved) cb.remove(i); } for (int i = 0; i < b.size(); i++) { b.get(i).move(); if (b.get(i).rect.intersects(p2.rect)) { if (p2.health >= 0) { p2.health--; b.remove(i); // System.out.println("Hited P2"); i--; continue; } } if (b.get(i).rect.intersects(p3.rect)) { if (p3.health >= 0) { p3.health--; b.remove(i); // System.out.println("Hited P3"); i--; continue; } } if (b.get(i).rect.intersects(p4.rect)) { if (p4.health >= 0) { p4.health--; b.remove(i); // System.out.println("Hited P4"); i--; continue; } } if (b.get(i).rect.x > 790) { b.remove(i); } } for (int j = 0; j < cb.size(); j++) { cb.get(j).move(); if (cb.get(j).rect.intersects(p1.rect) && cb.get(j).xVel < 0) { p1.health--; cb.remove(j); j--; continue; } } timeEnd = System.currentTimeMillis(); timeElapsed = (int) (timeEnd - timeStart); } public void level2() { if (p2.health <= 10) { Level2 = true; cbSpeed = 4; p3.x = 750; p4.x = 750; p2.speed = 10; p3.speed = 20; p4.speed = 30; } } public void keyTyped(KeyEvent e) { } public void keyPressed(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_ENTER: newGame = false; break; case KeyEvent.VK_P: pause = true; break; case KeyEvent.VK_R: resart = true; break; case KeyEvent.VK_A: a = true; break; case KeyEvent.VK_D: d = true; break; case KeyEvent.VK_W: w = true; break; case KeyEvent.VK_S: s = true; break; case KeyEvent.VK_SPACE: S += 1; break; } } public void keyReleased(KeyEvent e) { switch (e.getKeyCode()) { case KeyEvent.VK_A: a = false; break; case KeyEvent.VK_D: d = false; break; case KeyEvent.VK_W: w = false; break; case KeyEvent.VK_S: s = false; break; case KeyEvent.VK_SPACE: S = 0; break; } } public void newGame() { p1.health = 20; p2.health = 20; p3.health = 20; p4.health = 20; p3.x = 0; p4.x = 0; p2.x = 750; Level2 = false; cbSpeed = 0; p2.speed = 9; b.removeAll(b); cb.removeAll(cb); timerStart = (int) System.currentTimeMillis(); GameOver = false; } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { KeyListener k = new Shooter(); } }); } @Override public void run() { player = JOptionPane.showInputDialog(frame, "Enter Player Name", "New Player", JOptionPane.DEFAULT_OPTION); while (true) { timerEnd = (int) System.currentTimeMillis(); if (resart) { newGame(); resart = false; } if (pause) { Thread.currentThread().notify(); } try { if (!GameOver) { Timer = timerEnd - timerStart; level2(); if (p1.y < p2.y && p2.y60) { p2.moveUp(); } if (p1.y < p3.y && p3.y43) { p3.moveUp(); } if (p1.y < p4.y && p4.y43) { p4.moveUp(); } if (p1.y > p2.y && p2.y<535) { p2.moveDown(); } if (p1.y > p3.y && p3.y<535) { p3.moveDown(); } if (p1.y > p4.y && p4.y<530) { p4.moveDown(); } } if (timeElapsed < 125) { Thread.currentThread().sleep(125); } } catch (InterruptedException ex) { System.out.print("FInished"); } } } }

    Read the article

  • Need help making a check statement to make sure al the controls are not blank

    - by Michael Quiles
    This is for a tic tac toe game. I need help making a check statement to see if all the controls' Texts are non-blank, and if they are, you have a draw (if someone had won the previous code would have discovered that). Can you give me a good example using my code. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using System.Drawing; namespace MyGame { public class Result1 { static private int[,] Winners = new int[,] { // main gameplay Ex: if x is on 0,1,2 x is the winner {0,1,2}, {3,4,5}, {6,7,8}, {0,3,6}, {1,4,7}, {2,5,8}, {0,4,8}, {2,4,6}, }; static public bool CheckWinner(Button[] myControls) { //bolean statement to check for the winner bool gameOver = false; for (int i = 0; i < 8; i++) { int a = Winners[i, 0]; int b = Winners[i, 1]; int c = Winners[i, 2]; Button b1 = myControls[a], b2 = myControls[b], b3 = myControls[c]; if (b1.Text == "" || b2.Text == "" || b3.Text == "") continue; if (b1.Text == b2.Text && b2.Text == b3.Text) { b1.BackColor = b2.BackColor = b3.BackColor = Color.LightCoral; b1.Font = b2.Font = b3.Font = new System.Drawing.Font("Microsoft Sans Serif", 32F, System.Drawing.FontStyle.Italic & System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); gameOver = true; xWinnerForm xWinnerForm = new xWinnerForm(); xWinnerForm.ShowDialog(); //only works with show not showDialog method gets overloaded (b1.Text + " is the Winner"); to get around this I added and image showing the last player } } return gameOver; } } }

    Read the article

  • Need help with if else statement

    - by Michael Quiles
    I'm trying to do an else statement that would tell the user that the game ended in a draw (tic tac toe game). I got it where it works if played and there's a winner it will show another form declaring the winner through an if statement but I cant figure out the its a draw portion. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using System.Drawing; namespace MyGame { public class Result1 { static private int[,] Winners = new int[,] { // main gameplay Ex: if x is on 0,1,2 x is the winner {0,1,2}, {3,4,5}, {6,7,8}, {0,3,6}, {1,4,7}, {2,5,8}, {0,4,8}, {2,4,6}, }; static public bool CheckWinner(Button[] myControls) { //bolean statement to check for the winner bool gameOver = false; for (int i = 0; i < 8; i++) { int a = Winners[i, 0]; int b = Winners[i, 1]; int c = Winners[i, 2]; Button b1 = myControls[a], b2 = myControls[b], b3 = myControls[c]; if (b1.Text == "" || b2.Text == "" || b3.Text == "") continue; if (b1.Text == b2.Text && b2.Text == b3.Text) { b1.BackColor = b2.BackColor = b3.BackColor = Color.LightCoral; b1.Font = b2.Font = b3.Font = new System.Drawing.Font("Microsoft Sans Serif", 32F, System.Drawing.FontStyle.Italic & System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); gameOver = true; xWinnerForm xWinnerForm = new xWinnerForm(); xWinnerForm.ShowDialog(); //only works with show not showDialog method gets overloaded (b1.Text + " is the Winner"); to get around this I added and image showing the last player } //else statement here for draw what code would I put in? } return gameOver; } } }

    Read the article

  • cannot convert from string to system.windows.forms.string iwin32window

    - by Michael Quiles
    This is supposed to show the winner in the xWinner form label but I cant figure it out. xWinnerForm.Show(b1.Text);. I'm new to c# so can you please explain in layman terms thanks. static public bool CheckWinner(Button[] myControls) { bool gameOver = false; for (int i = 0; i < 8; i++) { int a = Winners[i, 0]; int b = Winners[i, 1]; int c = Winners[i, 2]; Button b1 = myControls[a], b2 = myControls[b], b3 = myControls[c]; if (b1.Text == "" || b2.Text == "" || b3.Text == "") continue; if (b1.Text == b2.Text && b2.Text == b3.Text) { gameOver = true; Form xWinnerForm = new xWinnerForm(); xWinnerForm.Show(b1.Text); } public void Show(string text) { this.xWinnerLabel.Text = text; this.Show(); } } return gameOver; }

    Read the article

  • How can show data from another form

    - by Michael Quiles
    This is basically a tic tac toe game, and I have another form called Winner.cs when a player wins I want it to call the form (this part works) and then I want it to say xWinner.label =b1.text"" + has won the game!. the part I cant get to work is displaying the text in the winners form label. There's an example of a message box that commented out for reference instead of b1.text using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; namespace MyGame { public class Result1 { static private int[,] Winners = new int[,] { {0,1,2}, {3,4,5}, {6,7,8}, {0,3,6}, {1,4,7}, {2,5,8}, {0,4,8}, {2,4,6}, }; static public bool CheckWinner(Button[] myControls) { bool gameOver = false; for (int i = 0; i < 8; i++) { int a = Winners[i, 0], b = Winners[i, 1], c = Winners[i, 2]; Button b1 = myControls[a], b2 = myControls[b], b3 = myControls[c]; if (b1.Text == "" || b2.Text == "" || b3.Text == "") continue; if (b1.Text == b2.Text && b2.Text == b3.Text) { b1.BackColor = b2.BackColor = b3.BackColor = System.Drawing.Color.LightCoral; b1.Font = b2.Font = b3.Font = new System.Drawing.Font("Microsoft Sans Serif", 32F, System.Drawing.FontStyle.Italic & System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); gameOver = true; Form xWinnerForm = new xWinnerForm(); xWinnerForm.Show(); //MessageBox.Show(b1.Text + " .... Wins the game!", "Game End", MessageBoxButtons.OK); //break; } } return gameOver; } } }

    Read the article

  • why does array initialization in function other than main is temporary? [on hold]

    - by shafeeq
    This is the code in which i initialize array "turn[20]" in main as well as in function "checkCollisionOrFood()",the four values turn[0],turn[1],turn[2],turn[3] are initialized to zero in main function,rest are being intialized in "checkCollisionOrFood()".This is where fault starts.when i initialize turn[4]=0 in "checkCollisionOrFood()" and then access it anywhere,it remains 0 in any function,but! when i initialize next turn[] i.e turn[5],the value of turn[4] gets depleted .i.e turn[4] have garbage value.turn[20] is global variable,its index"head" is also global.I'm stuck.Plz help me get out of it.Ishall be highly obliged for this act of kindness.This is my excerpt of code unsigned short checkCollisionOrFood(){ head=(head+1)%20; if(turn[head-1]==0){ turn[head]=0; /this is where turn[] is iniliazized and if i access turn[head] here i.e just after iniliazition then it gives correct value but if i access its previous value means turn[head-1]then it gives garbage value/ rowHead=(rowHead+1)%8; if(!(address[colHead]&(1<<rowHead)))return 1; else if((address[colHead]&(1<<rowHead))&& (!((colHead==foody)&&(rowHead==foodx))))gameOver(); else return 0; } if(turn[head-1]==1){ turn[head]=1; colHead=(colHead+1)%8; if(!(address[colHead]&(1<<rowHead)))return 1; else if((address[colHead]&(1<<rowHead))&& (!((colHead==foody)&&(rowHead==foodx))))gameOver(); else return 0; } } void main(void) { turn[0]=0;turn[1]=0;turn[2]=0;turn[3]=0; /these values of turn[] are not changed irrespective of where they are accessed./ while (1) { if(checkCollisionOrFood()) { PORTB=(address[colHead] |=1<<rowHead); turnOffTail(); blink(); } else { PORTB=address[colHead]; createFood(); blink(); } } } Plz help me.

    Read the article

  • How to convert this procedural programming to object-oriented programming?

    - by manus91
    I have a source code that is needed to be converted by creating classes, objects and methods. So far, I've just done by converting the initial main into a separate class. But I don't know what to do with constructor and which variables are supposed to be private. This is the code : import java.util.*; public class Card{ private static void shuffle(int[][] cards){ List<Integer> randoms = new ArrayList<Integer>(); Random randomizer = new Random(); for(int i = 0; i < 8;) { int r = randomizer.nextInt(8)+1; if(!randoms.contains(r)) { randoms.add(r); i++; } } List<Integer> clonedList = new ArrayList<Integer>(); clonedList.addAll(randoms); Collections.shuffle(clonedList); randoms.addAll(clonedList); Collections.shuffle(randoms); int i=0; for(int r=0; r < 4; r++){ for(int c=0; c < 4; c++){ cards[r][c] = randoms.get(i); i++; } } } public static void play() throws InterruptedException { int ans = 1; int preview; int r1,c1,r2,c2; int[][] cards = new int[4][4]; boolean[][] cardstatus = new boolean[4][4]; boolean gameover = false; int moves; Scanner input = new Scanner(System.in); do{ moves = 0; shuffle(cards); System.out.print("Enter the time(0 to 5) in seconds for the preview of the answer : "); preview = input.nextInt(); while((preview<0) || (preview>5)){ System.out.print("Invalid time!! Re-enter time(0 - 5) : "); preview = input.nextInt(); } preview = 1000*preview; System.out.println(" "); for (int i =0; i<4;i++){ for (int j=0;j<4;j++){ System.out.print(cards[i][j]); System.out.print(" "); } System.out.println(""); System.out.println(""); } Thread.sleep(preview); for(int b=0;b<25;b++){ System.out.println(" "); } for(int r=0;r<4;r++){ for(int c=0;c<4;c++){ System.out.print("*"); System.out.print(" "); cardstatus[r][c] = false; } System.out.println(""); System.out.println(" "); } System.out.println(""); do{ do{ System.out.print("Please insert the first card row : "); r1 = input.nextInt(); while((r1<1) || (r1>4)){ System.out.print("Invalid coordinate!! Re-enter first card row : "); r1 = input.nextInt(); } System.out.print("Please insert the first card column : "); c1 = input.nextInt(); while((c1<1) || (c1>4)){ System.out.print("Invalid coordinate!! Re-enter first card column : "); c1 = input.nextInt(); } if(cardstatus[r1-1][c1-1] == true){ System.out.println("The card is already flipped!! Select another card."); System.out.println(""); } }while(cardstatus[r1-1][c1-1] != false); do{ System.out.print("Please insert the second card row : "); r2 = input.nextInt(); while((r2<1) || (r2>4)){ System.out.print("Invalid coordinate!! Re-enter second card row : "); r2 = input.nextInt(); } System.out.print("Please insert the second card column : "); c2 = input.nextInt(); while((c2<1) || (c2>4)){ System.out.print("Invalid coordinate!! Re-enter second card column : "); c2 = input.nextInt(); } if(cardstatus[r2-1][c2-1] == true){ System.out.println("The card is already flipped!! Select another card."); } if((r1==r2)&&(c1==c2)){ System.out.println("You can't select the same card twice!!"); continue; } }while(cardstatus[r2-1][c2-1] != false); r1--; c1--; r2--; c2--; System.out.println(""); System.out.println(""); System.out.println(""); for(int r=0;r<4;r++){ for(int c=0;c<4;c++){ if((r==r1)&&(c==c1)){ System.out.print(cards[r][c]); System.out.print(" "); } else if((r==r2)&&(c==c2)){ System.out.print(cards[r][c]); System.out.print(" "); } else if(cardstatus[r][c] == true){ System.out.print(cards[r][c]); System.out.print(" "); } else{ System.out.print("*"); System.out.print(" "); } } System.out.println(" "); System.out.println(" "); } System.out.println(""); if(cards[r1][c1] == cards[r2][c2]){ System.out.println("Cards Matched!!"); cardstatus[r1][c1] = true; cardstatus[r2][c2] = true; } else{ System.out.println("No cards match!!"); } Thread.sleep(2000); for(int b=0;b<25;b++){ System.out.println(""); } for(int r=0;r<4;r++){ for(int c=0;c<4;c++){ if(cardstatus[r][c] == true){ System.out.print(cards[r][c]); System.out.print(" "); } else{ System.out.print("*"); System.out.print(" "); } } System.out.println(""); System.out.println(" "); } System.out.println(""); System.out.println(""); System.out.println(""); gameover = true; for(int r=0;r<4;r++){ for( int c=0;c<4;c++){ if(cardstatus[r][c]==false){ gameover = false; break; } } if(gameover==false){ break; } } moves++; }while(gameover != true); System.out.println("Congratulations, you won!!"); System.out.println("It required " + moves + " moves to finish it."); System.out.println(""); System.out.print("Would you like to play again? (1=Yes / 0=No) : "); ans = input.nextInt(); }while(ans == 1); } } The main class is: import java.util.*; public class PlayCard{ public static void main(String[] args) throws InterruptedException{ Card game = new Card(); game.play(); } } Should I simplify the Card class by creating other classes? Through this code, my javadoc has no constructtor. So i need help on this!

    Read the article

  • Show Dialog Question

    - by Michael Quiles
    How can I get the Xwinnerform to stay on top an keep the main form from being clicked, I tried ShowDialog but I cant get it to work. static public bool CheckWinner(Button[] myControls) { //bolean statement to check for the winner bool gameOver = false; for (int i = 0; i < 8; i++) { int a = Winners[i, 0]; int b = Winners[i, 1]; int c = Winners[i, 2]; Button b1 = myControls[a], b2 = myControls[b], b3 = myControls[c]; if (b1.Text == "" || b2.Text == "" || b3.Text == "") continue; if (b1.Text == b2.Text && b2.Text == b3.Text) { xWinnerForm xWinnerForm = new xWinnerForm(); xWinnerForm.ShowDialog(b1.Text + " is the Winner"); } } return gameOver; } enter code here

    Read the article

  • How to implement line of sight restriction in actionscript?

    - by Michiel Standaert
    I have a problem with a game i am programming. I am making some sort of security game and i would like to have some visual line of sight. The problem is that i can't restrict my line of sight so my cops can't see through the walls. Below you find the design, in which they can look through windows, but not walls. Further below you find an illustration of what my problem is exactly. this is what it looks like now. As you can see, the cops can see through walls. This is the map i would want to use to restrict the line of sight. So the way i am programming the line of sight now is just by calculating some points and drawing the sight accordingly, as shown below. Note that i also check for a hittest using bitmapdata to check whether or not my player has been spotted by any of the cops. private function setSight(e:Event=null):Boolean { g = copCanvas.graphics; g.clear(); for each(var cop:Cop in copCanvas.getChildren()) { var _angle:Number = cop.angle; var _radians:Number = (_angle * Math.PI) / 180; var _radius:Number = 50; var _x1:Number = cop.x + (cop.width/2); var _y1:Number = cop.y + (cop.height/2); var _baseX:Number = _x1 + (Math.cos(_radians) * _radius); var _baseY:Number = _y1 - (Math.sin(_radians) * _radius); var _x2:Number = _baseX + (25 * Math.sin(_radians)); var _y2:Number = _baseY + (25 * Math.cos(_radians)); var _x3:Number = _baseX - (25 * Math.sin(_radians)); var _y3:Number = _baseY - (25 * Math.cos(_radians)); g.beginFill(0xff0000, 0.3); g.moveTo(_x1, _y1); g.lineTo(_x2, _y2); g.lineTo(_x3, _y3); g.endFill(); } var _cops:BitmapData = new BitmapData(width, height, true, 0); _cops.draw(copCanvas); var _bmpd:BitmapData = new BitmapData(10, 10, true, 0); _bmpd.draw(me); if(_cops.hitTest(new Point(0, 0), 10, _bmpd, new Point(me.x, me.y), 255)) { gameover.alpha = 1; setTimeout(function():void{ gameover.alpha = 0; }, 5000); stop(); return true; } return false; } So now my question is: Is there someone who knows how to restrict the view so that the cops can't look through the walls? Thanks a lot in advance. ps: i have already looked at this tutorial by emanuele feronato, but i can't use the code to restric the visual line of sight.

    Read the article

  • Load previous (last) scene used in unity3d

    - by user3666251
    Im making a 2D game for android and I made over 200 levels/scenes.I also made a game over scene that opens when the players collides with an obscale.In the GameOver scene I added a retry button which I wanna make it so it opens the last level played.Im new in Unity and scripting.I've read other similar questions but none of them fixed my issue.Anyone has any idea that could help ? Im doing this because I don't wanna create over 200 game over scenes and edit each obscale in game. Thank you. Edit : Im using javascript.

    Read the article

  • XNA When to call LoadContent

    - by Peteyslatts
    I have an enum in my game that denotes the game state ie MainMenu, InGame, GameOver, Exit and I was wondering if it would be advisable to add a new one in for PrepGame - in which the game creates viewports for however many players there are, creates the battlefield etc. I feel like this is a good idea except for one thing: should I make a call back to LoadContent() in this state? I could just put a switch statement in the LoadContent for my currentGameState. If it equals PrepGame load things like the skybox, ship models, texures, HUD graphics etc. Or is it a good idea to create an Asset Manager class in the first call to LoadContent() and load everything then. I feel like both approaches have different benefits: faster, but more load times vs slower initial load time, but then all my objects are referencing the same variables so I only have to load each on once. Any help is greatly appreciated. Thanks, Peter

    Read the article

  • How do I set values for a class without using any setter methods?

    - by fari
    Please can anyone help me public class KalaGameState implements Cloneable { // your code goes here public KalaGameState(int startingStones) throws InvalidStartingStonesException { // your code goes here } public int getTurn() { // your code goes here } public int getKala(int playerNum) throws IllegalPlayerNumException { // your code goes here } public int getNumStones(int sidePitNum) throws IllegalSidePitNumException { // your code goes here } public int getNumStones(int playerNum, int sidePitNum) throws IllegalPlayerNumException, IllegalSidePitNumException { // your code goes here } public int getScore(int playerNum) throws IllegalPlayerNumException { // your code goes here } private int getSidePitArrayIndex(int sidePitNum) throws IllegalSidePitNumException { // your code goes here } public boolean gameOver() { // your code goes here } public void makeMove(int sidePitNum) throws IllegalSidePitNumException, IllegalMoveException { // your code goes here } }

    Read the article

  • iPhone Serialization problem

    - by Jenicek
    Hi, I need to save my own created class to file, I found on the internet, that good approach is to use NSKeyedArchiver and NSKeyedUnarchiver My class definition looks like this: @interface Game : NSObject <NSCoding> { NSMutableString *strCompleteWord; NSMutableString *strWordToGuess; NSMutableArray *arGuessedLetters; //This array stores characters NSMutableArray *arGuessedLettersPos; //This array stores CGRects NSInteger iScore; NSInteger iLives; NSInteger iRocksFallen; BOOL bGameCompleted; BOOL bGameOver; } I've implemented methods initWithCoder: and encodeWithCoder: this way: - (id)initWithCoder:(NSCoder *)coder { if([coder allowsKeyedCoding]) { strCompleteWord = [[coder decodeObjectForKey:@"CompletedWord"] copy]; strWordToGuess = [[coder decodeObjectForKey:@"WordToGuess"] copy]; arGuessedLetters = [[coder decodeObjectForKey:@"GuessedLetters"] retain]; // arGuessedLettersPos = [[coder decodeObjectForKey:@"GuessedLettersPos"] retain]; iScore = [coder decodeIntegerForKey:@"Score"]; iLives = [coder decodeIntegerForKey:@"Lives"]; iRocksFallen = [coder decodeIntegerForKey:@"RocksFallen"]; bGameCompleted = [coder decodeBoolForKey:@"GameCompleted"]; bGameOver = [coder decodeBoolForKey:@"GameOver"]; } else { strCompleteWord = [[coder decodeObject] retain]; strWordToGuess = [[coder decodeObject] retain]; arGuessedLetters = [[coder decodeObject] retain]; // arGuessedLettersPos = [[coder decodeObject] retain]; [coder decodeValueOfObjCType:@encode(NSInteger) at:&iScore]; [coder decodeValueOfObjCType:@encode(NSInteger) at:&iLives]; [coder decodeValueOfObjCType:@encode(NSInteger) at:&iRocksFallen]; [coder decodeValueOfObjCType:@encode(BOOL) at:&bGameCompleted]; [coder decodeValueOfObjCType:@encode(BOOL) at:&bGameOver]; } return self; } - (void)encodeWithCoder:(NSCoder *)coder { if([coder allowsKeyedCoding]) { [coder encodeObject:strCompleteWord forKey:@"CompleteWord"]; [coder encodeObject:strWordToGuess forKey:@"WordToGuess"]; [coder encodeObject:arGuessedLetters forKey:@"GuessedLetters"]; //[coder encodeObject:arGuessedLettersPos forKey:@"GuessedLettersPos"]; [coder encodeInteger:iScore forKey:@"Score"]; [coder encodeInteger:iLives forKey:@"Lives"]; [coder encodeInteger:iRocksFallen forKey:@"RocksFallen"]; [coder encodeBool:bGameCompleted forKey:@"GameCompleted"]; [coder encodeBool:bGameOver forKey:@"GameOver"]; } else { [coder encodeObject:strCompleteWord]; [coder encodeObject:strWordToGuess]; [coder encodeObject:arGuessedLetters]; //[coder encodeObject:arGuessedLettersPos]; [coder encodeValueOfObjCType:@encode(NSInteger) at:&iScore]; [coder encodeValueOfObjCType:@encode(NSInteger) at:&iLives]; [coder encodeValueOfObjCType:@encode(NSInteger) at:&iRocksFallen]; [coder encodeValueOfObjCType:@encode(BOOL) at:&bGameCompleted]; [coder encodeValueOfObjCType:@encode(BOOL) at:&bGameOver]; } } And I use these methods to archive and unarchive data: [NSKeyedArchiver archiveRootObject:currentGame toFile:strPath]; Game *currentGame = [NSKeyedUnarchiver unarchiveObjectWithFile:strPath]; I have two problems. 1) As you can see, lines with arGuessedLettersPos is commented, it's because every time I try to encode this array, error comes up(this archiver cannot encode structs), and this array is used for storing CGRect structs. I've seen solution on the internet. The thing is, that every CGRect in the array is converted to an NSString (using NSStringFromCGRect()) and then saved. Is it a good approach? 2)This is bigger problem for me. Even if I comment this line and then run the code successfully, then save(archive) the data and then try to load (unarchive) them, no data is loaded. There aren't any error but currentGame object does not have data that should be loaded. Could you please give me some advice? This is first time I'm using archivers and unarchivers. Thanks a lot for every reply.

    Read the article

  • null pointer exception comparing two strings in java.

    - by David
    I got this error message and I'm not quite sure whats wrong: Exception in thread "main" java.lang.NullPointerException at Risk.runTeams(Risk.java:384) at Risk.blobRunner(Risk.java:220) at Risk.genRunner(Risk.java:207) at Risk.main(Risk.java:176) Here is the relevant bits of code (i will draw attention to the line numbers within the error message via comments in the code as well as inputs i put into the program while its running where relevant) public class Risk { ... public static void main (String[]arg) { String CPUcolor = CPUcolor () ; genRunner (CPUcolor) ; //line 176 ... } ... public static void genRunner (String CPUcolor) // when this method runs i select 0 and run blob since its my only option. Theres nothing wrong with this method so long as i know, this is only significant because it takes me to blob runner and because another one of our relelvent line numbers apears. { String[] strats = new String[1] ; strats[0] = "0 - Blob" ; int s = chooseStrat (strats) ; if (s == 0) blobRunner (CPUcolor) ; // this is line 207 } ... public static void blobRunner (String CPUcolor) { System.out.println ("blob Runner") ; int turn = 0 ; boolean gameOver = false ; Dice other = new Dice ("other") ; Dice a1 = new Dice ("a1") ; Dice a2 = new Dice ("a2") ; Dice a3 = new Dice ("a3") ; Dice d1 = new Dice ("d1") ; Dice d2 = new Dice ("d2") ; space (5) ; Territory[] board = makeBoard() ; IdiceRoll (other) ; String[] colors = runTeams(CPUcolor) ; //this is line 220 Card[] deck = Card.createDeck () ; System.out.println (StratUtil.canTurnIn (deck)) ; while (gameOver == false) { idler (deck) ; board = assignTerri (board, colors) ; checkBoard (board, colors) ; } } ... public static String[] runTeams (String CPUcolor) { boolean z = false ; String[] a = new String[6] ; while (z == false) { a = assignTeams () ; printOrder (a) ; boolean CPU = false ; for (int i = 0; i<a.length; i++) { if (a[i].equals(CPUcolor)) CPU = true ; //this is line 384 } if (CPU==false) { System.out.println ("ERROR YOU NEED TO INCLUDE THE COLOR OF THE CPU IN THE TURN ORDER") ; runTeams (CPUcolor) ; } System.out.println ("is this turn order correct? (Y/N)") ; String s = getIns () ; while (!((s.equals ("y")) || (s.equals ("Y")) || (s.equals ("n")) || (s.equals ("N")))) { System.out.println ("try again") ; s = getIns () ; } if (s.equals ("y") || s.equals ("Y") ) z = true ; } return a ; } ... } // This } closes the class The reason i don't think i should be getting a Null:pointerException is because in this line: a[i].equals(CPUcolor) a at index i holds a string and CPUcolor is a string. Both at this point definatly have a value neither is null. Can anyone please tell me whats going wrong?

    Read the article

  • Game Over function is not working Starling

    - by aNgeLyN omar
    I've been following a tutorial over the web but it somehow did not show something about creating a game over function. I am new to the Starling framework and Actionscript so I'm kind of still trying to find a way to make it work. Here's the complete snippet of the code. package screens { import flash.geom.Rectangle; import flash.utils.getTimer; import events.NavigationEvent; import objects.GameBackground; import objects.Hero; import objects.Item; import objects.Obstacle; import starling.display.Button; import starling.display.Image; import starling.display.Sprite; import starling.events.Event; import starling.events.Touch; import starling.events.TouchEvent; import starling.text.TextField; import starling.utils.deg2rad; public class InGame extends Sprite { private var screenInGame:InGame; private var screenWelcome:Welcome; private var startButton:Button; private var playAgain:Button; private var bg:GameBackground; private var hero:Hero; private var timePrevious:Number; private var timeCurrent:Number; private var elapsed:Number; private var gameState:String; private var playerSpeed:Number = 0; private var hitObstacle:Number = 0; private const MIN_SPEED:Number = 650; private var scoreDistance:int; private var obstacleGapCount:int; private var gameArea:Rectangle; private var touch:Touch; private var touchX:Number; private var touchY:Number; private var obstaclesToAnimate:Vector.<Obstacle>; private var itemsToAnimate:Vector.<Item>; private var scoreText:TextField; private var remainingLives:TextField; private var gameOverText:TextField; private var iconSmall:Image; static private var lives:Number = 2; public function InGame() { super(); this.addEventListener(starling.events.Event.ADDED_TO_STAGE, onAddedToStage); } private function onAddedToStage(event:Event):void { this.removeEventListener(Event.ADDED_TO_STAGE, onAddedToStage); drawGame(); scoreText = new TextField(300, 100, "Score: 0", "MyFontName", 35, 0xD9D919, true); remainingLives = new TextField(600, 100, "Lives: " + lives +" X ", "MyFontName", 35, 0xD9D919, true); iconSmall = new Image(Assets.getAtlas().getTexture("darnahead1")); iconSmall.x = 360; iconSmall.y = 40; this.addChild(iconSmall); this.addChild(scoreText); this.addChild(remainingLives); } private function drawGame():void { bg = new GameBackground(); this.addChild(bg); hero = new Hero(); hero.x = stage.stageHeight / 2; hero.y = stage.stageWidth / 2; this.addChild(hero); startButton = new Button(Assets.getAtlas().getTexture("startButton")); startButton.x = stage.stageWidth * 0.5 - startButton.width * 0.5; startButton.y = stage.stageHeight * 0.5 - startButton.height * 0.5; this.addChild(startButton); gameArea = new Rectangle(0, 100, stage.stageWidth, stage.stageHeight - 250); } public function disposeTemporarily():void { this.visible = false; } public function initialize():void { this.visible = true; this.addEventListener(Event.ENTER_FRAME, checkElapsed); hero.x = -stage.stageWidth; hero.y = stage.stageHeight * 0.5; gameState ="idle"; playerSpeed = 0; hitObstacle = 0; bg.speed = 0; scoreDistance = 0; obstacleGapCount = 0; obstaclesToAnimate = new Vector.<Obstacle>(); itemsToAnimate = new Vector.<Item>(); startButton.addEventListener(Event.TRIGGERED, onStartButtonClick); //var mainStage:InGame =InGame.current.nativeStage; //mainStage.dispatchEvent(new Event(Event.COMPLETE)); //playAgain.addEventListener(Event.TRIGGERED, onRetry); } private function onStartButtonClick(event:Event):void { startButton.visible = false; startButton.removeEventListener(Event.TRIGGERED, onStartButtonClick); launchHero(); } private function launchHero():void { this.addEventListener(TouchEvent.TOUCH, onTouch); this.addEventListener(Event.ENTER_FRAME, onGameTick); } private function onTouch(event:TouchEvent):void { touch = event.getTouch(stage); touchX = touch.globalX; touchY = touch.globalY; } private function onGameTick(event:Event):void { switch(gameState) { case "idle": if(hero.x < stage.stageWidth * 0.5 * 0.5) { hero.x += ((stage.stageWidth * 0.5 * 0.5 + 10) - hero.x) * 0.05; hero.y = stage.stageHeight * 0.5; playerSpeed += (MIN_SPEED - playerSpeed) * 0.05; bg.speed = playerSpeed * elapsed; } else { gameState = "flying"; } break; case "flying": if(hitObstacle <= 0) { hero.y -= (hero.y - touchY) * 0.1; if(-(hero.y - touchY) < 150 && -(hero.y - touchY) > -150) { hero.rotation = deg2rad(-(hero.y - touchY) * 0.2); } if(hero.y > gameArea.bottom - hero.height * 0.5) { hero.y = gameArea.bottom - hero.height * 0.5; hero.rotation = deg2rad(0); } if(hero.y < gameArea.top + hero.height * 0.5) { hero.y = gameArea.top + hero.height * 0.5; hero.rotation = deg2rad(0); } } else { hitObstacle-- cameraShake(); } playerSpeed -= (playerSpeed - MIN_SPEED) * 0.01; bg.speed = playerSpeed * elapsed; scoreDistance += (playerSpeed * elapsed) * 0.1; scoreText.text = "Score: " + scoreDistance; initObstacle(); animateObstacles(); createEggItems(); animateItems(); remainingLives.text = "Lives: "+lives + " X "; if(lives == 0) { gameState = "over"; } break; case "over": gameOver(); break; } } private function gameOver():void { gameOverText = new TextField(800, 400, "Hero WAS KILLED!!!", "MyFontName", 50, 0xD9D919, true); scoreText = new TextField(800, 600, "Score: "+scoreDistance, "MyFontName", 30, 0xFFFFFF, true); this.addChild(scoreText); this.addChild(gameOverText); playAgain = new Button(Assets.getAtlas().getTexture("button_tryAgain")); playAgain.x = stage.stageWidth * 0.5 - startButton.width * 0.5; playAgain.y = stage.stageHeight * 0.75 - startButton.height * 0.75; this.addChild(playAgain); playAgain.addEventListener(Event.TRIGGERED, onRetry); } private function onRetry(event:Event):void { playAgain.visible = false; gameOverText.visible = false; scoreText.visible = false; var btnClicked:Button = event.target as Button; if((btnClicked as Button) == playAgain) { this.dispatchEvent(new NavigationEvent(NavigationEvent.CHANGE_SCREEN, {id: "playnow"}, true)); } disposeTemporarily(); } private function animateItems():void { var itemToTrack:Item; for(var i:uint = 0; i < itemsToAnimate.length; i++) { itemToTrack = itemsToAnimate[i]; itemToTrack.x -= playerSpeed * elapsed; if(itemToTrack.bounds.intersects(hero.bounds)) { itemsToAnimate.splice(i, 1); this.removeChild(itemToTrack); } if(itemToTrack.x < -50) { itemsToAnimate.splice(i, 1); this.removeChild(itemToTrack); } } } private function createEggItems():void { if(Math.random() > 0.95){ var itemToTrack:Item = new Item(Math.ceil(Math.random() * 10)); itemToTrack.x = stage.stageWidth + 50; itemToTrack.y = int(Math.random() * (gameArea.bottom - gameArea.top)) + gameArea.top; this.addChild(itemToTrack); itemsToAnimate.push(itemToTrack); } } private function cameraShake():void { if(hitObstacle > 0) { this.x = Math.random() * hitObstacle; this.y = Math.random() * hitObstacle; } else if(x != 0) { this.x = 0; this.y = 0; lives--; } } private function initObstacle():void { if(obstacleGapCount < 1200) { obstacleGapCount += playerSpeed * elapsed; } else if(obstacleGapCount !=0) { obstacleGapCount = 0; createObstacle(Math.ceil(Math.random() * 5), Math.random() * 1000 + 1000); } } private function animateObstacles():void { var obstacleToTrack:Obstacle; for(var i:uint = 0; i<obstaclesToAnimate.length; i++) { obstacleToTrack = obstaclesToAnimate[i]; if(obstacleToTrack.alreadyHit == false && obstacleToTrack.bounds.intersects(hero.bounds)) { obstacleToTrack.alreadyHit = true; obstacleToTrack.rotation = deg2rad(70); hitObstacle = 30; playerSpeed *= 0.5; } if(obstacleToTrack.distance > 0) { obstacleToTrack.distance -= playerSpeed * elapsed; } else { if(obstacleToTrack.watchOut) { obstacleToTrack.watchOut = false; } obstacleToTrack.x -= (playerSpeed + obstacleToTrack.speed) * elapsed; } if(obstacleToTrack.x < -obstacleToTrack.width || gameState == "over") { obstaclesToAnimate.splice(i, 1); this.removeChild(obstacleToTrack); } } } private function checkElapsed(event:Event):void { timePrevious = timeCurrent; timeCurrent = getTimer(); elapsed = (timeCurrent - timePrevious) * 0.001; } private function createObstacle(type:Number, distance:Number):void{ var obstacle:Obstacle = new Obstacle(type, distance, true, 300); obstacle.x = stage.stageWidth; this.addChild(obstacle); if(type >= 4) { if(Math.random() > 0.5) { obstacle.y = gameArea.top; obstacle.position = "top" } else { obstacle.y = gameArea.bottom - obstacle.height; obstacle.position = "bottom"; } } else { obstacle.y = int(Math.random() * (gameArea.bottom - obstacle.height - gameArea.top)) + gameArea.top; obstacle.position = "middle"; } obstaclesToAnimate.push(obstacle); } } }

    Read the article

  • Unity3D : Retry Menu (Scene Management)

    - by user3666251
    I'm making a simple 2D game for Android using the Unity3D game engine. I created all the levels and everything but I'm stuck at making the game over/retry menu. So far I've been using new scenes as a game over menu. I used this simple script: #pragma strict var level = Application.LoadLevel; function OnCollisionEnter(Collision : Collision) { if(Collision.collider.tag == "Player") { Application.LoadLevel("GameOver"); } } And this as a 'menu': #pragma strict var myGUISkin : GUISkin; var btnTexture : Texture; function OnGUI() { GUI.skin = myGUISkin; if (GUI.Button(Rect(Screen.width/2-60,Screen.height/2+30,100,40),"Retry")) Application.LoadLevel("Easy1"); if (GUI.Button(Rect(Screen.width/2-90,Screen.height/2+100,170,40),"Main Menu")) Application.LoadLevel("MainMenu"); } The problem stands at the part where I have to create over 200 game over scenes, obstacles (the objects that kill the player) and recreate the same script over 200 times for each level. Is there any other way to make this faster and less painful?

    Read the article

  • Unity3D Android : Game Over/Retry

    - by user3666251
    Im making a simple 2D game for android using the Unity3D game engine.I created all the levels and everything but Im stuck at making the game over/retry menu.So far I've been using new scenes as a game over menu.I used this simple script : pragma strict var level = Application.LoadLevel; function OnCollisionEnter(Collision : Collision) { if(Collision.collider.tag == "Player") { Application.LoadLevel("GameOver"); } } And this as a 'menu' : #pragma strict var myGUISkin : GUISkin; var btnTexture : Texture; function OnGUI() { GUI.skin = myGUISkin; if (GUI.Button(Rect(Screen.width/2-60,Screen.height/2+30,100,40),"Retry")) Application.LoadLevel("Easy1"); if (GUI.Button(Rect(Screen.width/2-90,Screen.height/2+100,170,40),"Main Menu")) Application.LoadLevel("MainMenu"); } The problem stands at the part where I have to create over 200 game over scenes,obscales(the objects that kill the player) and recreate the same script over 200 times for each level. Is there any other way to make this faster and less painful? I've been searching the web but didn't find anything useful according to my issue. Thank you.

    Read the article

  • How to animate the sprite along with action in Cocos2d?

    - by user1201239
    Cocos2d-android - I have an animation which has 5 Frames they are close cropped images. Now I want Sprite to do animation as well as Move in X direction.i.e. I have a player running which gets collided with obstacle and falls down .. Now I want sprite to run animation as well as moveBy in -ve x direction gameOverAnimation =CCSprite.sprite("gmovr00") gameOverAnimation.setAnchorPoint(0, 0); gameOverAnimation.setPosition(340.0f, 200.0f); addChild(gameOverAnimation,10); CCIntervalAction action1 = CCAnimate.action(mEndAnimation, false); action1.setDuration(1.0f); CCIntervalAction delay = CCDelayTime.action(0.68f); CCMoveBy actionBy = CCMoveBy.action(1.0f, CGPoint.ccp(-340,0)); CCIntervalAction seq1 = CCSpawn.actions(action1,actionBy); //CCSpawn spawn = CCSpawn.actions(action1, actionBy); CCSequence sequence1 = CCSequence.actions(seq1,CCCallFuncN.action(this,"gameOver")); gameOverAnimation.runAction(sequence1); Above code makes animation run first then moved in y direction Thanks for the help.. And can some one explaing me the concept of time with frame Animation or good example ?

    Read the article

1 2  | Next Page >