Skip to content
Snippets Groups Projects
Commit 22d9a5aa authored by Jie Luo's avatar Jie Luo
Browse files

eclipse game files

parent 6f9bf896
No related branches found
No related tags found
No related merge requests found
Showing
with 959 additions and 706 deletions
hello
\ No newline at end of file
Game_Code/Resources/tutorial.png

4.92 KiB

hello
\ No newline at end of file
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.util.HashMap;
import java.util.HashSet;
import javax.swing.*;
public class Game extends JPanel implements KeyListener, ActionListener {
private int height, width; // the height and width of the screen
private Timer t = new Timer(5, this); // the 't' variable makes sure that there is a initial delay before the same starts off
private boolean first; //game state (starting/playing)
private HashSet<String> keys = new HashSet<String>();
// pad
private final int SPEED = 1; //the speed of the paddles
private int padH = 10, padW = 40; // paddle width/height
private int bottomPadX, topPadX; // these represent the top and the bottom paddles in the game
private int inset = 30; // this helps determine the distance between the paddle
// - and the top and bottom screen boundaries
// ball
private double ballX, ballY, velX = 1, velY = 1, ballSize = 20; //ball position, ball velocity, ball size
// score
private int scoreTop, scoreBottom; // keep track of game record
public Game() {
addKeyListener(this); // it helps to read the commands given through the keyboard
setFocusable(true); // keylisterer knows that it needs to look for the movement through keys
setFocusTraversalKeysEnabled(false); // since the argument is set to false, it moves the focus away from tab and shift keys
first = true; // sets the game state to true to start playing
t.setInitialDelay(100); // sets initial delay for the movement of the ball
t.start(); // set the delay for every movement of the ball
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g; // create an object for graphics (rectangles)
height = getHeight(); // get game frame/screen size
width = getWidth();
// initial positioning
if (first) {
bottomPadX = width / 2 - padW / 2; // setups for the paddles positions - in the middle of the screen
topPadX = bottomPadX;
ballX = width / 2 - ballSize / 2; // setups for the ball positions - in the middle of the screen
ballY = height / 2 - ballSize / 2;
first = false; // setup completed
}
// bottom pad
Rectangle2D bottomPad = new Rectangle(bottomPadX, height - padH - inset, padW, padH); // creating the object for bottom paddle
g2d.fill(bottomPad);
// top pad
Rectangle2D topPad = new Rectangle(topPadX, inset, padW, padH); // creating paddle object for the top paddle
g2d.fill(topPad);
// ball
Ellipse2D ball = new Ellipse2D.Double(ballX, ballY, ballSize, ballSize); // creating the ball object for the game
g2d.fill(ball);
// scores
String scoreB = "Bottom: " + new Integer(scoreBottom).toString(); // saving the score of the bottom paddle
String scoreT = "Top: " + new Integer(scoreTop).toString(); // saving the score of the top paddle
g2d.drawString(scoreB, 10, height / 2); // printing the score of the bottom paddle in the screen
g2d.drawString(scoreT, width - 50, height / 2); // printing the score of the top paddle in the screen
}
@Override
public void actionPerformed(ActionEvent e) {
// side walls
if (ballX < 0 || ballX > width - ballSize) { // making sure ball is horizontally within the frame (left&right)
velX = -velX; // reverse the ball position if trying to go out
}
// top / down walls
if (ballY < 0) { // similarly, for vertical position
velY = -velY; // reverse the ball position vertically
++ scoreBottom;
}
if (ballY + ballSize > height) { // similarly, for the vertical position of bottom paddle
velY = -velY;
++ scoreTop; // points are incremented if the paddle is missed by opponent
}
// bottom pad
if (ballY + ballSize >= height - padH - inset && velY > 0) // similar to the previous parts
if (ballX + ballSize >= bottomPadX && ballX <= bottomPadX + padW)
velY = -velY;
// top pad
if (ballY <= padH + inset && velY < 0)
if (ballX + ballSize >= topPadX && ballX <= topPadX + padW)
velY = -velY;
ballX += velX;
ballY += velY;
// pressed keys
if (keys.size() == 1) {
if (keys.contains("LEFT")) { // left key is pressed
bottomPadX -= (bottomPadX > 0) ? SPEED : 0; // move the bottom paddle to the left
}
else if (keys.contains("RIGHT")) { // right key is pressed
bottomPadX += (bottomPadX < width - padW) ? SPEED : 0;
}
}
// AI
double delta = ballX - topPadX;
if (delta > 0) { // move right if ball is to the right of the paddle
topPadX += (topPadX < width - padW) ? SPEED : 0;
}
else if (delta < 0) { // move left if ball is to the left of the paddle
topPadX -= (topPadX > 0) ? SPEED : 0;
}
repaint();
}
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode(); // get which key is pressed
switch (code) {
case KeyEvent.VK_LEFT:
keys.add("LEFT");
break;
case KeyEvent.VK_RIGHT:
keys.add("RIGHT");
break;
}
}
@Override
public void keyReleased(KeyEvent e) {
int code = e.getKeyCode(); // get which key is released
switch (code) {
case KeyEvent.VK_LEFT:
keys.remove("LEFT");
break;
case KeyEvent.VK_RIGHT:
keys.remove("RIGHT");
break;
}
}
}
import java.awt.*;
import javax.swing.*;
public class Pong_viewAndController extends JFrame{
private JButton suspend = new JButton("Suspend");
private JButton resume = new JButton("Resume");
private JButton save = new JButton("Save");
private JButton exit = new JButton("Exit");
public Pong_viewAndController(){
super("FaultInOurPong");
this.setSize(700,500);
this.setResizable(false);
JPanel game_interface = new JPanel();
game_interface.setLayout(new BoxLayout(game_interface, BoxLayout.X_AXIS));
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel,BoxLayout.Y_AXIS));
suspend.setAlignmentX(Component.CENTER_ALIGNMENT);
buttonPanel.add(suspend);
buttonPanel.add(Box.createVerticalStrut(10));
resume.setMaximumSize(suspend.getPreferredSize());
resume.setAlignmentX(Component.CENTER_ALIGNMENT);
buttonPanel.add(resume);
buttonPanel.add(Box.createVerticalStrut(10));
save.setMaximumSize(suspend.getPreferredSize());
save.setAlignmentX(Component.CENTER_ALIGNMENT);
buttonPanel.add(save);
buttonPanel.add(Box.createVerticalStrut(10));
exit.setMaximumSize(suspend.getPreferredSize());
exit.setAlignmentX(Component.CENTER_ALIGNMENT);
buttonPanel.add(exit);
Game game = new Game();
game_interface.add(buttonPanel);
game_interface.add(game);
add(game_interface);
setLocationRelativeTo(null);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
}
/*public static void main(String[] args){
Pong_viewAndController view_controller = new Pong_viewAndController();
}*/
}
\ No newline at end of file
package model;
/**
* @file Ball.java
* @title Ball
* @author Pongthusiastics
* @date 4/11/2016
* @brief This class represents a ball on the pong game
* @details This class saves the information of a ball, including its position,
* size and the speed.
*/
public class Ball {
/**
* The X position of a ball on the screen
*/
private int positionX;
/**
* The Y position of a ball on the screen
*/
private int positionY;
/**
* The size of a ball
*/
private final int SIZE = 20;
// TODO
private int speed;
/**
* @brief Constructor for Ball
* @details Constructor accepts the x and y position of the ball
* @param x
* is the x-position
* @param y
* is the y-position
*/
public Ball(int x, int y) {
positionX = x;
positionY = y;
}
/**
* @brief sets the x position of the ball
* @param x-position
* of the ball
*/
public void setPositionX(int x) {
positionX = x;
}
/**
* @brief sets the y position of the ball
* @param y-position
* of the ball
*/
public void setPositionY(int y) {
positionY = y;
}
/**
* @brief gets the x-position of the ball
* @return positionX
*/
public int getPositionX() {
return positionX;
}
/**
* @brief gets the y-position of the ball
* @return positionY
*/
public int getPositionY() {
return positionY;
}
/**
* @brief gets the size of the ball
* @return SIZE
*/
public int getSize() {
return SIZE;
}
}
package model;
/**
* @file GameModel.java
* @title GameModel
* @author Pongthusiastics
* @date 4/11/2016
* @brief This class represents a ball on the pong game
* @details This class saves the information of a ball, including its position,
* size and the speed.
*/
public class GameModel {
/**
* The ball object for the game
*/
private Ball b1;
/**
* The two paddle in the game, one for the player and the other for the computer
*/
private Paddle p_player, p_computer;
/**
* The two players in the game, one for the user and the other for the computer
*/
private Player player, computer;
private int ballX, ballY;
private int playerX, playerY;
private int compX, compY;
/**
* @brief Constructor for the game Model
* @details Contains all the data and models for the game, including the player, paddle, and the ball.
* @param ballX is the x-position of the ball
* @param ballY is the y-position of the ball
* @param playerX is the x-position of the user's paddle
* @param playerY is the y-position of the user's paddle
* @param compX is the x-position of the user's paddle
* @param compY is the y-position of the user's paddle
*/
public GameModel(int ballX, int ballY, int playerX, int playerY, int compX, int compY){
b1 = new Ball(ballX, ballY);
p_player = new Paddle(playerX, playerY);
p_computer = new Paddle(compX, compY);
//TODO
player = new Player();
computer = new Player();
}
/**
* @brief sets the x and y positions of a ball
* @param x is the x position of the ball
* @param y is the y position of the ball
*/
public void setBall(int x, int y){
b1.setPositionX(x);
b1.setPositionY(y);
}
/**
* @brief gets the Ball object
* @return b1
*/
public Ball getBall(){
return b1;
}
/**
* @brief gets the user paddle object
* @return p_player
*/
public Paddle getPlayerPaddle(){
return p_player;
}
/**
* @brief gets the computer paddle object
* @return p_computer
*/
public Paddle getComputerPaddle(){
return p_computer;
}
/**
* @brief gets the player object
* @return player
*/
public Player getPlayer(){
return player;
}
/**
* @brief gets the computer object
* @return computer
*/
public Player getComputer(){
return computer;
}
}
package model;
public class Paddle {
private int positionX;
private int positionY;
private final int HEIGHT = 10;
private final int WIDTH = 40;
private final int INSET = 10;
//TODO
private int speed;
public Paddle(int x, int y){
positionX = x;
positionY = y;
}
/**
* @brief sets the x-position of the paddle
* @param x is the x position of the paddle
*/
public void setPositionX(int x){
positionX = x;
}
/**
* @brief sets the y-position of the paddle
* @param y is the y position of the paddle
*/
public void setPositionY(int y){
positionY = y;
}
/**
* @brief returns the x position of the paddle
* @return positionX
*/
public int getPositionX(){
return positionX;
}
/**
* @brief returns the y position of the paddle
* @return positionY
*/
public int getPositionY(){
return positionY;
}
/**
* @brief returns the width of the paddle
* @return WIDTH
*/
public int getWidth(){
return WIDTH;
}
/**
* @brief returns the height of the paddle
* @return HEIGHT
*/
public int getHeight(){
return HEIGHT;
}
/**
* @brief returns the inset between the paddle and the screen
* @return INSET
*/
public int getInset(){
return INSET;
}
}
package redevelopedCode;
package model;
public class Players {
public class Player {
// Constant declaration for number of life
private final int LIFE = 3;
private final int NOLIFE = 0;
// Variable declaration that store the player score
private int playerScore;
private int paddlePositionX;
private int paddlePositionY;
// Variable declaration for storing the player score
private int score;
/**
* Constructor for the player - set the score to be 0 initially
*/
public Players(){
playerScore = LIFE;
public Player(){
score = LIFE;
//TODO: POSITION X, POSITION Y
}
/**
* Decrease number of life of the player
* @brief decreases number of life of the player
*/
public void decrementLife(){
playerScore--;
score--;
}
/**
* Increase score for a player
* @brief increases score for a player
*/
public void incrementScore(){
playerScore++;
score++;
}
/**
* Get the score of a player
* @brief gets the score of a player
* @return playerScore - return the score of the player
*/
public int getScore(){
return playerScore;
}
/**
* Save the paddle positions
* @param x - horizontal position of the paddle
* @param y - vertical position of the paddle
*/
public void setPosition(int x, int y){
paddlePositionX = x;
paddlePositionY = y;
}
/**
* Get the paddle positions
* @return - horizontal and vertical positions in an array
*/
public int[] getPosition(){
int[] temp = {paddlePositionX,paddlePositionY};
return temp;
return score;
}
/**
* Check whether the player loses the game or not
* @brief checks whether the player loses the game or not
* @return - boolean indicating losing or not
*/
public boolean checkLoss(){
if(playerScore==NOLIFE){ return true;}
if(score==NOLIFE){ return true;}
else{ return false; }
}
}
package original_code;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.util.HashMap;
import java.util.HashSet;
import javax.swing.*;
public class Game extends JPanel implements KeyListener, ActionListener {
private int height, width;
private Timer t = new Timer(5, this);
private boolean first;
private HashSet<String> keys = new HashSet<String>();
// pad
private final int SPEED = 1;
private int padH = 10, padW = 40;
private int bottomPadX, topPadX;
private int inset = 10;
// ball
private double ballX, ballY, velX = 1, velY = 1, ballSize = 20;
// score
private int scoreTop, scoreBottom;
public Game() {
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
first = true;
t.setInitialDelay(100);
t.start();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
height = getHeight();
width = getWidth();
// initial positioning
if (first) {
bottomPadX = width / 2 - padW / 2;
topPadX = bottomPadX;
ballX = width / 2 - ballSize / 2;
ballY = height / 2 - ballSize / 2;
first = false;
}
// bottom pad
Rectangle2D bottomPad = new Rectangle(bottomPadX, height - padH - inset, padW, padH);
g2d.fill(bottomPad);
// top pad
Rectangle2D topPad = new Rectangle(topPadX, inset, padW, padH);
g2d.fill(topPad);
// ball
Ellipse2D ball = new Ellipse2D.Double(ballX, ballY, ballSize, ballSize);
g2d.fill(ball);
// scores
String scoreB = "Bottom: " + new Integer(scoreBottom).toString();
String scoreT = "Top: " + new Integer(scoreTop).toString();
g2d.drawString(scoreB, 10, height / 2);
g2d.drawString(scoreT, width - 50, height / 2);
}
@Override
public void actionPerformed(ActionEvent e) {
// side walls
if (ballX < 0 || ballX > width - ballSize) {
velX = -velX;
}
// top / down walls
if (ballY < 0) {
velY = -velY;
++ scoreBottom;
}
if (ballY + ballSize > height) {
velY = -velY;
++ scoreTop;
}
// bottom pad
if (ballY + ballSize >= height - padH - inset && velY > 0)
if (ballX + ballSize >= bottomPadX && ballX <= bottomPadX + padW)
velY = -velY;
// top pad
if (ballY <= padH + inset && velY < 0)
if (ballX + ballSize >= topPadX && ballX <= topPadX + padW)
velY = -velY;
ballX += velX;
ballY += velY;
// pressed keys
if (keys.size() == 1) {
if (keys.contains("LEFT")) {
bottomPadX -= (bottomPadX > 0) ? SPEED : 0;
}
else if (keys.contains("RIGHT")) {
bottomPadX += (bottomPadX < width - padW) ? SPEED : 0;
}
}
// AI
double delta = ballX - topPadX;
if (delta > 0) {
topPadX += (topPadX < width - padW) ? SPEED : 0;
}
else if (delta < 0) {
topPadX -= (topPadX > 0) ? SPEED : 0;
}
repaint();
}
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
switch (code) {
case KeyEvent.VK_LEFT:
keys.add("LEFT");
break;
case KeyEvent.VK_RIGHT:
keys.add("RIGHT");
break;
}
}
@Override
public void keyReleased(KeyEvent e) {
int code = e.getKeyCode();
switch (code) {
case KeyEvent.VK_LEFT:
keys.remove("LEFT");
break;
case KeyEvent.VK_RIGHT:
keys.remove("RIGHT");
break;
}
}
}
package original_code;
import java.awt.BorderLayout;
import javax.swing.JFrame;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
JFrame frm = new JFrame();
frm.setTitle("Pong");
Game g = new Game();
frm.setContentPane(g);
frm.setSize(300, 700);
frm.setResizable(false);
frm.setVisible(true);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
package redevelopedCode;
public class Ball {
private int positionX;
private int positionY;
public Ball(int x, int y){
positionX = x;
positionY = y;
}
public void setPosition(int x, int y){
positionX = x;
positionY = y;
}
public int[] getPosition(){
int[] temp = {positionX,positionY};
return temp;
}
}
package redevelopedCode;
import java.io.*;
public class Pong_controller {
public Pong_model model;
public static Pong_view viewer;
public Pong_controller(){
model = new Pong_model();
}
public static void main(String[] args){
Pong_controller controller = new Pong_controller();
viewer = new Pong_view(controller);
}
public void loadGame(){
try{
FileReader fr = new FileReader("savedScore.txt");
BufferedReader br = new BufferedReader(fr);
int score1 = Integer.parseInt(br.readLine());
int score2 = Integer.parseInt(br.readLine());
// TODO
br.close();
} catch(Exception e){
e.printStackTrace();
}
}
public void saveGame(){
try{
FileWriter fw = new FileWriter("savedScore.txt");
BufferedWriter bw = new BufferedWriter(fw);
bw.write(model.player1.getScore());
bw.write(model.player2.getScore());
// TODO
bw.close();
} catch(Exception e){
e.printStackTrace();
}
}
public int gameOver(){
if(model.player1.getScore()==0){
return 1;
}
else if(model.player2.getScore()==0){
return 2;
}
else{
return -1;
}
}
}
package redevelopedCode;
public class Pong_model{
private int score1;
private int score2;
public Players player1;
public Players player2;
public Pong_model(){
player1 = new Players();
player2 = new Players();
score1 = player1.getScore();
score2 = player2.getScore();
}
public void changeSpeed(int newSpeed){
}
public String readTutorial(){
String content = "";
return content;
}
public boolean createObstacle(boolean gameMode){
if(gameMode==true){ return true;}
else{ return false; }
}
}
\ No newline at end of file
package redevelopedCode;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.util.HashSet;
import javax.swing.*;
public class Pong_view extends JFrame{
private Pong_controller controller;
private JButton start = new JButton("Start New Game");
private JButton load = new JButton("Load Game");
private JButton highScores = new JButton("High Scores");
private JButton tutorial = new JButton("Tutorial");
private JButton exit = new JButton("Exit");
private JButton single = new JButton("Single Player Mode");
private JButton sObstacle = new JButton("Advanced Single Player Mode");
private JButton multi = new JButton("Multiplayer Mode");
private JPanel buttonPanel = new JPanel();
public Pong_view(Pong_controller c){
super("FaultInOurPong");
controller = c;
initializeFrame();
}
private void initializeFrame(){
this.setSize(700,500);
this.setResizable(false);
buttonPanel.setLayout(new BoxLayout(buttonPanel,BoxLayout.Y_AXIS));
buttonPanel.add(Box.createVerticalGlue());
addButton(start);
addButton(load);
addButton(highScores);
addButton(tutorial);
addButton(exit);
buttonPanel.add(Box.createVerticalGlue());
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
start();
}
});
load.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// TODO:
//load();
}
});
highScores.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// TODO:
//highScores();
}
});
tutorial.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// TODO:
//tutorial();
}
});
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
add(buttonPanel);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public void addButton(JButton x) {
x.setMaximumSize(sObstacle.getPreferredSize());
x.setAlignmentY(CENTER_ALIGNMENT);
x.setAlignmentX(CENTER_ALIGNMENT);
buttonPanel.add(x);
buttonPanel.add(Box.createVerticalStrut(20));
}
public void start() {
buttonPanel.removeAll();
this.getContentPane().removeAll();
this.repaint();
buttonPanel.setLayout(new BoxLayout(buttonPanel,BoxLayout.Y_AXIS));
buttonPanel.add(Box.createVerticalGlue());
addButton(single);
addButton(sObstacle);
buttonPanel.add(Box.createVerticalGlue());
add(buttonPanel);
this.setVisible(true);
single.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// TODO:
single();
}
});
}
private int height, width; // the height and width of the screen
//private Timer t = new Timer(1, this); // the 't' variable makes sure that there is a initial delay before the same starts off
private boolean first=true; //game state (starting/playing)
private HashSet<String> keys = new HashSet<String>();
// pad
private final int SPEED = 1; //the speed of the paddles
private int padH = 10, padW = 40; // paddle width/height
private int bottomPadX, topPadX; // these represent the top and the bottom paddles in the game
private int inset = 10; // this helps determine the distance between the paddle
// - and the top and bottom screen boundaries
// ball
private double ballX, ballY, velX = 1, velY = 1, ballSize = 20; //ball position, ball velocity, ball size
// score
private int scoreTop, scoreBottom; // keep track of game record
public void single(){
buttonPanel.removeAll();
this.remove(buttonPanel);
JPanel game_panel = new JPanel(){
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g; // create an object for graphics (rectangles)
height = getHeight(); // get game frame/screen size
width = getWidth();
// initial positioning
if (first) {
bottomPadX = width / 2 - padW / 2; // setups for the paddles positions - in the middle of the screen
topPadX = bottomPadX;
ballX = width / 2 - ballSize / 2; // setups for the ball positions - in the middle of the screen
ballY = height / 2 - ballSize / 2;
first = false; // setup completed
}
// bottom pad
Rectangle2D bottomPad = new Rectangle(bottomPadX, height - padH - inset, padW, padH); // creating the object for bottom paddle
g2d.fill(bottomPad);
// top pad
Rectangle2D topPad = new Rectangle(topPadX, inset, padW, padH); // creating paddle object for the top paddle
g2d.fill(topPad);
// ball
Ellipse2D ball = new Ellipse2D.Double(ballX, ballY, ballSize, ballSize); // creating the ball object for the game
g2d.fill(ball);
// scores
String scoreB = "Bottom: " + new Integer(scoreBottom).toString(); // saving the score of the bottom paddle
String scoreT = "Top: " + new Integer(scoreTop).toString(); // saving the score of the top paddle
g2d.drawString(scoreB, 10, height / 2); // printing the score of the bottom paddle in the screen
g2d.drawString(scoreT, width - 50, height / 2); // printing the score of the top paddle in the screen
}
};
this.add(game_panel);
this.revalidate();
this.repaint();
}
}
package startGame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashSet;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.Timer;
import model.*;
import view.*;
public class GameController{
private GameView v;
private GameModel m;
private Welcome w;
private Mode mode;
private Tutorial tut;
private HashSet<String> keys = new HashSet<String>();
private JFrame gameFrame;
private int frameWidth, frameHeight;
private PongGameDisplay gameDisplay;
private int velX=1, velY=1;
private int padWidth = 80, padHeight = 10;
private int bottomPadX, bottomPadY, topPadX, topPadY;
private int ballX, ballY, ballSize=20;
private int scoreTop, scoreBottom;
private int inset;
private Timer t;
public GameController(GameView v, GameModel m){
this.v = v;
this.m = m;
/*
* Setups for the View
*/
w = this.v.getWelcome();
w.addListener(new WelcomepageListener());
mode = this.v.getmode();
mode.addListener(new ModeListener());
ImageIcon image = new ImageIcon("./Resources/tutorial.png");
v.tutorialPage(image);
tut = v.getTutorial();
tut.addListener(new TutorialListener());
gameFrame = this.v.getGameFrame();
gameDisplay = this.v.getGame();
gameDisplay.addKeyListener(new GameListener());
gameDisplay.setFocusable(true);
gameDisplay.setFocusTraversalKeysEnabled(false);
/*
* Setups for the Model
*/
frameWidth = v.getFrameWidth();
frameHeight = v.getFrameHeight();
}
/*
* Actionlistener for the welcome page
*/
class WelcomepageListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Object source = e.getSource();
// If clicked the start button
if(source==w.getStart()){
mode.setVisible(true);
w.setVisible(false);
}else if(source==w.load()){
// If clicked the load button
//TODO
try{
FileReader fr = new FileReader("./Resources/userData.txt");
BufferedReader br = new BufferedReader(fr);
System.out.println("can load data");
br.close();
}catch(Exception exp){
v.cannotLoadMessage();
}
}else if(source==w.highScores()){
// If clicked the high score button
//TODO
try{
FileReader fr = new FileReader("./Resources/gameScore.txt");
BufferedReader br = new BufferedReader(fr);
System.out.println("can display high score");
br.close();
}catch(Exception exp){
v.noFileAvailMessage();
}
}else if(source==w.tutorial()){
// If clicked the tutorial button
//TODO
w.setVisible(false);
tut.setVisible(true);
}else if(source==w.exit()){
// If clicked the exit button
System.exit(0);
}
}
}
/*
* Actionlistener for the Single-Mode page
*/
class ModeListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Object source = e.getSource();
if(source == mode.getSingle()){
// If clicked the basic single mode button
mode.setVisible(false);
gameFrame.setVisible(true);
t.start();
}
}
}
/*
* Actionlistener for the tutorial page
*/
class TutorialListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Object source = e.getSource();
if(source == tut.getBack()){
// If clicked the back button
tut.setVisible(false);
w.setVisible(true);
}
}
}
class GameListener implements ActionListener, KeyListener{
GameListener(){
ballX = gameDisplay.getBallX();
ballY = gameDisplay.getBallY();
t = new Timer(5,this);
t.setInitialDelay(1000); // sets initial delay for the movement of the ball
bottomPadX = gameDisplay.getBottomX();
bottomPadY = gameDisplay.getBottomY();
//TODO: MODEL FOR THE PADDLE
}
@Override
public void actionPerformed(ActionEvent e) {
// X-direction
if(ballX< 0 || ballX > frameWidth-1.5*ballSize){
/*
* If the ball is trying to go beyond the left/right border of the frame,
* reverse the direction.
*/
velX = -velX;
}
// Y-direction
if(ballY < 0){
/*
* If the ball is trying to go up above the frame,
* - reverse the direction
* - user gets points because the ball hits the border of the computer side
*/
velY = -velY;
++scoreBottom;
gameDisplay.setBottomScore(scoreBottom);
} else if(ballY+2.5*ballSize>frameHeight){
/*
* If the ball is trying to go down beyond the frame
* - reverse the direction
* - the computer gets points
*/
velY = -velY;
++scoreTop;
gameDisplay.setTopScore(scoreTop);
} else if(ballY+2.5*ballSize>frameHeight-inset-2*padHeight && velY > 0 && ballX + ballSize >= bottomPadX && ballX <= bottomPadX + padWidth){
/*
* If the ball is touching the bottom paddle
* - reverse the direction
*/
velY = -velY;
} else if(ballY<=inset+2*padHeight && velY < 0 && ballX + ballSize >= topPadX && ballX <= topPadX + padWidth){
/*
* If the ball is touching the top paddle
* - reverse the direction
*/
velY = -velY;
}
/*
* Update the ball position by velocity
*/
ballX += velX;
ballY += velY;
gameDisplay.setBall(ballX,ballY);
/*
* Detect the key pressed by the user on the keyboard
*/
if (keys.size() == 1) {
if (keys.contains("LEFT")) {
/*
* If the user presses LEFT
* - update the position of the user paddle
* - display the change on the screen
*/
if(bottomPadX>0) {
//TODO: SPEED
bottomPadX-=3;
gameDisplay.setBottom(bottomPadX);
}
}
else if (keys.contains("RIGHT")) {
if(bottomPadX < frameWidth - padWidth){
/*
* If the user presses RIGHT
* - update the position of the user paddle
* - display the change on the screen
*/
//TODO: SPEED
bottomPadX+=3;
gameDisplay.setBottom(bottomPadX);
}
}
}
/*
* Create actions for the AI paddles
*/
double delta = ballX - topPadX;
if (delta > 0) {
if(topPadX < frameWidth - padWidth){
/*
* If the AI paddle is trying to reach the right wall
* - move the paddle to the right
* - display the movement on the screen
*/
topPadX +=1;
gameDisplay.setTop(topPadX);
}
}
else if (delta < 0) {
if(topPadX>0){
/*
* If the AI paddle is trying to reach the left wall
* - move the paddle to the left
* - display the movement on the screen
*/
topPadX -=1;
gameDisplay.setTop(topPadX);
}
}
gameDisplay.repaint();
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
int code = e.getKeyCode(); // get which key is pressed
switch (code) {
case KeyEvent.VK_LEFT:
keys.add("LEFT");
break;
case KeyEvent.VK_RIGHT:
keys.add("RIGHT");
break;
}
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
int code = e.getKeyCode(); // get which key is released
switch (code) {
case KeyEvent.VK_LEFT:
keys.remove("LEFT");
break;
case KeyEvent.VK_RIGHT:
keys.remove("RIGHT");
break;
}
}
@Override
public void keyTyped(KeyEvent e) {}
}
public void display(){
v.display();
}
}
package startGame;
import model.*;
import view.*;
public class PongGame {
public PongGame(){
}
public static void main(String[] args){
/*
* Initialize the model, view, and controller for the game
*/
GameView view = new GameView();
GameModel model = new GameModel(1,1,2,2,2,2);
GameController controller = new GameController(view, model);
/*
* Invoke the game display from the controller
*/
controller.display();
}
}
package view;
import javax.swing.*;
public class GameView{
private Welcome welcome;
private Mode mode;
private PongGameDisplay ponggame;
private Tutorial tutorial;
private final int FRAMEWIDTH = 700;
private final int FRAMEHEIGHT = 500;
private JFrame gameFrame;
public GameView(){
/*
* Pass in different windows to this view interface
* - will wait for further invocation
*/
welcome = new Welcome();
mode = new Mode();
ponggame = new PongGameDisplay();
createGame();
}
public void display(){
welcome.setVisible(true);
}
public Welcome getWelcome(){
return welcome;
}
public Mode getmode(){
return mode;
}
public PongGameDisplay getGame(){
return ponggame;
}
public Tutorial getTutorial(){
return tutorial;
}
//TODO: ADD PANEL FOR OPTIONS IN THE GAME
public void createGame(){
gameFrame = new JFrame("FaultInOurPong");
gameFrame.setContentPane(ponggame);
gameFrame.setSize(FRAMEWIDTH,FRAMEHEIGHT);
gameFrame.setResizable(false);
gameFrame.setLocationRelativeTo(null);
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public JFrame getGameFrame(){
return gameFrame;
}
// TODO: display a dialogue after successfully saving game records (high score)
public void noFileAvailMessage(){
JFrame errorFrame = new JFrame("Error");
JOptionPane.showMessageDialog(errorFrame, "No record available!");
}
public void cannotLoadMessage(){
JFrame errorFrame = new JFrame("Error");
JOptionPane.showMessageDialog(errorFrame, "The record is either damaged or not available, please start a new game!");
}
public void tutorialPage(ImageIcon img){
tutorial = new Tutorial(img);
}
public int getFrameWidth(){
return FRAMEWIDTH;
}
public int getFrameHeight(){
return FRAMEHEIGHT;
}
}
\ No newline at end of file
package view;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import model.*;
import view.*;
public class Mode extends JFrame{
private JButton single = new JButton("Single Player Mode");
private JButton sObstacle = new JButton("Advanced Single Player Mode");
private JPanel buttonPanel;
public Mode(){
/*
* - Set the header of the window
* - Set the size of the window
*/
super("FaultInOurPong");
this.setSize(700,500);
this.setResizable(false);
this.setLocationRelativeTo(null);
/*
* Add buttons on the window
*/
buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel,BoxLayout.Y_AXIS));
buttonPanel.add(Box.createVerticalGlue());
addButton(single);
addButton(sObstacle);
buttonPanel.add(Box.createVerticalGlue());
add(buttonPanel);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void addButton(JButton x) {
x.setMaximumSize(sObstacle.getPreferredSize());
x.setAlignmentY(CENTER_ALIGNMENT);
x.setAlignmentX(CENTER_ALIGNMENT);
buttonPanel.add(x);
buttonPanel.add(Box.createVerticalStrut(20));
}
public void addListener(ActionListener buttonListener){
single.addActionListener(buttonListener);
sObstacle.addActionListener(buttonListener);
}
public JButton getSingle(){
return single;
}
}
package view;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionListener;
import java.awt.event.KeyListener;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class PongGameDisplay extends JPanel{
//private JFrame gameFrame;
private int frameWidth;
private int frameHeight;
private int scoreTop, scoreBottom;
private int ballX, ballY;
private int bottomPadX, bottomPadY;
private int topPadX, topPadY;
private boolean first;
private int ballSize;
private int padW, padH;
private int inset;
public PongGameDisplay(){
first = true;
ballSize = 20;
padW = 80;
padH = 10;
inset = 10;
scoreTop=0;
scoreBottom=0;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g; // create an object for graphics (rectangles)
frameHeight = getHeight(); // get game frame/screen size
frameWidth = getWidth();
// initial positioning
if (first) {
bottomPadX = frameWidth / 2 - padW / 2; // setups for the paddles positions - in the middle of the screen
topPadX = bottomPadX;
ballX = frameWidth / 2 - ballSize / 2; // setups for the ball positions - in the middle of the screen
ballY = frameHeight / 2 - ballSize / 2;
first = false; // setup completed
}
// bottom pad
Rectangle2D bottomPad = new Rectangle(bottomPadX, frameHeight - padH - inset, padW, padH); // creating the object for bottom paddle
g2d.fill(bottomPad);
// top pad
Rectangle2D topPad = new Rectangle(topPadX, inset, padW, padH); // creating paddle object for the top paddle
g2d.fill(topPad);
// ball
Ellipse2D ball = new Ellipse2D.Double(ballX, ballY, 20, 20); // creating the ball object for the game
g2d.fill(ball);
// scores
String scoreB = "Bottom: " + scoreBottom; // saving the score of the bottom paddle
String scoreT = "Top: " + scoreTop; // saving the score of the top paddle
g2d.drawString(scoreB, 10, frameHeight / 2); // printing the score of the bottom paddle in the screen
g2d.drawString(scoreT, frameWidth - 50, frameHeight / 2); // printing the score of the top paddle in the screen
}
public void setBall(int x, int y){
ballX = x;
ballY = y;
}
public void setBottom(int x){
bottomPadX = x;
}
public void setTop(int x){
topPadX = x;
}
public int getBottomX(){
return bottomPadX;
}
public int getBottomY(){
return bottomPadY;
}
public void setTopScore(int s){
scoreTop=s;
}
public void setBottomScore(int s){
scoreBottom = s;
}
public int getBallX(){
return ballX;
}
public int getBallY(){
return ballY;
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment