2015-07-11 19 views
0

問:的Java,JDBC:更新和顯示值/從SQLite的分貝

如何在數據庫中的程序運行更新numberOfWins(撲克回合玩法),&在程序結束執行,顯示數據在/從我的數據庫?

背景:

這是一個相當標準的基於控制檯的撲克遊戲。表是經銷商(創造手)&執行輪。主打PokerGameMain。我還有卡,甲板,播放器,錢包等課程。 3名球員被髮牌,創造一隻手,雙手被打出,有一個贏家&更寬鬆,這是一輪。我已將當前代碼包含在這些類的上下文中。

我的問題是關於兩臺數據庫/ JDBC/SQLite的類(SQLiteJDBC,數據庫)我試圖實現。我已經將這些僅用於學習目的。我試圖獲得有關數據庫/ JDBC/SQLite & maven(我曾經用來管理我的SQLite依賴項)的知識。

我在這個節目工作得很努力,但我有一個小麻煩看到如何把它拉起來。

問題再次:

小學)我如何:

  • 建立DB(撲克)......做我的想法。

  • 創建一個包含2列(palyerName,numberOfWins)的表格(玩家)......我想。

  • 創建3行(player1-3)...完成我的想法。

  • 更新numberOfWins在DB爲(撲克回合玩法)程序運行,&在程序執行結束後,在我的數據庫顯示的數據

中學)有關建議:

  • 我的異常處理&設計SQLiteJDBC &數據庫

SQLiteJDBC

注:

在我所知道的程序的唯一錯誤是一個未經檢查的異常 &一個無法解析的方法。無論是在SQLiteJDBC,這裏&這裏:

try { 
     db.execute(dropTable); 
     db.execute(createTable); 
     db.execute(insertInto1); 
     db.execute(insertInto2); 
     db.execute(insertInto3); 

     ResultSet resultSets = db.executeQuery(selectFrom); 
     try { 
      while (resultSets.next()) { 
       // read the result set 
       System.out.println("player = " + resultSets.getString("playerName")); 
       System.out.println("number of wins = " + resultSets.getInt("numberOfWins")); 
      } 
     } 

try { 
      db.close(); 
     } 



package com.craigreedwilliams.utilities; 

import java.sql.*; 

/** 
* Created by Reed on 7/10/2015. 
*/ 
public class SQLiteJDBC { 
    public static void passQuery() { 
     String dropTable = "DROP TABLE if EXISTS players"; 
     String createTable = "CREATE TABLE players(VARCHAR(25) playerName, INTEGER numberOfWins)"; 
     String insertInto1 = "INSERT INTO player1 VALUES ('player1', 0)"; 
     String insertInto2 = "INSERT INTO player2 VALUES ('player2', 0)"; 
     String insertInto3 = "INSERT INTO player3 VALUES ('player3', 0)"; 
     String selectFrom = "SELECT * FROM players"; 

     // Url for SqlLite 
     String jdbcDbType = "jdbc:sqlite"; 
     String dbName = "poker.db"; 
     String dbUrl = jdbcDbType + ":" + dbName; 

     Database db = new Database(dbUrl); 
     try { 
      db.execute(dropTable); 
      db.execute(createTable); 
      db.execute(insertInto1); 
      db.execute(insertInto2); 
      db.execute(insertInto3); 

      ResultSet resultSets = db.executeQuery(selectFrom); 
      try { 
       while (resultSets.next()) { 
        // read the result set 
        System.out.println("player = " + resultSets.getString("playerName")); 
        System.out.println("number of wins = " + resultSets.getInt("numberOfWins")); 
       } 
      } 
      finally { 
       try { 
        resultSets.close(); 
       } 
       catch (Exception ignore) { 
       } 
      } 
     } 
     finally { 
      try { 
       db.close(); 
      } 
      catch (Exception ignore) { 
      } 
     } 
    } 
} 

數據庫

package com.craigreedwilliams.utilities; 

import java.sql.*; 

/** 
* Created by Reed on 7/10/2015. 
*/ 
public class Database { 
    public String dbUrl; 
    private String sqliteDriver = "org.sqlite.JDBC"; 
    private String driver; 
    private Connection connection = null; 
    private Statement statement = null; 

    public Database() { 

    } 

    public Database(String dbUrl) { 
     this.dbUrl = dbUrl; 
     // sqliteDriver = getDriverString(dbUrl); 
     try { 
      setConnection(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    private void setConnection() throws Exception { 
     try { 
      // registered DriverName using the current class loader 
      Class.forName(sqliteDriver); 
     } 
     catch (Exception e) { 
      // connection failed 
      System.out.println("DriverName: " + driver + " was not available"); 
      System.err.println(e); 
      throw e; 
     } 
     // create a database connection 
     connection = DriverManager.getConnection(dbUrl); 
     try { 
      statement = connection.createStatement(); 
     } 
     catch (Exception e) { 
      try { 
       connection.close(); 
      } 
      catch (Exception ignore) { 
      } 
      connection = null; 
     } 
    } 

    // this method should undoubtedly be public as we'll want to call this 
    // to close connections externally to the class 
    public void closeConnection() { 
     if (statement!=null) { 
      try { 
       statement.close(); 
      } 
      catch (Exception ignore) { 
      } 
     } 
     if (connection!=null) { 
      try { 
       connection.close(); 
      } 
      catch (Exception ignore) { 
      } 
     } 
    } 

    // and we will definitely want to be able to call the following two 
    // functions externally since they expose the database 
    // behaviour which we are trying to access 
    public ResultSet executeQuery(String query) throws SQLException { 
     return statement.executeQuery(query); 
    } 

    public void execute(String query) throws SQLException { 
     statement.executeUpdate(query); 
    } 

} 

PokerGameMain

package com.craigreedwilliams.game; 

import java.util.Scanner; 

/** 
* Hello world! 
* 
*/ 
public class PokerGameMain 
{ 
    public static void main(String[] args) { 

     //Input Object of the scanner class 
     Scanner input = new Scanner(System.in); 

     int choice; 

     System.out.println("Welcome to Poker Table! May the odds forever be in your favor :)"); 



     do { 

      printMainGameWelcomeMenu(); 

      choice = input.nextInt(); 

      switch (choice){ 

       case 1: 
        //call start game method or class here 
        startGame(); 
        break; 
       case 2: 
        //end game here 
        printMainGameGoodbyeMessage(); 
        break; 
       default: 
        System.out.println("The value you entered is outside of the range required for this application..."); 

      } 

     } while (choice != 2); 

    } 


    public static void printMainGameWelcomeMenu(){ 

     System.out.println("This is the poker game's menu: \n" 
       + "To start the game enter: 1\n" 
       + "To end game enter: 2\n"); 
    } 

    public static void printMainGameGoodbyeMessage(){ 

     System.out.println("Thank you for playing the poker game! Hope you enjoyed your experience. Have a great day! :D"); 
    } 

    public static void startGame(){ 

     int count = 1; 
     Table table = new Table(); 

     getUserInput(table); 

     while (count < 4) { 

      System.out.println("Round : " + count + "...\n"); 

      table.dealCards(); 
      table.showCards(); 

      count++; 
     } 


    } 

    public static void getUserInput(Table table){ 

     Scanner usrInput = new Scanner(System.in); 
     boolean anteSet = false; 

     System.out.println("Before the game starts, I will need some information...\n"); 

     System.out.println("What is your name?"); 
     String name = usrInput.nextLine(); 

     //set player name 
     table.getPlayerAt(0).setPlayerName(name); 


     // set ante 
     do { 
      System.out.println("How much are you willing to bet for every round? Keep in mind there will have to be at least three rounds..."); 
      Double ante = usrInput.nextDouble(); 

      if(checkAnte(ante, table.getPlayerAt(0).getWallet())) { 
       table.getPlayerAt(0).setAnteValue(ante); 
       anteSet = true; 
      } 
     }while (!(anteSet)); 

    } 

    public static boolean checkAnte(double ante, Wallet wallet){ 

     if (ante * 3.0 > wallet.getBalance()) { 
      System.out.println("Sorry your wallet balance is less than you think...Please reconsider the ante value"); 
      return false; 
     } 
     else 
     { 
      wallet.deductFromBalance(ante); 
      System.out.println("Your ante for each round is set to be: " + ante + ". Good luck!"); 
      return true; 
     } 

    } 
} 

package com.craigreedwilliams.game; 

/** 
* Created by Reed on 7/10/2015. 
*/ 
public class Table { 
    // two private attributes 
    private Player[] players; 
    private Deck deck; 
    private double pot; 
    private Player winner; 


    /****************************************** 
    ** The array is set in the following way: 
    ****************************************** 
    ** pairs are each given 1 point  ** 
    ** three of a kind are given 3 points ** 
    ** straights are given 5 points  ** 
    ** flush are given 7 points   ** 
    ** four of a kind are given 8 points ** 
    ** royal straights are given 10 points ** 
    ** royal flush are given 12 points  ** 
    ****************************************** 
    */ 
    private int[][] game = new int [7][2]; 

    // constructor initializes the deck and cards 
    public Table() { 
     deck = new Deck(); 
     players = new Player[3]; 
     players[0] = new Player(); 
     players[1] = new Player(); 
     players[2] = new Player(); 
     deck.shuffle(); 

    } 

    // getter for player at the given index 
    public Player getPlayerAt(int index){ 
     return players[index]; 
    } 

    // deals the card to each player 
    public void dealCards() { 
     int count = 0; 
     for (int i = 0; i < players[0].getCards().length; i++) { 
      for (int j = 0; j < players.length; j++) { 
       players[j].setCardAtIndex(deck.getCard(count++), i); 
      } 
     } 
    } 

    // simulates the game and shows the result 
    public void showCards() { 
     for (int i = 0; i < players.length; i++) { 
      System.out.print("Player " + (i + 1) + ": \n"); 
      for (int j = 0; j < players[0].getCards().length; j++) { 
       System.out.println("{" + players[i].getCardAtIndex(j).toString() + "} "); 
      } 
      if(players[i].countPair() > 0) { 
       System.out.println("Pair(S):" + players[i].countPair() + "! \n"); 
       game[0][i] += players[i].countPair(); 
      } 
      if(players[i].isFlush()) { 
       System.out.println("Flush! "); 
      } 
      if(players[i].isRoyalFlush()) 
       System.out.println("Royal Flush!!\n"); 
      if(players[i].isThreeOfAkind()) 
       System.out.println("Three of a kind! "); 
      if(players[i].isFourOfAkind()) 
       System.out.println("Four of a kind!!\n"); 
      if(players[i].isStraight()) 
       System.out.println("Straight! \n"); 
      if(players[i].isRoyalStraight()) 
       System.out.println("Royal Straight!!\n"); 
      else 
       System.out.print("\n"); 
     } 
    } 
} 

錢包

package com.craigreedwilliams.game; 

import java.util.Random; 

/** 
* Created by Reed on 7/11/2015. 
*/ 
public class Wallet { 
    private double balance; 
    /** 
    * default Wallet constructor 
    */ 
    public Wallet() { 
     setRandomStartingBalance(50.0, 500.0); 
    } 

    private void setRandomStartingBalance(double minimum, double maximum) { 
     Random random = new Random(); 
     double randomStartingBalance = minimum + (maximum - minimum) * random.nextDouble(); 
     balance = randomStartingBalance; 
    } 

    public double getBalance() { 
     return balance; 
    } 

    public void deductFromBalance(double price) { 
     this.balance = balance - price; 
    } 
} 

球員

package com.craigreedwilliams.game; 

/** 
* Created by Reed on 7/10/2015. 
*/ 
public class Player { 
    private final static int MAX = 5; 
    private Card cards[]; //hand 
    private Deck tempDeck = new Deck(); 
    private Double anteValue = 0.0; 


    private Wallet wallet; 
    private String playerName = ""; 



    int gamesWon = 0; 

    // private bools for checks 
    private boolean pair = false; 
    private boolean threeOfAkind = false; 
    private boolean fourOfAkind = false; 
    private boolean royalStraight = false; 
    private boolean royalFlush = false; 



    //constructor initializes 5 cards in each hand 
    public Player() { 
     cards = new Card[MAX]; 
     wallet = new Wallet(); 
    } 

    // getters are setters for name and ante value 
    public String getPlayerName() { 
     return playerName; 
    } 

    public void setPlayerName(String playerName) { 
     this.playerName = playerName; 
    } 

    public Double getAnteValue() { 
     return anteValue; 
    } 

    public void setAnteValue(Double anteValue) { 
     this.anteValue = anteValue; 
    } 

    // getter for wallet for player object 
    public Wallet getWallet() { 
     return wallet; 
    } 

    // getter and setter for games won so far... 
    public int getGamesWon() { 
     return gamesWon; 
    } 

    public void setGamesWon(int gamesWon) { 
     this.gamesWon = gamesWon; 
    } 

    //returns all the cards in hand 
    public Card[] getCards() { 
     return cards; 
    } 

    //get the cards at a particular position 
    public Card getCardAtIndex(int index) { 
     return (index >= 0 && index < MAX) ? cards[index] : null; 
    } 

    //sets the card at particular position 
    public void setCardAtIndex(Card c, int index) { 
     if(index >= 0 && index < MAX) 
      cards[index] = c; 
    } 

    // basic bool return functions 
    public boolean isRoyalStraight() { 
     return royalStraight; 
    } 

    public boolean isThreeOfAkind() { 
     return threeOfAkind; 
    } 

    public boolean isFourOfAkind() { 
     return fourOfAkind; 
    } 

    public boolean isRoyalFlush() { 
     return royalFlush; 
    } 

    //Main Logic here : public functions that check for all winning hands and change private boolean variables 
    //     appropriately 

    //counts number of matched pair 
    public int countPair() { 

     int count = 0; 
     //boolean pairCheck = ((!(threeOfAkind) && (!(fourOfAkind)))); 

     for (int i = 0; i < cards.length; i++) { 
      for (int j = i + 1; j < cards.length; j++) 
      { 
       if (cards[i].getRank().equals(cards[j].getRank())){ 
        count++; 
        if (count == 1) 
         pair = true; 
        else if ((pair) && (count == 3)) { 
         threeOfAkind = true; 
         pair = false; 
        } 
        else if ((threeOfAkind) && (count == 4)) { 
         fourOfAkind = true; 
         threeOfAkind = false; 
        } 

       } 
      } 
     } 
     return (pair) ? count : 0; 
    } 

    //checks if it is a flush or not i.e all five cards of same suit also checks for royal flush 
    public boolean isFlush() 
    { 
     int count = 0; 
     for (int i = 0; i < cards.length; i++) { 
      for (int j = i + 1; j < cards.length; j++) { 
       if (cards[i].getSuit().equals(cards[j].getSuit())) { 
        count++; 
       } 
      } 
      if (count == 5){ 
       if (cards[i].getRankInt() == tempDeck.getRankInt(12)) 
        royalFlush = true; 
      } 

     } 
     return ((count == 5) && (!(royalFlush))) ? true : false; 
    } 

    //checks to see if it is a straight or royal straight or neither 
    public boolean isStraight(){ 
     int count = 0; 

     for (int i = 0; i < cards.length - 1; i++){ 
      if ((cards[i].getRankInt() + 1 == cards[i + 1].getRankInt()) && (count < 4)){ 
       count++; 
      } 
      else if (count == 4){ 
       if (cards[i].getRankInt() == tempDeck.getRankInt(13)){ 
        royalStraight = true; 
       } 
      } 

     } 

     return ((count == 4) && (!(royalStraight))) ? true : false; 
    } 
} 

甲板

package com.craigreedwilliams.game; 

import java.util.Calendar; 
import java.util.Random; 

/** 
* Created by Reed on 7/10/2015. 
*/ 
public class Deck { 
    private final String rank[] = {"2","3","4","5","6","7","8","9","10","Jack","Queen","King", "Ace"}; 
    private final String suits[]={"Hearts","Diamonds","Clubs","Spades"}; 

    private final int rankInt[] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14}; 
    private final int suitsInt[] = {1, 2, 3, 4}; 

    private Card deck[]; 
    private final int MAX = 52; 
    private Random randNum; 

    //makes the deck, constructor - no arguments 
    public Deck() { 
     deck = new Card[MAX]; 

     //uses calendar object to get time stamp 
     Calendar cal = Calendar.getInstance(); 
     long seed = cal.getTimeInMillis(); 

     randNum = new Random(seed); // random generated using time seed 

     // uses modulus operator 
     for(int i = 0; i < deck.length; i++){ 
      deck[i] = new Card(rank[i % 13], suits[i/13], rankInt[i % 13], suitsInt[i/13]); 
     } 
    } 

    //shuffles the deck 
    public void shuffle(){ 

     for(int i = 0; i < deck.length; i++){ 
      int j = randNum.nextInt(MAX); 
      Card c = deck[i]; 
      deck[i] = deck[j]; 
      deck[j] = c; 
     } 
    } 

    //returns the individual card in the deck 
    public Card getCard(int index){ 
     return deck[index]; 
    } 

    //returns rankInt from the deck object at the given index value 
    public int getRankInt(int index) { 
     return rankInt[index]; 
    } 

} 

package com.craigreedwilliams.game; 

/** 
* Created by Reed on 7/10/2015. 
*/ 
public class Card { 
    private String rank; 
    private String suit; 
    private int rankInt; 

    // TODO: remove this if actually never used 
    private int suitInt; 

    //four argument constructor initializes Cards rank and suit (stings and ints) 
    public Card(String rank, String suit, int rankInt, int suitInt) { 
     super(); 
     this.rank = rank; 
     this.suit = suit; 
     this.rankInt = rankInt; 
     this.suitInt = suitInt; 
    } 

    //getter method to return the rank value 
    public String getRank() { 
     return rank; 
    } 

    //getter method to return the suit value 
    public String getSuit() { 
     return suit; 
    } 

    //setter method to initialize the suit 
    public int getRankInt() { 
     return rankInt; 
    } 

    //return String representation of Card object 
    public String toString() { 
     return rank + " : " + suit; 
    } 
} 
+0

所以你只是想更新每個球員的勝利數量? –

+0

你得到了它,然後在所有回合(撲克牌)進行後顯示我的數據庫值。 –

+0

並且每一行都是針對每個玩家的? –

回答

0

你的SQL查詢應該是這樣的:

Select Player,Wins From yourtable Set Wins=Wins + 1 Where Player=playerid 

列只是一個例子,因爲我不知道你怎麼叫不他們;)

並且在每一輪結束時,您只需查詢您的SQL-Server。