Latest Tutorials| Questions and Answers|Ask Questions?|Site Map




Have Programming Question? Ask it here!
 
 
 


mo afsar
game
3 Answer(s)      2 years and a month ago
Posted in : Java3D


How to make 3D game in java Applet


Advertisement
View Answers

July 24, 2012 at 12:19 PM


Here is a code of snake game in java swing.

1)SnakeGame.java:

import javax.swing.JFrame;

public class SnakeGame extends JFrame {

public SnakeGame() {

add(new Snake());

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(320, 340);
setLocationRelativeTo(null);
setTitle("Snake");

setResizable(false);
setVisible(true);
}

public static void main(String[] args) {
new SnakeGame();
}
}

2)Snake.java:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class Snake extends JPanel implements ActionListener {
private final int WIDTH = 300;
private final int HEIGHT = 300;
private final int DOT_SIZE = 10;
private final int ALL_DOTS = 900;
private final int RAND_POS = 29;
private final int DELAY = 140;
private int x[] = new int[ALL_DOTS];
private int y[] = new int[ALL_DOTS];
private int dots;
private int apple_x;
private int apple_y;
private boolean left = false;
private boolean right = true;
private boolean up = false;
private boolean down = false;
private boolean inGame = true;
private Timer timer;
private Image ball;
private Image apple;
private Image head;
public Snake() {
addKeyListener(new TAdapter());
setBackground(Color.black);
ImageIcon iid = new ImageIcon(this.getClass().getResource("image3.gif"));
ball = iid.getImage();
ImageIcon iia = new ImageIcon(this.getClass().getResource("image2.png"));
apple = iia.getImage();
ImageIcon iih = new ImageIcon(this.getClass().getResource("image1.gif"));
head = iih.getImage();
setFocusable(true);
initGame();
}
public void initGame() {
dots = 3;
for (int z = 0; z < dots; z++) {
x[z] = 50 - z*10;
y[z] = 50;
}
locateStar();
timer = new Timer(DELAY, this);
timer.start();
}


July 24, 2012 at 12:20 PM


continue....

public void paint(Graphics g) {
super.paint(g);
if (inGame) {
g.drawImage(apple, apple_x, apple_y, this);
for (int z = 0; z < dots; z++) {
if (z == 0)
g.drawImage(head, x[z], y[z], this);
else g.drawImage(ball, x[z], y[z], this);
}
Toolkit.getDefaultToolkit().sync();
g.dispose();
} else {
gameOver(g);
}
}
public void gameOver(Graphics g) {
String msg = "Game Over";
Font small = new Font("Helvetica", Font.BOLD, 14);
FontMetrics metr = this.getFontMetrics(small);
g.setColor(Color.white);
g.setFont(small);
g.drawString(msg, (WIDTH - metr.stringWidth(msg)) / 2,
HEIGHT / 2);
}
public void checkApple() {
if ((x[0] == apple_x) && (y[0] == apple_y)) {
dots++;
locateStar();
}
}
public void move() {
for (int z = dots; z > 0; z--) {
x[z] = x[(z - 1)];
y[z] = y[(z - 1)];
}
if (left) {
x[0] -= DOT_SIZE;
}
if (right) {
x[0] += DOT_SIZE;
}
if (up) {
y[0] -= DOT_SIZE;
}
if (down) {
y[0] += DOT_SIZE;
}
}
public void checkCollision() {
for (int z = dots; z > 0; z--) {
if ((z > 4) && (x[0] == x[z]) && (y[0] == y[z])) {
inGame = false;
}
}
if (y[0] > HEIGHT) {
inGame = false;
}
if (y[0] < 0) {
inGame = false;
}
if (x[0] > WIDTH) {
inGame = false;
}
if (x[0] < 0) {
inGame = false;
}
}
public void locateStar() {
int r = (int) (Math.random() * RAND_POS);
apple_x = ((r * DOT_SIZE));
r = (int) (Math.random() * RAND_POS);
apple_y = ((r * DOT_SIZE));
}
public void actionPerformed(ActionEvent e) {
if (inGame) {
checkApple();
checkCollision();
move();
}
repaint();
}
private class TAdapter extends KeyAdapter {
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if ((key == KeyEvent.VK_LEFT) && (!right)) {
left = true;
up = false;
down = false;
}
if ((key == KeyEvent.VK_RIGHT) && (!left)) {
right = true;
up = false;
down = false;
}
if ((key == KeyEvent.VK_UP) && (!down)) {
up = true;
right = false;
left = false;
}
if ((key == KeyEvent.VK_DOWN) && (!up)) {
down = true;
right = false;
left = false;
}
}
}
}


July 24, 2012 at 12:21 PM


Here is a code of TicTacToe game. We usually say cross and zero to it.

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TicTacToe implements ActionListener {
private int[][] winCombinations = 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}};
private JFrame window = new JFrame("Tic-Tac-Toe");
private JButton buttons[] = new JButton[9];
private int count, xWins, oWins = 0;
private String letter = "";
private boolean win = false;
public TicTacToe(){
window.setSize(300,300);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setLayout(new GridLayout(3,3));
window.setLocationRelativeTo(null);
for(int i=0; i<=8; i++){
buttons[i] = new JButton();
window.add(buttons[i]);
buttons[i].addActionListener(this);
}
window.setVisible(true);
}
public void actionPerformed(ActionEvent a) {
count++;
if(count % 2 == 0){
letter = "O";
} else {
letter = "X";
}
JButton pressedButton = (JButton)a.getSource();
pressedButton.setText(letter);
pressedButton.setEnabled(false);
for(int i=0; i<=7; i++){
if( buttons[winCombinations[i][0]].getText().equals(buttons[winCombinations[i][1]].getText()) &&
buttons[winCombinations[i][1]].getText().equals(buttons[winCombinations[i][2]].getText()) &&
buttons[winCombinations[i][0]].getText() != ""){
win = true;
}
}
if(win == true){
if (count % 2 == 0){
JOptionPane.showMessageDialog(null, "Player O WINS the game!");
saveName();
playAgainDialog();
}else
JOptionPane.showMessageDialog(null, "Player X WINS the game!");
saveName();
playAgainDialog();
} else if(count == 9 && win == false){
JOptionPane.showMessageDialog(null, "The game was tie!");
playAgainDialog();
}
}
public void playAgainDialog() {
if(letter.equals("X")) xWins++;
else oWins++;
int response = JOptionPane.showConfirmDialog(null, "Do you want to play again?","Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if(response == JOptionPane.YES_OPTION) reset();
else window.hide();
}
public void reset() {
for (int i=0; i<=8; i++){
buttons[i].setText("");
buttons[i].setEnabled(true);
}
win = false;
count = 0;
}
public void saveName(){
int response = JOptionPane.showConfirmDialog(null, "Do you want to save your name?","Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if(response == JOptionPane.YES_OPTION){
String name= JOptionPane.showInputDialog(null,"Enter Name (Player X or Player O)");
try{
File file = new File("TicTacToe.txt");
FileWriter fstream = new FileWriter(file,true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(name);
out.newLine();
out.close();
}
catch(Exception e){}
}
}
public static void main(String[] args){
new TicTacToe();
}
}


Related Tutorials/Questions & Answers:
Game
Game  How to develop a game using java? give me a total code for any simple game
game
game  How to make 3D game in java Applet
Advertisements
Game
Game  how can create simple game in java . thank u so match ,please help
game
game  Hi thank you for answers.I am devoloping a java game caled Duck Hunt Game in netbeans6.7.1 software and I need help in some codes...,if you have this game's code please post me as soon as possible
java game
java game  Can anyone please give me a game source code
game programming
game programming  Hi. i have witten the script and have almost completed developing a social game like mafia wars. can any one plz help me by answering me some of my doubts.. after uploading the game on facebook how tokeep data
JAVA Game
JAVA Game  I want to make a JAVA game...in dat game...d player has to input a word in 10 secnds...4 dat m running a delay loop... but the problem is not...i am not getting any way...to make that input field(eg: String str
game Nim - Java Beginners
game Nim  how is the search tree for a game Nim looks like
tetris game code - Swing AWT
tetris game code  To develop a JAVA puzzle game which is a "variation" of the Tetris game
Blackjack game - IDE Questions
Blackjack game  Create a java code for a simple blackjack game for just one hand of Blackjack, it does not need to include money and betting
Create a Swamp Game in Java
Create a Swamp Game in Java  You are to create a game called ‚??Get Out of My Swamp‚??. In this game an ogre, called ‚??Hek‚??, wanders around his... two ogre enemies in the same place they kill the ogre and the game ends. Full
Java Game Pontoon
Java Game Pontoon  Could someone help me create a programme for the game pontoon //play a game of pontoon import java.util.*; public class Pontoon { public static void main (String args[]) { //deal initial hands
Create a guessing game - Framework
Create a guessing game  Create a guessing game that picks a random number between 1 and 100 and lets you keep guessing until you get it right! You have two decisions to make. The first one tells you whether your guess was TOO
Java game Pontoon
Java game Pontoon  Hello. I have trouble with my pontoon code. I ahve done it using simple java programming. It is working BUT it dosent stops when the players hand rises ober 24 points. where in game the player should be bust
Java program for connectfour game
connectFour game. I need help with resolving the logic for this problem. I appreciate...; ConnectFourServer game = new ConnectFourServer(); private ConnectFourClient..., player, turn, num, full; boolean filled; /* The game board is a grid
How do i slow down the game (othello game)??
How do i slow down the game (othello game)??  Hello, I built an othello game that can be played by 2 humans , human and computer and two computers... with each other the fram doesn't appear until the game is finish. I think it is becase
Can anyone assist with the coding of this game?
Can anyone assist with the coding of this game?  I am in need of the coding for this game. I need to write a "Hangman" game that will randomly generate a word from a text file and will prompt the user to guess one letter
Two user chess game - Applet
Two user chess game  Write a program for a two user chess game(Users must be on different systems)? please send me this source code to my mail id with step by step explanation
game programming code - Swing AWT
game programming code  write a snake program using swings with step by step explanation?. please send me this source code to my mail id with step by step explanation
Craps Game Java Programming Help
Craps Game Java Programming Help  Craps is a casino game that involves the throwing of a pair of dice. Based on the throw, the thrower either gets to continue throw (and win money), or stops throwing (and loses money). Write your
BRICK-BREAKER game concept - Java Beginners
BRICK-BREAKER game concept  I am planning to write a program for BRICK-BREAKER GAME. can any 1 help me any 1 can u plz help me frzzz?? you can also send the mails to poramboku.me@gmai.com
Java game bulls and cows
Java game bulls and cows In this tutorial, you will learn how to implement bulls and cows game in java. The game bulls and cows is an ancient game...;quit", the user will come out from the game. If the user inputs 4 digit
How to design a little game
How to design a little game In this example we are going to design a little game which is used by the children easily. New File: Take a new file with appropriate size. Rounded Rectangle Tool: Choose Rounded Rectangular
who know full coding of guessing game in java?
who know full coding of guessing game in java?  There is only 1 player. Use JAVA Random toolkit to generate random number between 1 to 10. Once user... again or to exit the game by type 1 to proceed the game and type 2 to end the game
Game and Graphic Books
Game and Graphic Books         Computer Game Developer I've always thought game developers were born, not made. True greatness comes from within
plz help me to write a snake game using swings - Swing AWT
plz help me to write a snake game using swings  write snake game program using swings
XP Bowling Game User input help
XP Bowling Game User input help  I was asked to do the XP Bowling Example as an assignment. I have the programme passing all tests, but now I need to make the code accept input from a user and display the scores/frames
genaral snake game in java - Java Beginners
genaral snake game in java  can u please send code for fallowing write a snake game program using swings?  Hi This is the source code of Snake game in swing Snake.java file import javax.swing.JFrame
How to design a remote of the game.
How to design a remote of the game.       Hey, do you want to brush up your designing skill? Then come forward to design a video game remote by using Photoshop. This tutorial
20 question Game involving recursive methods
20 question Game involving recursive methods  I have a problem with compiling my program. Any help please. My code of line where it says "Node first = question.new Node()" i get the error"String.Node cannot be resolved
iPhone Game Applications Development, iPhone Game Porting Services, iPhone Game Designing
iPhone Game Applications Development iPhone Game Development.... Benefits of iPhone Game Development There are many benefits.... Features of Rose India iPhone Game Development Services Rose
iPhone Game Development Company
iPhone Game Development Company Since the evaluation of the video games... to the addiction of playing games. The game industry is booming day by day and thousands of new games are being introduced by game development companies across
Mobile Game Developers
Mobile Game Developers A mobile game is very different from handheld video game that is played on PlayStation portable or with remote on television or computer. A mobile game here refers to a video game played on a mobile phone
Open Source Game Engine
Open Source Game Engine Genesis3D Open Source Engine Genesis3D...-featured game engine. It is being developed to fulfill the needs of military training...: A HLA networking component for the Game Manager that support an Agile FOM interface
Flex Mobile Phone Game Development
Flex Mobile Phone Game Development Games are always mean of entertainment... that specializes in Flex mobile phone game development for all types of mobile phones... team of Flex Mobile Phone Game Development that comprises from super specialists
Mobile J2ME Game Development Services, J2ME Mobile Game Application Solutions, Mobile Games Development
Mobile J2ME Game Development J2ME Mobile Games Development Solutions from Rose... time. Rose India is a mobile game development games company that has mastered the J2ME game application development platform to deliver immersive 3D based
Code rally
Code rally       A Java-based, real-time programming game based on the Eclipse platform. What is CodeRally? CodeRally is a Java?-based, real-time programming game based
What is Gamification?
. Basically the term signifies the incorporation of typically game attributes, game thinking pattern or game mechanics in a non-game context to achieve better... are provided in a game like design. For instance in a web portal informing you
Guess Number Games in Java
Guess Number Games in Java Here we are going to create guess number game where user have to guess the randomly generated number. For this, we have allowed... will like to quit from the game, you can press 'quit'button.   Here
What is LARP?
of the characters during playing the game.  This game is based on any specific theme... or storyline was developed/written by  one or more moderator or  game master. The user decides what to choose a single or more characters of  the game
Java ME
of entertainment in the real life because mobile game is user friendly and portable.... As a result, graphics are getting better and similarly game play is getting better.     Mobile Game Constraints Features such as memory
Chess Application In Java Swing
.style1 { margin-right: 0px; } Chess Application In Java Swing       In this section, you will learn how to create chess game in java swing
Software Consulting Revolutionizing The Way You Do Business
Software Consulting – Revolutionizing The Way You Do Business Running a business is hard enough but when it comes to one on the IT industry you had better be on top of your game. Just as in any other line of business you hire
J2ME Canvas Example
; A J2ME Game Canvas Example This example illustrates how to create a game using GameCanvas class. In this example we are extending GameCanvas class...;display = Display.getDisplay(this);   display.setCurrent(game);  
GPS in Geocaching Games
; Geocaching is an outdoor treasure haunting game that requires... of discovering a new place generate interest for this game. Geo cache can be of any size... are ready to explore the thrill and adventure of the game. The sole aim of the game
What is JavaScript and its Features?
JavaScript is a scripting programming language that is used to make desktop widgets, applications, dynamic websites, PDF documents, developing game, etc. All... the browser but now it is also used to develop game and creating desktop applications
Enjoy the Challenge in a Sudoku Mobile Application
Enjoy the Challenge in a Sudoku Mobile Application Sudoku has become one of the most popular types of games that anyone can play. People can play the game online just like how they can play it on a newspaper page. In fact, a Sudoku
Types of Handheld Devices, Handheld Device Software, Handheld Gadgets, What are Handheld Devices
game consoles and so on. Various popular handheld devices... computer (largely obsolete) Handheld game consoles Nintendo DS (NDS) Game Boy, Game Boy
Top 10 Java Applications
Java is the wonder programming language that is widely used for most of the modern day computing jobs, from designing websites to game applications to preparing interactive video to any other application jobs. Without java applications we
 

 

 

DMCA.com