diff --git a/MerchantRPGCSE2102/src/controller/RPGame.java b/MerchantRPGCSE2102/src/controller/RPGame.java index 53f67df..9708493 100644 --- a/MerchantRPGCSE2102/src/controller/RPGame.java +++ b/MerchantRPGCSE2102/src/controller/RPGame.java @@ -5,10 +5,15 @@ import java.util.ArrayList; import java.util.Scanner; +import javax.swing.JFrame; + import model.Merchant; import model.Player; +import view.MapUI; public class RPGame { + public static final int WIDTH = 1206; + public static final int HEIGHT = 929; private ArrayList merchantInventoryList1 = new ArrayList(); // merchant 1's inventory list private ArrayList merchantInventoryList2 = new ArrayList(); // merchant 2's inventory list private ArrayList merchantInventoryList3 = new ArrayList(); // merchant 3's inventory list @@ -35,12 +40,12 @@ public void inventoryFromFile() { String token = null; String item = null; - while(fileScanner.hasNextLine()) { // loops as long as there is another line to read + while(fileScanner.hasNextLine()) { // loops as long as there is another line to read token = fileScanner.next(); if (token.equals("merchant")) currentMerchant = fileScanner.nextInt(); else { - item = token + " " + fileScanner.nextInt(); // a string containing the item name and price + item = token + " " + fileScanner.nextInt(); // a string containing the item name and price if (currentMerchant == 1) merchantInventoryList1.add(item); else if (currentMerchant == 2) @@ -49,11 +54,11 @@ else if (currentMerchant == 3) merchantInventoryList3.add(item); playerInventoryList.add(item); } - if (fileScanner.hasNextLine()) // only advances to the next line if there is one to read + if (fileScanner.hasNextLine()) // only advances to the next line if there is one to read fileScanner.nextLine(); } - } catch (FileNotFoundException e) { // if inventory.txt is deleted or missing + } catch (FileNotFoundException e) { // if inventory.txt is deleted or missing System.out.println("Inventory file not found"); e.printStackTrace(); } @@ -112,8 +117,7 @@ public ArrayList getPlayerInventoryList() { } /** - * This method will create a new instance of Transaction - * incomplete method + * This method will create a new instance of Transaction which runs independently * * @param player * @param targetMerchant The merchant that the player is trading with @@ -122,6 +126,7 @@ public void createTransaction(Player player, Merchant targetMerchant) { toggleMovement("OFF"); Transaction newTransaction = new Transaction(player, targetMerchant); + toggleMovement("ON"); } /** @@ -165,17 +170,9 @@ else if(merchantNum == 2) /** * Main method used to test the GUI components since test classes do not maintain the GUI * @param args no need for input + * @throws InterruptedException */ - public static void main(String[] args) + public static void main(String[] args) throws InterruptedException { - RPGame _rpg = new RPGame(); - _rpg.inventoryFromFile(); - _rpg.buildMerchants(); - ArrayList playerInventory = _rpg.getMerchantInventoryList(1); - playerInventory.addAll(_rpg.getMerchantInventoryList(2)); - playerInventory.addAll(_rpg.getMerchantInventoryList(3)); - _rpg.buildPlayer("test", 500, playerInventory); - _rpg.getPlayer().getItem("armor").increaseQuantity(15); - _rpg.createTransaction(_rpg.getPlayer(), _rpg.getMerchant(1)); } } diff --git a/MerchantRPGCSE2102/src/controller/Transaction.java b/MerchantRPGCSE2102/src/controller/Transaction.java index 4769e31..def3e51 100644 --- a/MerchantRPGCSE2102/src/controller/Transaction.java +++ b/MerchantRPGCSE2102/src/controller/Transaction.java @@ -1,5 +1,6 @@ package controller; +import exceptions.NotInInventoryException; import view.TransactionUI; import model.Item; import model.Merchant; @@ -48,8 +49,9 @@ public boolean actionBuy(String itemName, int amount) * @param itemName name of the item * @param amount amount that the player wants to buy * @return returns true if transaction successful, false otherwise + * @throws NotInInventoryException */ - public boolean actionSell(String itemName, int amount) + public boolean actionSell(String itemName, int amount) throws NotInInventoryException { if(_player.sell(itemName, _targetMerchant, amount)) return true; diff --git a/MerchantRPGCSE2102/src/exceptions/NotInInventoryException.java b/MerchantRPGCSE2102/src/exceptions/NotInInventoryException.java new file mode 100644 index 0000000..83e5086 --- /dev/null +++ b/MerchantRPGCSE2102/src/exceptions/NotInInventoryException.java @@ -0,0 +1,10 @@ +package exceptions; + +@SuppressWarnings("serial") +public class NotInInventoryException extends Exception +{ + public NotInInventoryException() + { + super(); + } +} diff --git a/MerchantRPGCSE2102/src/graph/Graph.java b/MerchantRPGCSE2102/src/graph/Graph.java index 1acff8b..ce7dc19 100644 --- a/MerchantRPGCSE2102/src/graph/Graph.java +++ b/MerchantRPGCSE2102/src/graph/Graph.java @@ -3,12 +3,14 @@ public class Graph { private Vertex[] _vertexList; - private int _size; + private int _rows; + private int _cols; - public Graph(int size) + public Graph(int rows, int cols) { - _size = size; - _vertexList = new Vertex[size*size]; + _rows = rows; + _cols = cols; + _vertexList = new Vertex[rows*cols]; } public void initializeGraph() { @@ -17,24 +19,25 @@ public void initializeGraph() { } public void initializeVertices() { - for (int row = 0; row < _size; row++) { - for (int col = 0; col < _size; col++) { - int cellNum = row*_size + col; - Vertex v = new Vertex(cellNum, _size); + for (int row = 0; row < _rows; row++) { + for (int col = 0; col < _cols; col++) { + int cellNum = row*_cols + col; + Vertex v = new Vertex(cellNum, row, col); setVertex(cellNum, v); } } } public void initializeEdges() { - for (int row = 0; row < _size; row++) { - for (int col = 0; col < _size; col++) { + for (int row = 0; row < _rows; row++) { + for (int col = 0; col < _cols; col++) { - if (row !=0) - connectWithEdge(getVertex(_size*row + col), getVertex(_size*(row - 1) + col)); + if (row !=0) { + connectWithEdge(getVertex(_cols*row + col), getVertex(_cols*(row - 1) + col)); + } - if (col != _size - 1) - connectWithEdge(getVertex(_size*row + col), getVertex(_size*row + col + 1)); + if (col != _cols - 1) + connectWithEdge(getVertex(_cols*row + col), getVertex(_cols*row + col + 1)); } } } @@ -47,9 +50,14 @@ public void connectWithEdge(Vertex v, Vertex w) { edge.setW(w); } - public int getSize() + public int getRows() { - return _size; + return _rows; + } + + public int getCols() + { + return _cols; } public Vertex getVertex(int vertexNum) diff --git a/MerchantRPGCSE2102/src/graph/Vertex.java b/MerchantRPGCSE2102/src/graph/Vertex.java index 4b69807..c904344 100644 --- a/MerchantRPGCSE2102/src/graph/Vertex.java +++ b/MerchantRPGCSE2102/src/graph/Vertex.java @@ -11,15 +11,10 @@ public class Vertex private LinkedList _incidentEdges = new LinkedList(); - public Vertex(int cellNum, int n) { + public Vertex(int cellNum, int row, int col) { + _row = row; + _col = col; _cellNum = cellNum; - _row = 0; - int temp = _cellNum; - while (temp - n >= 0) { // Calculates the row of the vertex - temp = temp - n; - _row++; - } - _col = _cellNum - _row*n; // Calculates the column of the vertex } public void addEdge(Edge edge) { diff --git a/MerchantRPGCSE2102/src/images/background.jpg b/MerchantRPGCSE2102/src/images/background.jpg new file mode 100644 index 0000000..4c64943 Binary files /dev/null and b/MerchantRPGCSE2102/src/images/background.jpg differ diff --git a/MerchantRPGCSE2102/src/images/icon.png b/MerchantRPGCSE2102/src/images/icon.png new file mode 100644 index 0000000..b5d509b Binary files /dev/null and b/MerchantRPGCSE2102/src/images/icon.png differ diff --git a/MerchantRPGCSE2102/src/model/Character.java b/MerchantRPGCSE2102/src/model/Character.java new file mode 100644 index 0000000..f1dcd57 --- /dev/null +++ b/MerchantRPGCSE2102/src/model/Character.java @@ -0,0 +1,64 @@ +package model; + +public class Character { + private int _x, _y; + protected Item[] _inventory; + protected String _name; + + + /** + * Searches through the player's inventory for the item corresponding to the specified item name + * + * @param itemName string containing the name of the item + * @return the item matching the specified item name + */ + public Item getItem(String itemName) + { + for(int i = 0; i < _inventory.length; i++) + { + if(_inventory[i].getItemName().equals(itemName)) + return _inventory[i]; + } + + System.out.println("No such item exists"); // item was not found by searching the inventory + return null; + } + + /** + * Returns the merchant's item inventory + * @return item inventory array + */ + public Item[] getInventory() + { + return _inventory; + } + + /** + * Returns a string containing the name of the merchant + * + * @return merchant name string + */ + public String getName() + { + return _name; + } + + public int getX() { + return _x; + } + + public void setX(int x) { + _x = x; + } + + public int getY() { + return _y; + } + + public void setY(int y) { + _y = y; + } + + + +} diff --git a/MerchantRPGCSE2102/src/model/Item.java b/MerchantRPGCSE2102/src/model/Item.java index 0adaca9..147e7cb 100644 --- a/MerchantRPGCSE2102/src/model/Item.java +++ b/MerchantRPGCSE2102/src/model/Item.java @@ -38,7 +38,7 @@ public Item(String itemName, int basePrice, int quantity) * @return adjusted price integer * */ - public int scaleAdjPrice(double merchantPercent) + public void scaleAdjPrice(double merchantPercent) { int calculatedPrice = (int) Math.floor((merchantPercent / 100) * _basePrice); //will find the floor of the price to prevent decimals @@ -48,7 +48,6 @@ else if(calculatedPrice < _minPrice) _adjustedPrice = _minPrice; else _adjustedPrice = calculatedPrice; - return _adjustedPrice; } /** diff --git a/MerchantRPGCSE2102/src/model/Map.java b/MerchantRPGCSE2102/src/model/Map.java index 8d56f36..78ae804 100644 --- a/MerchantRPGCSE2102/src/model/Map.java +++ b/MerchantRPGCSE2102/src/model/Map.java @@ -4,13 +4,14 @@ public class Map { - private Graph _mapGraph; // Graph representation of the map - private int _mapSize; // The n*n dimension of the map + private Graph _mapGraph; // Graph representation of the map + private int _rows, _cols; // The n*n dimension of the map private Player _player; - public Map(int size) { - _mapSize = size; - _mapGraph = new Graph(_mapSize); + public Map(int rows, int cols) { + _rows = rows; + _cols = cols; + _mapGraph = new Graph(_rows, _cols); _mapGraph.initializeGraph(); } @@ -21,8 +22,8 @@ public Map(int size) { * @param y The y coordinate of the player's location */ public void initializePlayer(Player player, int x, int y) { - _player = player; - int vertexNum = y*_mapSize + x; + _player = player; + int vertexNum = y*_cols + x; player.setX(x); player.setY(y); _mapGraph.getVertex(vertexNum).setOccupant(player); @@ -35,7 +36,7 @@ public void initializePlayer(Player player, int x, int y) { * @param y The y coordinate of the merchant's location */ public void initializeMerchant(Merchant merchant, int x, int y) { - int vertexNum = y*_mapSize + x; + int vertexNum = y*_cols + x; merchant.setX(x); merchant.setY(y); _mapGraph.getVertex(vertexNum).setOccupant(merchant); @@ -43,7 +44,6 @@ public void initializeMerchant(Merchant merchant, int x, int y) { /** * Moves the specified instance of Player in the specified direction on the map - * @param player The player to be moved * @param String The direction to be moved (north, west, east, or south) */ public void movePlayer(String direction) { @@ -52,29 +52,29 @@ public void movePlayer(String direction) { if (direction.equals("north")) { if (currentY != 0) { - if (!isOccupied(currentX, currentY - 1)) { - _mapGraph.getVertex(currentY*_mapSize + currentX).setOccupant(null); - _mapGraph.getVertex((currentY - 1)*_mapSize + currentX).setOccupant(_player); + if (!isOccupied(currentX, currentY - 1)) { + _mapGraph.getVertex(currentY*_cols + currentX).setOccupant(null); + _mapGraph.getVertex((currentY - 1)*_cols + currentX).setOccupant(_player); _player.setY(currentY - 1); } } } if (direction.equals("east")) { - if (currentX != _mapSize - 1) { - if (!isOccupied(currentX + 1, currentY)) { - _mapGraph.getVertex(currentY*_mapSize + currentX).setOccupant(null); - _mapGraph.getVertex(currentY*_mapSize + (currentX + 1)).setOccupant(_player); + if (currentX != _cols - 1) { + if (!isOccupied(currentX + 1, currentY)) { + _mapGraph.getVertex(currentY*_cols + currentX).setOccupant(null); + _mapGraph.getVertex(currentY*_cols + (currentX + 1)).setOccupant(_player); _player.setX(currentX + 1); } } } if (direction.equals("south")) { - if (currentY != _mapSize - 1) { - if (!isOccupied(currentX, currentY + 1)) { - _mapGraph.getVertex(currentY*_mapSize + currentX).setOccupant(null); - _mapGraph.getVertex((currentY + 1)*_mapSize + currentX).setOccupant(_player); + if (currentY != _rows - 1) { + if (!isOccupied(currentX, currentY + 1)) { + _mapGraph.getVertex(currentY*_cols + currentX).setOccupant(null); + _mapGraph.getVertex((currentY + 1)*_cols + currentX).setOccupant(_player); _player.setY(currentY + 1); } } @@ -82,13 +82,14 @@ public void movePlayer(String direction) { if (direction.equals("west")) { if (currentX != 0) { - if (!isOccupied(currentX - 1, currentY)) { - _mapGraph.getVertex(currentY*_mapSize + currentX).setOccupant(null); - _mapGraph.getVertex(currentY*_mapSize + (currentX - 1)).setOccupant(_player); + if (!isOccupied(currentX - 1, currentY)) { + _mapGraph.getVertex(currentY*_cols + currentX).setOccupant(null); + _mapGraph.getVertex(currentY*_cols + (currentX - 1)).setOccupant(_player); _player.setX(currentX - 1); } } } + System.out.println("Player is at vertex (" + _player.getX() + ", " + _player.getY() + ")"); } /** @@ -106,7 +107,7 @@ public Graph getGraph() { * @return Boolean value */ public boolean isOccupied(int x, int y) { - return _mapGraph.getVertex(y*_mapSize + x).getOccupant() != null; + return _mapGraph.getVertex(y*_cols + x).getOccupant() != null; } } diff --git a/MerchantRPGCSE2102/src/model/Merchant.java b/MerchantRPGCSE2102/src/model/Merchant.java index 17997b5..e9651c7 100644 --- a/MerchantRPGCSE2102/src/model/Merchant.java +++ b/MerchantRPGCSE2102/src/model/Merchant.java @@ -3,14 +3,11 @@ import java.util.ArrayList; import java.util.Random; -public class Merchant +public class Merchant extends Character { - private String _name; private int _currentCash; private int _baseCash; private int _dailyRandomPercent; - private Item[] _merchantInventory; - private int _x, _y; public Merchant(String name, int cashLimit, ArrayList inventory) @@ -30,7 +27,7 @@ public Merchant(String name, int cashLimit, ArrayList inventory) */ private void generateMerchantInventory(ArrayList itemList) { - _merchantInventory = new Item[itemList.size()]; // inventory size will be the size of the list of items + _inventory = new Item[itemList.size()]; // inventory size will be the size of the list of items String[] nameAndPrice; // a two string array of both the item name and price String name; String price; @@ -40,7 +37,7 @@ private void generateMerchantInventory(ArrayList itemList) nameAndPrice = itemList.get(i).split("\\s+"); // splits the string into the item name and price name = nameAndPrice[0]; price = nameAndPrice[1]; - _merchantInventory[i] = new Item(name, Integer.parseInt(price), -1); // stores a new instance of the item in the merchant's inventory (-1 represents infinite quantity) + _inventory[i] = new Item(name, Integer.parseInt(price), -1); // stores a new instance of the item in the merchant's inventory (-1 represents infinite quantity) } } @@ -125,46 +122,18 @@ public int getItemPrice(String itemName) return itemPrice; } - /** - * Searches through the merchant's inventory for the item corresponding to the specified item name - * - * @param itemName string containing the name of the item - * @return the item matching the specified item name - */ - public Item getItem(String itemName) - { - for(int i = 0; i < _merchantInventory.length; i++) - { - if(_merchantInventory[i].getItemName().equals(itemName)) - return _merchantInventory[i]; - } - - System.out.println("No such item exists"); // item was not found by searching the inventory - return null; - } - /** * Iterates through the merchant's inventory and scales each item's price by the daily random percentage value * */ public void scaleAllAdjustedPrices() { - for(Item item: _merchantInventory) + for(Item item: _inventory) { item.scaleAdjPrice(_dailyRandomPercent); } } - /** - * Returns a string containing the name of the merchant - * - * @return merchant name string - */ - public String getName() - { - return _name; - } - /** * Returns a the base cash amount of the merchant * @@ -193,29 +162,4 @@ public int getRandomPercent() { return _dailyRandomPercent; } - - /** - * Returns the merchant's item inventory - * @return item inventory array - */ - public Item[] getInventory() - { - return _merchantInventory; - } - - public int getX() { - return _x; - } - - public void setX(int x) { - _x = x; - } - - public int getY() { - return _y; - } - - public void setY(int y) { - _y = y; - } } diff --git a/MerchantRPGCSE2102/src/model/Player.java b/MerchantRPGCSE2102/src/model/Player.java index f9779e6..39c45d1 100644 --- a/MerchantRPGCSE2102/src/model/Player.java +++ b/MerchantRPGCSE2102/src/model/Player.java @@ -2,12 +2,11 @@ import java.util.ArrayList; -public class Player +import exceptions.NotInInventoryException; + +public class Player extends Character { - private String _name; // player's name private int _playerCash; // current amount of cash the player has - private Item[] _playerInventory; // the player's current inventory - private int _x, _y; public Player(String playerName, int startingCash, ArrayList startingInventory) { @@ -24,7 +23,7 @@ public Player(String playerName, int startingCash, ArrayList startingInv */ private void generatePlayerInventory(ArrayList itemList) { - _playerInventory = new Item[itemList.size()]; // inventory size will be the size of the list of items + _inventory = new Item[itemList.size()]; // inventory size will be the size of the list of items String[] nameAndPrice; // a two string array of both the item name and price String name; String price; @@ -34,7 +33,7 @@ private void generatePlayerInventory(ArrayList itemList) nameAndPrice = itemList.get(i).split("\\s+"); //splits the string into the string name and string price name = nameAndPrice[0]; price = nameAndPrice[1]; - _playerInventory[i] = new Item(name, Integer.parseInt(price), 0); // stores a new instance of the item in the player's inventory (quantity begins at 0) + _inventory[i] = new Item(name, Integer.parseInt(price), 0); // stores a new instance of the item in the player's inventory (quantity begins at 0) } } @@ -71,10 +70,17 @@ public boolean buy(String itemName, Merchant targetMerchant, int amount) * @param targetMerchant the merchant who the player is selling to * @param amount the amount of the item that the player is selling * @return returns true if transaction successful, false otherwise + * @throws NotInInventoryException */ - public boolean sell(String itemName, Merchant targetMerchant, int amount) + public boolean sell(String itemName, Merchant targetMerchant, int amount) throws NotInInventoryException { int totalPrice = targetMerchant.getItemPrice(itemName)* amount; //calculates the total price of the items + + if(totalPrice == -1 * amount) + { + throw new NotInInventoryException(); //returns false if the merchant does not buy that item + } + Item targetItem = getItem(itemName); if(targetMerchant.getCurrentCash() >= totalPrice) @@ -82,7 +88,7 @@ public boolean sell(String itemName, Merchant targetMerchant, int amount) if(targetItem.decreaseQuantity(amount)) { increaseCash(totalPrice); - targetMerchant.subtractCash(amount); + targetMerchant.subtractCash(totalPrice); return true; } else @@ -92,24 +98,6 @@ public boolean sell(String itemName, Merchant targetMerchant, int amount) return false; } - /** - * Searches through the player's inventory for the item corresponding to the specified item name - * - * @param itemName string containing the name of the item - * @return the item matching the specified item name - */ - public Item getItem(String itemName) - { - for(int i = 0; i < _playerInventory.length; i++) - { - if(_playerInventory[i].getItemName().equals(itemName)) - return _playerInventory[i]; - } - - System.out.println("No such item exists"); // item was not found by searching the inventory - return null; - } - /** * Decreases the player's cash by the specified amount * @@ -135,16 +123,6 @@ public void increaseCash(int increaseAmount) _playerCash += increaseAmount; } - /** - * Returns a string containing the player's name - * - * @return player's name - */ - public String getName() - { - return _name; - } - /** * Returns the current amount of cash the player has * @@ -154,30 +132,4 @@ public int getPlayerCash() { return _playerCash; } - - /** - * Returns the player's current inventory - * - * @return player's inventory array - */ - public Item[] getInventory() - { - return _playerInventory; - } - - public int getX() { - return _x; - } - - public void setX(int x) { - _x = x; - } - - public int getY() { - return _y; - } - - public void setY(int y) { - _y = y; - } } \ No newline at end of file diff --git a/MerchantRPGCSE2102/src/sprites/PlayerSprite.java b/MerchantRPGCSE2102/src/sprites/PlayerSprite.java new file mode 100644 index 0000000..9b1f91f --- /dev/null +++ b/MerchantRPGCSE2102/src/sprites/PlayerSprite.java @@ -0,0 +1,98 @@ +package sprites; + +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.event.KeyEvent; + +import view.MapUI; + +public class PlayerSprite { + private static final int WIDTH = 30; + MapUI mapui; + public int x, y = 0; + public int row, col; + int dx, dy = 0; + public int changeInX = 0; + public int changeInY = 0; + Color color = new Color(0, 0, 0); + boolean leftBeingPressed = false; + boolean rightBeingPressed = false; + boolean downBeingPressed = false; + boolean upBeingPressed = false; + + public PlayerSprite(MapUI mapui) { + this.mapui = mapui; + } + + public void keyPressed(KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_LEFT) { + dx = -1; + leftBeingPressed = true; + } + if (e.getKeyCode() == KeyEvent.VK_RIGHT) { + dx = 1; + rightBeingPressed = true; + } + if (e.getKeyCode() == KeyEvent.VK_UP) { + dy = -1; + upBeingPressed = true; + } + if (e.getKeyCode() == KeyEvent.VK_DOWN) { + dy = 1; + downBeingPressed = true; + } + } + + public void keyReleased(KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_LEFT) { + leftBeingPressed = false; + if (rightBeingPressed == false) + dx = 0; + } + + if (e.getKeyCode() == KeyEvent.VK_RIGHT) { + rightBeingPressed = false; + if (leftBeingPressed == false) + dx = 0; + } + + if (e.getKeyCode() == KeyEvent.VK_UP) { + upBeingPressed = false; + if (downBeingPressed == false) + dy = 0; + } + + if (e.getKeyCode() == KeyEvent.VK_DOWN) { + downBeingPressed = false; + if (upBeingPressed == false) + dy = 0; + } + + // This fixes some bugs with holding three keys down at once and letting go of two (Basically ensures that dx and dy match which keys are currently being held) + if(leftBeingPressed) + dx = -1; + if(rightBeingPressed) + dx = 1; + if(downBeingPressed) + dy = 1; + if(upBeingPressed) + dy = -1; + + } + + public void move() { + if (x + dx >= 0 && x + dx <= mapui.getWidth() - WIDTH && y + dy >= 0 && y + dy <= mapui.getHeight() - WIDTH) { + x = x + dx; + changeInX = changeInX + dx; + y = y + dy; + changeInY = changeInY + dy; + } + + } + + public void paint(Graphics2D g) { + g.setColor(color); + g.fillOval(x, y, WIDTH, WIDTH); + } + +} diff --git a/MerchantRPGCSE2102/src/tests/MockGame.java b/MerchantRPGCSE2102/src/tests/MockGame.java new file mode 100644 index 0000000..1856265 --- /dev/null +++ b/MerchantRPGCSE2102/src/tests/MockGame.java @@ -0,0 +1,33 @@ +package tests; + +import javax.swing.JFrame; + +import model.Map; +import model.Player; +import view.MapUI; +import controller.RPGame; + +public class MockGame { + + public static void main(String[] args) throws InterruptedException { + // This sets up the window for the game which is a 300 by 300 pixels JFrame + Player player = new Player("TestPlayer", 0, null); + Map map = new Map(30, 40); + map.initializePlayer(player, 0, 0); + JFrame frame = new JFrame("Merchant RPG"); + MapUI mapui = new MapUI(map); + frame.add(mapui); + frame.setSize(RPGame.WIDTH, RPGame.HEIGHT); + frame.setResizable(false); + frame.setVisible(true); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setLocationRelativeTo(null); + + while (true) { + mapui.move(); + mapui.repaint(); + Thread.sleep(10); + } + } + +} diff --git a/MerchantRPGCSE2102/src/tests/TestItem.java b/MerchantRPGCSE2102/src/tests/TestItem.java index 31c865b..e53b07a 100644 --- a/MerchantRPGCSE2102/src/tests/TestItem.java +++ b/MerchantRPGCSE2102/src/tests/TestItem.java @@ -15,13 +15,17 @@ public void setup() public void testAdjustedPrice() { setup(); - int testPrice = i.scaleAdjPrice(80); + i.scaleAdjPrice(80); + int testPrice = i.getAdjustedPrice(); assertEquals(80, testPrice); - testPrice = i.scaleAdjPrice(120); - assertEquals(120, testPrice); - testPrice = i.scaleAdjPrice(200); - assertEquals(150, testPrice); - testPrice = i.scaleAdjPrice(0); - assertEquals(50, testPrice); + i.scaleAdjPrice(120); + int testPrice2 = i.getAdjustedPrice(); + assertEquals(120, testPrice2); + i.scaleAdjPrice(180); + int testPrice3 = i.getAdjustedPrice(); + assertEquals(150, testPrice3); + i.scaleAdjPrice(40); + int testPrice4 = i.getAdjustedPrice(); + assertEquals(50, testPrice4); } } diff --git a/MerchantRPGCSE2102/src/tests/TestMap.java b/MerchantRPGCSE2102/src/tests/TestMap.java index 0c99c18..3475d69 100644 --- a/MerchantRPGCSE2102/src/tests/TestMap.java +++ b/MerchantRPGCSE2102/src/tests/TestMap.java @@ -23,7 +23,7 @@ public void test() { } public void setup() { - map = new Map(4); + map = new Map(4, 4); } public void testMapInit() { diff --git a/MerchantRPGCSE2102/src/tests/TestPlayer.java b/MerchantRPGCSE2102/src/tests/TestPlayer.java index da54a73..f1e424a 100644 --- a/MerchantRPGCSE2102/src/tests/TestPlayer.java +++ b/MerchantRPGCSE2102/src/tests/TestPlayer.java @@ -1,6 +1,7 @@ package tests; import controller.RPGame; +import exceptions.NotInInventoryException; import model.Item; import model.Merchant; import model.Player; @@ -46,7 +47,7 @@ public void testBuy() assertEquals(10, p.getItem("water").getQuantity()); } - public void testSell() + public void testSell() throws NotInInventoryException { setup(); testBuy(); diff --git a/MerchantRPGCSE2102/src/view/BackgroundPanel.java b/MerchantRPGCSE2102/src/view/BackgroundPanel.java new file mode 100644 index 0000000..48434ed --- /dev/null +++ b/MerchantRPGCSE2102/src/view/BackgroundPanel.java @@ -0,0 +1,262 @@ +package view; +import java.awt.*; +import java.awt.image.*; +import javax.swing.*; + +/* + * Support custom painting on a panel in the form of + * + * a) images - that can be scaled, tiled or painted at original size + * b) non solid painting - that can be done by using a Paint object + * + * Also, any component added directly to this panel will be made + * non-opaque so that the custom painting can show through. + */ +public class BackgroundPanel extends JPanel +{ + public static final int SCALED = 0; + public static final int TILED = 1; + public static final int ACTUAL = 2; + + private Paint painter; + private Image image; + private int style = SCALED; + private float alignmentX = 0.5f; + private float alignmentY = 0.5f; + private boolean isTransparentAdd = true; + + /* + * Set image as the background with the SCALED style + */ + public BackgroundPanel(Image image) + { + this(image, SCALED); + } + + /* + * Set image as the background with the specified style + */ + public BackgroundPanel(Image image, int style) + { + setImage( image ); + setStyle( style ); + setLayout( new BorderLayout() ); + } + + /* + * Set image as the backround with the specified style and alignment + */ + public BackgroundPanel(Image image, int style, float alignmentX, float alignmentY) + { + setImage( image ); + setStyle( style ); + setImageAlignmentX( alignmentX ); + setImageAlignmentY( alignmentY ); + setLayout( new BorderLayout() ); + } + + /* + * Use the Paint interface to paint a background + */ + public BackgroundPanel(Paint painter) + { + setPaint( painter ); + setLayout( new BorderLayout() ); + } + + /* + * Set the image used as the background + */ + public void setImage(Image image) + { + this.image = image; + repaint(); + } + + /* + * Set the style used to paint the background image + */ + public void setStyle(int style) + { + this.style = style; + repaint(); + } + + /* + * Set the Paint object used to paint the background + */ + public void setPaint(Paint painter) + { + this.painter = painter; + repaint(); + } + + /* + * Specify the horizontal alignment of the image when using ACTUAL style + */ + public void setImageAlignmentX(float alignmentX) + { + this.alignmentX = alignmentX > 1.0f ? 1.0f : alignmentX < 0.0f ? 0.0f : alignmentX; + repaint(); + } + + /* + * Specify the horizontal alignment of the image when using ACTUAL style + */ + public void setImageAlignmentY(float alignmentY) + { + this.alignmentY = alignmentY > 1.0f ? 1.0f : alignmentY < 0.0f ? 0.0f : alignmentY; + repaint(); + } + + /* + * Override method so we can make the component transparent + */ + public void add(JComponent component) + { + add(component, null); + } + + /* + * Override to provide a preferred size equal to the image size + */ + @Override + public Dimension getPreferredSize() + { + if (image == null) + return super.getPreferredSize(); + else + return new Dimension(image.getWidth(null), image.getHeight(null)); + } + + /* + * Override method so we can make the component transparent + */ + public void add(JComponent component, Object constraints) + { + if (isTransparentAdd) + { + makeComponentTransparent(component); + } + + super.add(component, constraints); + } + + /* + * Controls whether components added to this panel should automatically + * be made transparent. That is, setOpaque(false) will be invoked. + * The default is set to true. + */ + public void setTransparentAdd(boolean isTransparentAdd) + { + this.isTransparentAdd = isTransparentAdd; + } + + /* + * Try to make the component transparent. + * For components that use renderers, like JTable, you will also need to + * change the renderer to be transparent. An easy way to do this it to + * set the background of the table to a Color using an alpha value of 0. + */ + private void makeComponentTransparent(JComponent component) + { + component.setOpaque( false ); + + if (component instanceof JScrollPane) + { + JScrollPane scrollPane = (JScrollPane)component; + JViewport viewport = scrollPane.getViewport(); + viewport.setOpaque( false ); + Component c = viewport.getView(); + + if (c instanceof JComponent) + { + ((JComponent)c).setOpaque( false ); + } + } + } + + /* + * Add custom painting + */ + @Override + protected void paintComponent(Graphics g) + { + super.paintComponent(g); + + // Invoke the painter for the background + + if (painter != null) + { + Dimension d = getSize(); + Graphics2D g2 = (Graphics2D) g; + g2.setPaint(painter); + g2.fill( new Rectangle(0, 0, d.width, d.height) ); + } + + // Draw the image + + if (image == null ) return; + + switch (style) + { + case SCALED : + drawScaled(g); + break; + + case TILED : + drawTiled(g); + break; + + case ACTUAL : + drawActual(g); + break; + + default: + drawScaled(g); + } + } + + /* + * Custom painting code for drawing a SCALED image as the background + */ + private void drawScaled(Graphics g) + { + Dimension d = getSize(); + g.drawImage(image, 0, 0, d.width, d.height, null); + } + + /* + * Custom painting code for drawing TILED images as the background + */ + private void drawTiled(Graphics g) + { + Dimension d = getSize(); + int width = image.getWidth( null ); + int height = image.getHeight( null ); + + for (int x = 0; x < d.width; x += width) + { + for (int y = 0; y < d.height; y += height) + { + g.drawImage( image, x, y, null, null ); + } + } + } + + /* + * Custom painting code for drawing the ACTUAL image as the background. + * The image is positioned in the panel based on the horizontal and + * vertical alignments specified. + */ + private void drawActual(Graphics g) + { + Dimension d = getSize(); + Insets insets = getInsets(); + int width = d.width - insets.left - insets.right; + int height = d.height - insets.top - insets.left; + float x = (width - image.getWidth(null)) * alignmentX; + float y = (height - image.getHeight(null)) * alignmentY; + g.drawImage(image, (int)x + insets.left, (int)y + insets.top, this); + } +} \ No newline at end of file diff --git a/MerchantRPGCSE2102/src/view/MapUI.java b/MerchantRPGCSE2102/src/view/MapUI.java new file mode 100644 index 0000000..68294ac --- /dev/null +++ b/MerchantRPGCSE2102/src/view/MapUI.java @@ -0,0 +1,83 @@ +package view; + +import java.awt.Color; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; + +import javax.swing.JPanel; + +import model.Map; +import sprites.PlayerSprite; + +@SuppressWarnings("serial") +public class MapUI extends JPanel { + + PlayerSprite player = new PlayerSprite(this); + Map map; + + + public MapUI(Map map) { + this.map = map; + addKeyListener(new KeyListener() { + + @Override + public void keyPressed(KeyEvent e) { + player.keyPressed(e); + + } + + @Override + public void keyReleased(KeyEvent e) { + player.keyReleased(e); + + } + + @Override + public void keyTyped(KeyEvent e) { + + } + + }); + setFocusable(true); + } + + + @Override + public void paint(Graphics g) { + super.paint(g); + Graphics2D g2d = (Graphics2D) g; + g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); + player.paint(g2d); + g2d.setColor(Color.GRAY); + g2d.setFont(new Font("Verdana", Font.BOLD, 20)); + g2d.drawString("x: " + player.x + " y : " + player.y, 10, 20); + g2d.drawString("delta X: " + player.changeInX +" delta Y: " + player.changeInY, 10, 50); + } + + public void move() { + player.move(); + + if (player.changeInX == 30) { + map.movePlayer("east"); + player.changeInX = 0; + } + if (player.changeInX == -30) { + map.movePlayer("west"); + player.changeInX = 0; + } + if (player.changeInY == -30) { + map.movePlayer("north"); + player.changeInY = 0; + } + if (player.changeInY == 30) { + map.movePlayer("south"); + player.changeInY = 0; + } + } + + +} diff --git a/MerchantRPGCSE2102/src/view/StartScreen.java b/MerchantRPGCSE2102/src/view/StartScreen.java new file mode 100644 index 0000000..d7e8e4a --- /dev/null +++ b/MerchantRPGCSE2102/src/view/StartScreen.java @@ -0,0 +1,82 @@ +package view; + +import java.awt.Color; +import java.awt.GradientPaint; +import java.awt.Image; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; + +import javax.imageio.ImageIO; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JPanel; + +public class StartScreen extends JFrame { + private static final long serialVersionUID = 1L; + JPanel startMenu = new JPanel(); + + public static void main(String[] args) throws IOException { + new StartScreen(); + } + + public StartScreen() throws IOException { + Image icon, background; + icon = loadIcon(); + background = loadBackground(); + BackgroundPanel panel = new BackgroundPanel(background, BackgroundPanel.ACTUAL, 1.0f, 0.5f); + this.setIconImage(icon); + this.setTitle("The Merchant RPG"); + this.setSize(1500, 844); + this.setLocationRelativeTo(null); + this.setDefaultCloseOperation(EXIT_ON_CLOSE); + this.setResizable(false); + this.setVisible(true); + JButton start = new JButton("Start"); + start.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e){ + System.out.println("Game started"); + } + }); + JButton instructions = new JButton("Instructions"); + instructions.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent e){ + System.out.println("Instructions opened"); + } + }); + this.getContentPane().setLayout(null); + start.setBounds(650, 382, 200, 80); + instructions.setBounds(650, 482, 200, 40); + panel.setBounds(0, 0, 1500, 844); + start.setBackground(null); + instructions.setBackground(null); + this.add(panel); + this.add(instructions); + this.add(start); + } + + public BufferedImage loadIcon() throws IOException { + BufferedImage img = null; + try { + img = ImageIO.read(new File("src/images/icon.png")); + return img; + } catch (IOException e) { + System.out.println("File not found"); + return null; + } + } + + public BufferedImage loadBackground() throws IOException { + BufferedImage img = null; + try { + img = ImageIO.read(new File("src/images/background.jpg")); + return img; + } catch (IOException e) { + System.out.println("File not found"); + return null; + } + } + +} diff --git a/MerchantRPGCSE2102/src/view/Test.java b/MerchantRPGCSE2102/src/view/Test.java deleted file mode 100644 index 072e852..0000000 --- a/MerchantRPGCSE2102/src/view/Test.java +++ /dev/null @@ -1,70 +0,0 @@ -package view; - -import java.awt.BorderLayout; -import java.awt.EventQueue; - -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.border.EmptyBorder; -import javax.swing.JComboBox; -import javax.swing.JTextField; -import javax.swing.JSlider; -import javax.swing.JLabel; -import javax.swing.JButton; -import java.awt.event.ActionListener; -import java.awt.event.ActionEvent; - -public class Test extends JFrame { - - private JPanel contentPane; - private JTextField textField; - - /** - * Launch the application. - */ - public static void main(String[] args) { - EventQueue.invokeLater(new Runnable() { - public void run() { - try { - Test frame = new Test(); - frame.setVisible(true); - } catch (Exception e) { - e.printStackTrace(); - } - } - }); - } - - /** - * Create the frame. - */ - public Test() { - setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - setBounds(100, 100, 400, 400); - contentPane = new JPanel(); - contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); - setContentPane(contentPane); - contentPane.setLayout(null); - - JComboBox comboBox = new JComboBox(); - comboBox.setBounds(61, 141, 131, 20); - contentPane.add(comboBox); - - JLabel lblSelectTheItem = new JLabel("Select the Item you want:"); - lblSelectTheItem.setBounds(61, 105, 168, 14); - contentPane.add(lblSelectTheItem); - - JLabel lblSelectTheAmount = new JLabel("Enter the amount you wish to sell:"); - lblSelectTheAmount.setBounds(61, 197, 168, 14); - contentPane.add(lblSelectTheAmount); - - JButton btnAccept = new JButton("Accept"); - btnAccept.setBounds(247, 306, 89, 23); - contentPane.add(btnAccept); - - textField = new JTextField(); - textField.setBounds(61, 238, 86, 20); - contentPane.add(textField); - textField.setColumns(10); - } -} diff --git a/MerchantRPGCSE2102/src/view/TransactionUI.java b/MerchantRPGCSE2102/src/view/TransactionUI.java index 0db30eb..8d1be0e 100644 --- a/MerchantRPGCSE2102/src/view/TransactionUI.java +++ b/MerchantRPGCSE2102/src/view/TransactionUI.java @@ -1,14 +1,11 @@ package view; -import java.awt.BorderLayout; import java.awt.EventQueue; -import javax.swing.BoxLayout; -import javax.swing.ComboBoxModel; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JPanel; -import javax.swing.JSlider; +import javax.swing.JRootPane; import javax.swing.border.EmptyBorder; import javax.swing.JButton; import javax.swing.JLabel; @@ -18,17 +15,19 @@ import javax.swing.JTextField; import controller.Transaction; +import exceptions.NotInInventoryException; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; +@SuppressWarnings("serial") public class TransactionUI extends JFrame { - private static final ComboBoxModel[] Item = null; private JPanel contentPane; - private static Transaction MASTER; //TransactionUI class will hold the instance of the Transaction that created it + private static Transaction MASTER; //TransactionUI class will hold the instance of the Transaction that created it + private static boolean _inTransaction; //Prevents the user from making multiple transaction windows /** * Launch the application. @@ -51,6 +50,7 @@ public void run() { */ public TransactionUI(Transaction master) { MASTER = master; + _inTransaction = false; setTitle("Transaction Window"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 600, 430); @@ -58,8 +58,8 @@ public TransactionUI(Transaction master) { contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); - - JButton btnBuy = new JButton("BUY"); + + JButton btnBuy = new JButton("BUY"); //creates a "Buy" button btnBuy.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { } @@ -67,47 +67,52 @@ public void actionPerformed(ActionEvent arg0) { btnBuy.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent arg0) { - System.out.println("BUY"); //temporary test code - createBuyWindow(); + System.out.println("BUY"); //temporary test code + if(!_inTransaction) //checks if there is another transaction window open if not, then creates a buy transaction window + createBuyWindow(); } }); btnBuy.setBounds(58, 155, 169, 105); contentPane.add(btnBuy); - - JButton btnSell = new JButton("SELL"); + + JButton btnSell = new JButton("SELL"); //creates a "Sell" button btnSell.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { - System.out.println("SELL"); //temporary test code - createSellWindow(); + System.out.println("SELL"); //temporary test code + if(!_inTransaction) //checks if there is another transaction window open, if not creates a sell transaction window + createSellWindow(); } }); btnSell.setBounds(351, 155, 169, 105); contentPane.add(btnSell); - - JButton btnCancel = new JButton("Cancel"); + + JButton btnCancel = new JButton("End Transaction"); //creates a button to end the transaction btnCancel.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { - System.out.println("Cancel"); //temporary test code - MASTER.actionCancel(); - exitWindow(); + System.out.println("Cancel"); //temporary test code + if(!_inTransaction) + { + MASTER.actionCancel(); + exitWindow(); //Will end the transaction main screen but only if player does not have another transaction screen open + } } }); - btnCancel.setBounds(246, 344, 89, 23); + btnCancel.setBounds(210, 310, 160, 50); contentPane.add(btnCancel); - + JLabel lblWouldYouLike = new JLabel("Would you like to:"); lblWouldYouLike.setFont(new Font("Tahoma", Font.PLAIN, 15)); lblWouldYouLike.setBounds(233, 76, 193, 32); contentPane.add(lblWouldYouLike); - + JLabel lblOr = new JLabel("OR"); lblOr.setFont(new Font("Tahoma", Font.PLAIN, 15)); lblOr.setBounds(277, 189, 35, 32); contentPane.add(lblOr); } - + /** * Will exit the transaction window * incomplete method @@ -116,85 +121,178 @@ public void exitWindow() { this.dispose(); } - + /** * Will create a window for the BUY option - * incomplete method + * INCOMPLETE METHOD */ public static void createBuyWindow() { - EventQueue.invokeLater(new Runnable() + _inTransaction = true; //does not allow new transaction windows to be opened while buy window is + final JFrame frame = new JFrame("Buy"); + frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + frame.setBounds(100, 100, 400, 400); + frame.setUndecorated(true); + frame.getRootPane().setWindowDecorationStyle(JRootPane.NONE); + JPanel contentPane = new JPanel(); + contentPane = new JPanel(); + contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); + frame.setContentPane(contentPane); + contentPane.setLayout(null); + + String[] itemList = new String[MASTER.getTargetMerchant().getInventory().length]; //create a new array of strings with the length of the player's inventory + for(int i = 0; i < itemList.length; i++) //adds all the item names to the item list { + itemList[i] = MASTER.getTargetMerchant().getInventory()[i].getItemName(); + itemList[i] = itemList[i] + " ($" + MASTER.getTargetMerchant().getInventory()[i].getAdjustedPrice() + ")"; + } + + JLabel lblYouHave = new JLabel("You have: $" + MASTER.getPlayer().getPlayerCash()); + lblYouHave.setBounds(61, 27, 86, 14); + contentPane.add(lblYouHave); + + @SuppressWarnings({ "rawtypes", "unchecked" }) + final JComboBox comboBox = new JComboBox(itemList); //create a drop-down menu for the player to choose from + comboBox.setBounds(61, 141, 131, 20); + contentPane.add(comboBox); + + final JTextField textField = new JTextField(); //create a text field for the player to enter the amount desired into + textField.setBounds(61, 238, 86, 20); + contentPane.add(textField); + textField.setColumns(10); + + JLabel lblSelectTheItem = new JLabel("Select the Item you want:"); //label containing instructions + lblSelectTheItem.setBounds(61, 105, 168, 14); + contentPane.add(lblSelectTheItem); + + JLabel lblSelectTheAmount = new JLabel("Enter the amount you wish to buy:"); //label containing instructions + lblSelectTheAmount.setBounds(61, 197, 275, 30); + contentPane.add(lblSelectTheAmount); + + JButton btnCancel = new JButton("Cancel"); //cancel button, re-enables the player's ability to call new transaction windows + btnCancel.addMouseListener(new MouseAdapter() { @Override - public void run() - { - JFrame frame = new JFrame("Buy"); - frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); - frame.setBounds(100, 100, 600, 600); - JPanel contentPane = new JPanel(); - contentPane = new JPanel(); - contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); - frame.setContentPane(contentPane); - contentPane.setLayout(null); - - frame.setVisible(true); + public void mouseClicked(MouseEvent arg0) { + _inTransaction = false; + frame.dispose(); } }); + btnCancel.setBounds(61, 306, 89, 23); + contentPane.add(btnCancel); + + JButton btnAccept = new JButton("Accept"); //create an accept button to consume the information the player entered into the menu and text field + btnAccept.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { //information is consumed when player clicks the accept button + String chosenItem = comboBox.getSelectedItem().toString().split(" ")[0]; //consumes the String name of the item from drop-down menu + System.out.println(chosenItem); + + try{ //will attempt to parse the number player entered, will stay on the same screen if it cannot + int chosenAmount = Integer.parseInt(textField.getText()); + if(MASTER.actionBuy(chosenItem, chosenAmount)) //will attempt to buy the specified amount of the chosen item + { + System.out.println(chosenAmount); + _inTransaction = false; + frame.dispose(); + } + else + throw new NumberFormatException(); //will throw a NumberFormatException if actionBuy returns a false + } + catch(NumberFormatException exception){ + System.out.println("Must input an amount that you can afford"); + } + } + }); + btnAccept.setBounds(247, 306, 89, 23); + contentPane.add(btnAccept); + frame.setVisible(true); } - + /** * Will create a window for the SELL option - * incomplete method + * INCOMPLETE METHOD: Still needs to integrate with the transaction limit in the daily cycle */ @SuppressWarnings({ "unchecked", "rawtypes" }) public static void createSellWindow() { + _inTransaction = true; //does not allow new transaction windows to be opened if sell window is final JFrame frame = new JFrame("Sell"); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); - frame.setBounds(100, 100, 600, 600); + frame.setBounds(100, 100, 400, 400); + frame.setUndecorated(true); + frame.getRootPane().setWindowDecorationStyle(JRootPane.NONE); JPanel contentPane = new JPanel(); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); frame.setContentPane(contentPane); contentPane.setLayout(null); - - String[] itemList = new String[MASTER.getPlayer().getInventory().length]; //create a new array of strings with the length of the player's inventory //item that the player chooses from the combobox - for(int i = 0; i < itemList.length; i++) //adds all the item names to the item list + + String[] itemList = new String[MASTER.getPlayer().getInventory().length]; //create a new array of strings with the length of the player's inventory //item that the player chooses from the combobox + for(int i = 0; i < itemList.length; i++) //adds all the item names to the item list { itemList[i] = MASTER.getPlayer().getInventory()[i].getItemName(); + itemList[i] = itemList[i] + " (x" + MASTER.getPlayer().getInventory()[i].getQuantity() + ")"; } - final JComboBox comboBox = new JComboBox(itemList); + JLabel lblYouHave = new JLabel(MASTER.getTargetMerchant().getName() + " has: $" + MASTER.getTargetMerchant().getCurrentCash()); + lblYouHave.setBounds(61, 27, 299, 14); + contentPane.add(lblYouHave); + + final JComboBox comboBox = new JComboBox(itemList); //create a drop-down menu for the player to choose from comboBox.setBounds(61, 141, 131, 20); contentPane.add(comboBox); - - final JTextField textField = new JTextField(); + + final JTextField textField = new JTextField(); //create a text field for the player to enter the amount desired into textField.setBounds(61, 238, 86, 20); contentPane.add(textField); textField.setColumns(10); - - JLabel lblSelectTheItem = new JLabel("Select the Item you want:"); + + JLabel lblSelectTheItem = new JLabel("Select the Item you want:"); //label containing instructions lblSelectTheItem.setBounds(61, 105, 168, 14); contentPane.add(lblSelectTheItem); - - JLabel lblSelectTheAmount = new JLabel("Enter the amount you wish to sell:"); - lblSelectTheAmount.setBounds(61, 197, 168, 14); + + JLabel lblSelectTheAmount = new JLabel("Enter the amount you wish to sell:"); //label containing instructions + lblSelectTheAmount.setBounds(61, 197, 275, 30); contentPane.add(lblSelectTheAmount); - - JButton btnAccept = new JButton("Accept"); + + JButton btnCancel = new JButton("Cancel"); //cancel button, re-enables the player's ability to call new transaction windows + btnCancel.addMouseListener(new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent arg0) { + _inTransaction = false; + frame.dispose(); + } + }); + btnCancel.setBounds(61, 306, 89, 23); + contentPane.add(btnCancel); + + JButton btnAccept = new JButton("Accept"); //create an accept button to consume the information the player entered into the menu and text field btnAccept.addMouseListener(new MouseAdapter() { @Override - public void mouseClicked(MouseEvent e) { - String chosenItem = comboBox.getSelectedItem().toString(); + public void mouseClicked(MouseEvent e) { //information is consumed when player clicks the accept button + String chosenItem = comboBox.getSelectedItem().toString().split(" ")[0]; //consumes the String name of the item from drop-down menu System.out.println(chosenItem); - + boolean isGood = false; + try{ - int chosenAmount = Integer.parseInt(textField.getText()); - System.out.println(chosenAmount); - frame.dispose(); + try{ //will attempt to parse the number player entered, will stay on the same screen if it cannot + int chosenAmount = Integer.parseInt(textField.getText()); + isGood = MASTER.actionSell(chosenItem, chosenAmount); //checks if the merchant will buy that item + if(isGood) //will attempt to sell the specified amount of the chosen item + { + System.out.println(chosenAmount); + _inTransaction = false; + frame.dispose(); + } + else + throw new NumberFormatException(); //will throw a NumberFormatException if actionSell returns a false + } + catch(NumberFormatException exception){ + System.out.println("Must input a number less than or equal to the total amount of the item that you have"); + } } - catch(NumberFormatException ex){ - System.out.println("Must input a number less than or equal to the total amount of the item that you have"); + catch(NotInInventoryException niiexception){ + System.out.println("Merchant does not accept that item");; } } });