So I'm trying to create a monopoly web game using asp.net. I was having issues with variables being saved due to the postback, so I've created a database which stores all the info about the players and squares etc. The problem I'm having now however is for some reason the current player ID isn't being stored/retrieved correctly. I apologise for the relatively long wall of code;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
namespace Monopoly_Web
{
public partial class WebForm1 : System.Web.UI.Page
{
List<Player> players = new List<Player>();
List<Square> squares = new List<Square>();
Player currentPlayer;
Square CurrentSquare;
SQLDatabase.DatabaseTable players_table = new SQLDatabase.DatabaseTable("PlayersTable");
SQLDatabase.DatabaseTable squares_table = new SQLDatabase.DatabaseTable("SquaresTable");
SQLDatabase.DatabaseTable gameinfo_table = new SQLDatabase.DatabaseTable("GameInfoTable");
int currentPlayerID = 0;
int currentSquareID = 0;
int freeParkingAmount = 500;
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
readFromDatabase();
}
}
//------------------------------------------------------------------------------------------------------------------------------------
// MAIN GAME BUTTONS
//------------------------------------------------------------------------------------------------------------------------------------
protected void RollDiceButton_Click(object sender, EventArgs e)
{
int dice = new Random((int)DateTime.Now.Ticks).Next(1, 7); // Pick a number from 1 to 6 and add it to the current position.
diceRoll.Visible = true;
diceRoll.Text = "You rolled a " + dice.ToString();
currentPlayer.SetPosition(MovePlayer(dice));
CurrentSquare = squares[currentPlayer.GetPosition()];
updateDisplay();
RollDiceButton.Enabled = false;
EndTurnButton.Enabled = true;
writeToDatabase();
}
protected void BuyButton_Click(object sender, EventArgs e)
{
writeToDatabase();
}
protected void EndTurnButton_Click(object sender, EventArgs e)
{
diceRoll.Visible = false;
buyLabel.Visible = false;
payLabel.Visible = false;
RollDiceButton.Enabled = true;
BuyButton.Enabled = false;
EndTurnButton.Enabled = false;
//checkBankruptcy();
changeActivePlayer();
currentPlayerLabel.Text = "Current Player: " + currentPlayerID.ToString();
updateDisplay();
writeToDatabase();
}
protected void ResumeButton_Click(object sender, EventArgs e)
{
resumeGame();
RollDiceButton.Enabled = true;
EndTurnButton.Enabled = true;
StartButton.Visible = false;
ResumeButton.Visible = false;
}
//------------------------------------------------------------------------------------------------------------------------------------
// PLAYER MOVEMENT
//------------------------------------------------------------------------------------------------------------------------------------
private int MovePlayer(int dice_value)
{
currentPlayer.SetPosition(currentPlayer.GetPosition() + dice_value);
if (currentPlayer.GetPosition() > (squares.Count - 1))
{
currentPlayer.SetPosition(currentPlayer.GetPosition() % squares.Count());
currentPlayer.SetMoney(200);
}
return currentPlayer.GetPosition();
}
private void changeActivePlayer()
{
currentPlayerID += 1;
do
{
if (currentPlayerID >= players.Count())
{
currentPlayerID = 0;
}
currentPlayer = players[currentPlayerID];
} while (currentPlayer.IsBankrupt() == true);
}
//------------------------------------------------------------------------------------------------------------------------------------
// START/RESUME GAME
//------------------------------------------------------------------------------------------------------------------------------------
private void startGame()
{
createArrays();
currentPlayer = players[0];
CurrentSquare = squares[0];
if (players_table == null)
{
foreach (Player player in players)
{
SQLDatabase.DatabaseRow new_row = players_table.NewRow();
string new_id = players_table.GetNextID().ToString();
new_row["ID"] = new_id;
new_row["position"] = player.GetPosition().ToString();
new_row["money"] = player.GetMoney().ToString();
new_row["isInJail"] = player.IsInJail().ToString();
new_row["isBankrupt"] = player.IsBankrupt().ToString();
players_table.Insert(new_row);
}
}
if (gameinfo_table == null)
{
SQLDatabase.DatabaseRow new_row = gameinfo_table.NewRow();
new_row["ID"] = 1.ToString();
new_row["CurrentPlayerID"] = currentPlayer.GetID().ToString();
new_row["CurrentSquareID"] = CurrentSquare.GetID().ToString();
new_row["FreeParkingAmount"] = freeParkingAmount.ToString();
gameinfo_table.Insert(new_row);
}
writeToDatabase();
}
protected void StartButton_Click(object sender, EventArgs e)
{
startGame();
updateDisplay();
RollDiceButton.Enabled = true;
EndTurnButton.Enabled = true;
StartButton.Visible = false;
ResumeButton.Visible = false;
}
private void resumeGame()
{
readFromDatabase();
updateDisplay();
}
//------------------------------------------------------------------------------------------------------------------------------------
// READ/WRITE TO DATABASE
//------------------------------------------------------------------------------------------------------------------------------------
private void readFromDatabase()
{
createArrays();
for (int i = 0; i < 4; i++)
{
//players[i].SetID(Convert.ToInt32(players_table.GetRow(i)["ID"]));
players[i].SetPosition(Convert.ToInt32(players_table.GetRow(i)["position"]));
players[i].SetMoney(Convert.ToInt32(players_table.GetRow(i)["money"]));
players[i].SetInJail(Convert.ToBoolean(players_table.GetRow(i)["isInJail"]));
players[i].SetIsBankrupt(Convert.ToBoolean(players_table.GetRow(i)["isBankrupt"]));
}
currentPlayerID = Convert.ToInt32(gameinfo_table.GetRow(0)["CurrentPlayerID"]);
currentSquareID = Convert.ToInt32(gameinfo_table.GetRow(0)["CurrentSquareID"]);
freeParkingAmount = Convert.ToInt32(gameinfo_table.GetRow(0)["FreeParkingAmount"]);
currentPlayer = players[currentPlayerID];
CurrentSquare = squares[currentSquareID];
}
private void writeToDatabase()
{
foreach (Player player in players)
{
SQLDatabase.DatabaseRow prow = players_table.GetRow(player.GetID());
//prow["ID"] = player.GetID().ToString();
prow["position"] = player.GetPosition().ToString();
prow["money"] = player.GetMoney().ToString();
prow["isInJail"] = player.IsInJail().ToString();
prow["isBankrupt"] = player.IsBankrupt().ToString();
players_table.Update(prow);
}
SQLDatabase.DatabaseRow girow = gameinfo_table.GetRow(0);
girow["CurrentPlayerID"] = currentPlayerID.ToString();
girow["CurrentSquareID"] = CurrentSquare.GetID().ToString();
girow["FreeParkingAmount"] = freeParkingAmount.ToString();
}
//------------------------------------------------------------------------------------------------------------------------------------
// CREATE PLAYER AND SQUARE ARRAYS
//------------------------------------------------------------------------------------------------------------------------------------
private void createArrays()
{
for (int i = 0; i < 4; i++)
{
Player player = new Player(i);
players.Add(player);
}
Square square0 = new Square(0, 0, 0, "Go", "go");
Square square1 = new Square(1, 60, 2, "Old Kent Road", "prop");
Square square2 = new Square(2, 0, 0, "Community Chest", "comm");
Square square3 = new Square(3, 60, 4, "Whitechapel Road", "prop");
Square square4 = new Square(4, 200, 0, "Income Tax", "tax");
Square square5 = new Square(5, 200, 25, "Kings Cross Station", "prop");
Square square6 = new Square(6, 100, 6, "The Angel Islington", "prop");
Square square7 = new Square(7, 0, 0, "Chance", "chance");
Square square8 = new Square(8, 100, 6, "Euston Road", "prop");
Square square9 = new Square(9, 120, 8, "Pentonville Road", "prop");
Square square10 = new Square(10, 0, 0, "Visiting Jail", "other");
Square square11 = new Square(11, 140, 10, "Pall Mall", "prop");
Square square12 = new Square(12, 150, 12, "Electric Company", "prop");
Square square13 = new Square(13, 140, 10, "Whitehall", "prop");
Square square14 = new Square(14, 160, 12, "Northumberland Avenue", "prop");
Square square15 = new Square(15, 200, 25, "Marylebone Station", "prop");
Square square16 = new Square(16, 180, 14, "Bow Street", "prop");
Square square17 = new Square(17, 0, 0, "Community Chest", "comm");
Square square18 = new Square(18, 180, 14, "Marlborough Street", "prop");
Square square19 = new Square(19, 200, 16, "Vine Street", "prop");
Square square20 = new Square(20, 0, 0, "Free Parking", "freep");
Square square21 = new Square(21, 220, 18, "Strand", "prop");
Square square22 = new Square(22, 0, 0, "Chance", "chance");
Square square23 = new Square(23, 220, 18, "Fleet Street", "prop");
Square square24 = new Square(24, 240, 20, "Trafalgar Square", "prop");
Square square25 = new Square(25, 200, 25, "Fenchurch Street Station", "prop");
Square square26 = new Square(26, 260, 22, "Leicester Square", "prop");
Square square27 = new Square(27, 260, 22, "Coventry Street", "prop");
Square square28 = new Square(28, 150, 12, "Water Works", "prop");
Square square29 = new Square(29, 280, 22, "Piccadilly", "prop");
Square square30 = new Square(30, 0, 0, "Jail", "jail");
Square square31 = new Square(31, 300, 26, "Regent Street", "prop");
Square square32 = new Square(32, 300, 26, "Oxford Street", "prop");
Square square33 = new Square(33, 0, 0, "Community Chest", "comm");
Square square34 = new Square(34, 320, 28, "Bond Street", "prop");
Square square35 = new Square(35, 200, 25, "Liverpool Street Station", "prop");
Square square36 = new Square(36, 0, 0, "Chance", "chance");
Square square37 = new Square(37, 350, 35, "Park Lane", "prop");
Square square38 = new Square(38, 100, 0, "Super Tax", "tax");
Square square39 = new Square(39, 400, 50, "Mayfair", "prop");
squares.Add(square0);
squares.Add(square1);
squares.Add(square2);
squares.Add(square3);
squares.Add(square4);
squares.Add(square5);
squares.Add(square6);
squares.Add(square7);
squares.Add(square8);
squares.Add(square9);
squares.Add(square10);
squares.Add(square11);
squares.Add(square12);
squares.Add(square13);
squares.Add(square14);
squares.Add(square15);
squares.Add(square16);
squares.Add(square17);
squares.Add(square18);
squares.Add(square19);
squares.Add(square20);
squares.Add(square21);
squares.Add(square22);
squares.Add(square23);
squares.Add(square24);
squares.Add(square25);
squares.Add(square26);
squares.Add(square27);
squares.Add(square28);
squares.Add(square29);
squares.Add(square30);
squares.Add(square31);
squares.Add(square32);
squares.Add(square33);
squares.Add(square34);
squares.Add(square35);
squares.Add(square36);
squares.Add(square37);
squares.Add(square38);
squares.Add(square39);
}
}
}
As far as I know the database code I've got works fine as I can resume a game and it will set the player position to be the square they were at before. But for some reason when starting the game it is constantly player 2's turn, and the changeActivePlayer() doesn't seem do anything to help this. I stepped through the code line by line and after clicking the EndTurnButton the playerID had changed but when it came to getting the values from the database it was back to player 2's ID. I'm also not sure why it defaults to player 2, seeing as when I call the start game function I set the current player to players[0] so surely it should be player 1? Any help on this would be appreciated.
Related
I am generating voucher no with the concatenation of jdatechooer and jCombobox, when user selects the jcombobox it creates a voucher no and put it in the jTextField1 and passes focus to jTextField2. Till that the Application works fine. However, after submitting data, after two or three times, when I create a voucher all the JTextFields freezes and I cannot put the data into database. enter code here
public class Voucher extends javax.swing.JInternalFrame {
private java.util.Date Current_Date ;
private java.sql.Date sqlDate;
private Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
private SimpleDateFormat dateformat =new SimpleDateFormat("HH:mm:ss");
private SimpleDateFormat simpleformat =new SimpleDateFormat("yyyy-MM-dd");
private Connection connection;
private PreparedStatement preparedStatement;
private ResultSet resultSet, AccountChartSet;
private DBConnection dbc =null;
private StringTokenizer xToken ;
private String Query, CreatedVoucher, DateVal;
private String firstval,secondVal;
private Integer MaxVoucher , VoucherType, COF;
private Double Balance=0.0;
private Double DEBIT = 0.0 , CREDIT = 0.0;
private int row = 0;
private DefaultTableModel dmodel = new DefaultTableModel(new Object[][]
{
{ null, null, null , null, null },
{ null, null, null , null, null },
{ null, null, null , null, null },
{ null, null, null , null, null }
},new String []
{
"Account Code", "Acct Name", "DR /CR", "Amount"
}){
public boolean isCellEditable(int rowIndex, int mColIndex) {
return false;
}
};
/**
* Creates new form Voucher
*/
public Voucher() {
initComponents();
setTitle("Create Voucher");
dbc = new DBConnection();
connection = dbc.dbcon();
dmodel.setNumRows(0);
Current_Date = new java.util.Date();
jDateChooser1.setDate(Current_Date);
jTextField6.setText(Balance.toString());
FetchCOF();
setVisible(true);
}
private void initComponents() {
jScrollPane2 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList<>();
jButton1 = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jTextField6 = new javax.swing.JTextField();
jTextField5 = new javax.swing.JTextField();
jTextField4 = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jComboBox2 = new javax.swing.JComboBox<>();
jTextField3 = new javax.swing.JTextField();
jTextField2 = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jDateChooser1 = new com.toedter.calendar.JDateChooser();
jComboBox1 = new javax.swing.JComboBox<>();
jTextField1 = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jPanel1 = new javax.swing.JPanel();
jLabel10 = new javax.swing.JLabel();
jList1.setModel(new javax.swing.AbstractListModel<String>() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public String getElementAt(int i) { return strings[i]; }
});
jScrollPane2.setViewportView(jList1);
setBackground(new java.awt.Color(69, 105, 159));
setClosable(true);
getContentPane().setLayout(null);
jButton1.setFont(new java.awt.Font("Segoe UI", 0, 12));
jButton1.setIcon(new javax.swing.ImageIcon("D:\\GTradingPK\\src\\gtradingpk\\images\\floppy-disk.png")); // NOI18N
jButton1.setText("Submit");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
getContentPane().add(jButton1);
jButton1.setBounds(10, 385, 593, 50);
jTable1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jTable1.setModel(dmodel);
jTable1.setRowHeight(24);
jTable1.setShowGrid(true);
jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTable1MouseClicked(evt);
}
});
jScrollPane1.setViewportView(jTable1);
getContentPane().add(jScrollPane1);
jScrollPane1.setBounds(10, 210, 593, 170);
jTextField6.setEditable(false);
jTextField6.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
getContentPane().add(jTextField6);
jTextField6.setBounds(453, 180, 150, 25);
jTextField5.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jTextField5.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent evt) {
jTextField5FocusLost(evt);
}
});
getContentPane().add(jTextField5);
jTextField5.setBounds(171, 180, 280, 25);
jTextField4.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
getContentPane().add(jTextField4);
jTextField4.setBounds(10, 180, 160, 25);
jLabel7.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel7.setForeground(new java.awt.Color(255, 255, 255));
jLabel7.setText("Amount");
getContentPane().add(jLabel7);
jLabel7.setBounds(10, 162, 100, 14);
jLabel8.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel8.setForeground(new java.awt.Color(255, 255, 255));
jLabel8.setText("Narration");
getContentPane().add(jLabel8);
jLabel8.setBounds(171, 162, 100, 14);
jLabel9.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel9.setForeground(new java.awt.Color(255, 255, 255));
jLabel9.setText("Balance");
getContentPane().add(jLabel9);
jLabel9.setBounds(453, 162, 100, 14);
jComboBox2.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jComboBox2.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Select", "Debit", "Credit" }));
getContentPane().add(jComboBox2);
jComboBox2.setBounds(453, 130, 150, 25);
jTextField3.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
getContentPane().add(jTextField3);
jTextField3.setBounds(171, 130, 280, 25);
jTextField2.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jTextField2.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent evt) {
jTextField2FocusLost(evt);
}
});
getContentPane().add(jTextField2);
jTextField2.setBounds(10, 130, 160, 25);
jLabel4.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel4.setForeground(new java.awt.Color(255, 255, 255));
jLabel4.setText("Acct Code");
getContentPane().add(jLabel4);
jLabel4.setBounds(10, 110, 120, 20);
jLabel5.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel5.setForeground(new java.awt.Color(255, 255, 255));
jLabel5.setText("Acct Name");
getContentPane().add(jLabel5);
jLabel5.setBounds(171, 110, 120, 20);
jLabel6.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel6.setForeground(new java.awt.Color(255, 255, 255));
jLabel6.setText("Debit / Credit");
getContentPane().add(jLabel6);
jLabel6.setBounds(453, 110, 120, 20);
jDateChooser1.setDateFormatString("dd-MM-yyyy");
jDateChooser1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
getContentPane().add(jDateChooser1);
jDateChooser1.setBounds(453, 80, 150, 25);
jComboBox1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Select Voucher Type", "1-JV", "2-RV", "3-PV", "4-CV" }));
jComboBox1.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
jComboBox1ItemStateChanged(evt);
}
});
getContentPane().add(jComboBox1);
jComboBox1.setBounds(171, 80, 280, 25);
jTextField1.setEditable(false);
jTextField1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
jTextField1.setFocusable(false);
jTextField1.setRequestFocusEnabled(false);
getContentPane().add(jTextField1);
jTextField1.setBounds(10, 80, 160, 25);
jLabel1.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setText("Voucher Code");
getContentPane().add(jLabel1);
jLabel1.setBounds(10, 64, 120, 14);
jLabel2.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel2.setForeground(new java.awt.Color(255, 255, 255));
jLabel2.setText("Voucher Type");
getContentPane().add(jLabel2);
jLabel2.setBounds(171, 64, 120, 14);
jLabel3.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N
jLabel3.setForeground(new java.awt.Color(255, 255, 255));
jLabel3.setText("Date");
getContentPane().add(jLabel3);
jLabel3.setBounds(453, 64, 120, 14);
jPanel1.setBackground(new java.awt.Color(46, 26, 71));
jPanel1.setLayout(null);
jLabel10.setFont(new java.awt.Font("Segoe UI", 0, 20)); // NOI18N
jLabel10.setForeground(new java.awt.Color(255, 255, 255));
jLabel10.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel10.setText("CREATE VOUCHER");
jPanel1.add(jLabel10);
jLabel10.setBounds(0, 10, 610, 30);
getContentPane().add(jPanel1);
jPanel1.setBounds(0, 0, 620, 60);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if(jTextField1.getText().equals(""))
{
JOptionPane.showMessageDialog(null, "Voucher No is Missing ....");
}
else if (jComboBox1.getSelectedIndex() == 0)
{
JOptionPane.showMessageDialog(null, "Voucher Type is Missing ....");
jComboBox1.grabFocus();
}
else if(jTextField5.getText().equalsIgnoreCase(""))
{
JOptionPane.showMessageDialog(null, "Narration is Missing ....");
jTextField5.grabFocus();
}
else if (Balance != 0 )
{
JOptionPane.showMessageDialog(null, "Debit / Credit is not Equal");
}
else
{
double damount = 0.0 , camount = 0.0, balanceamt = 0.0;
try
{
CreateValues();
Current_Date = jDateChooser1.getDate();
String datestamp = simpleformat.format(Current_Date.getTime());
String timeStamp = new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime());
String DateTimess = datestamp+" "+timeStamp;
xToken = new StringTokenizer(jComboBox1.getSelectedItem().toString(), "-");
String voutype = xToken.nextToken().trim();
Integer voint= Integer.parseInt(voutype);
connection.setAutoCommit(false);
Query = "insert into voucher(voucherno, vdate, cof, decr, naration, debitamount,creditamount, balance, void,statuss, xdate) values(?,?,?,?,?,?,?,?,?,?,?) ";
preparedStatement = connection.prepareStatement(Query);
for(int x = 0 ; x<jTable1.getRowCount(); x++)
{
preparedStatement.setString(1, jTextField1.getText());
preparedStatement.setObject(2,DateTimess);
preparedStatement.setLong(3 , Long.parseLong(jTable1.getValueAt(x, 0).toString()));
preparedStatement.setString(4, jTable1.getValueAt(x , 2).toString());
preparedStatement.setString(5, jTextField5.getText());
if(jTable1.getValueAt(x , 2).toString().equalsIgnoreCase("Debit"))
{
damount = Double.parseDouble( jTable1.getValueAt(x, 3).toString() );
balanceamt = damount - camount;
preparedStatement.setDouble(6, damount);
preparedStatement.setDouble(7, camount);
preparedStatement.setDouble(8, balanceamt);
}
else {
camount = Double.parseDouble( jTable1.getValueAt(x, 3).toString() );
balanceamt = damount - camount;
preparedStatement.setDouble(6, damount);
preparedStatement.setDouble(7, camount);
preparedStatement.setDouble(8, balanceamt);
}
preparedStatement.setInt(9 , voint);
preparedStatement.setString(10 , "u");
preparedStatement.setObject(11, Current_Date);
preparedStatement.addBatch();
damount = 0.0 ;
camount = 0.0;
balanceamt = 0.0;
}
preparedStatement.executeBatch();
Query = "insert into vouchercounter values(?,?,?)";
preparedStatement = connection.prepareStatement(Query);
preparedStatement.setInt(1 , MaxVoucher);
preparedStatement.setObject(2 , Current_Date );
preparedStatement.setString(3, jTextField1.getText());
preparedStatement.execute();
connection.commit();
//System.out.println(resultSet.isClosed());
JOptionPane.showMessageDialog(null, "Voucher Saved Sccessfully....");
MaxVoucher++;
jTextField1.setText("");
jTextField2.setText("");
jTextField3.setText("");
jTextField4.setText("");
jTextField5.setText("");
jTextField6.setText("");
//jTextField2.requestFocus();
jComboBox1.setSelectedIndex(0);
jComboBox2.setSelectedIndex(0);
dmodel.setNumRows(0);
row=0;
}catch(SQLException sskl){System.out.println(sskl.getMessage());}
} // else closes
// TODO add your handling code here:
}
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {
if(evt.getClickCount() == 2 && !evt.isConsumed())
{
evt.consume();
dmodel.removeRow(jTable1.getSelectedRow());
row--;
}
// TODO add your handling code here:
}
private void jTextField5FocusLost(java.awt.event.FocusEvent evt) {
if(jTextField2.getText().equals(""))
{
jTextField2.requestFocus();
}
else if (jTextField3.getText().equals(""))
{
jTextField3.requestFocus();
}
else if (jTextField4.getText().equals(""))
{
jTextField4.requestFocus();
}
else if (jTextField5.getText().equals(""))
{
jTextField5.requestFocus();
}
else if (jComboBox2.getSelectedIndex() == 0)
{
JOptionPane.showMessageDialog(null, "Please Select Debit / Credit");
jComboBox2.requestFocus();
}
else
{
dmodel.addRow(new Object[]{"","","",""});
jTable1.setValueAt(jTextField2.getText(), row, 0);
jTable1.setValueAt(jTextField3.getText(), row, 1);
jTable1.setValueAt(jComboBox2.getSelectedItem().toString(), row, 2);
jTable1.setValueAt(jTextField4.getText(), row, 3);
CalculateValues();
jComboBox2.setSelectedIndex(0);
jTextField2.setText("");
jTextField3.setText("");
jTextField4.setText("");
jTextField2.grabFocus();
row++;
}
// TODO add your handling code here:
}
private void jTextField2FocusLost(java.awt.event.FocusEvent evt) {
boolean cofound = false;
if( jTextField2.getText().length() >= 4)
{
COF = Integer.parseInt(jTextField2.getText());
try{
AccountChartSet.beforeFirst();
while(AccountChartSet.next())
{
if (COF == AccountChartSet.getInt(1))
{
jTextField3.setText(AccountChartSet.getString(2));
cofound = true;
break;
}
}
if( (COF < 1100) || (COF > 9999))
{
// System.out.println("I am here");
JOptionPane.showMessageDialog(jTextField2, "Invalid Chart of Acctount");
jTextField2.requestFocus();
}
}catch(Exception zsdf){ System.out.println(zsdf.getMessage());}
}
// TODO add your handling code here:
}
private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {
/* if(evt.getStateChange() == ItemEvent.SELECTED && jComboBox1.getSelectedIndex() > 0 )
{
CreateValues();
}
*/
CreateValues();
// TODO add your handling code here:
}
void CalculateValues()
{
Balance=0.0;
CREDIT =0.0;
DEBIT = 0.0;
if(jTable1.getRowCount() > 0)
{
for (int x = 0 ; x<jTable1.getRowCount(); x++)
{
if(jTable1.getValueAt(x, 2).toString().equals("Debit"))
{
DEBIT = DEBIT + Double.parseDouble(jTable1.getValueAt(x, 3).toString()) ;
}
else //(jTable1.getValueAt(x, 2).toString().equals("Crdit"))
{
CREDIT = CREDIT + Double.parseDouble(jTable1.getValueAt(x, 3).toString()) ;
}
}
Balance = DEBIT- CREDIT;
jTextField6.setText(Balance.toString());
} // outer if closes
}
void CreateValues()
{
if (jComboBox1.getSelectedIndex()> 0)
{
Current_Date = jDateChooser1.getDate();
DateVal = simpleformat.format(Current_Date);
//sqlDate = new java.sql.Date(Current_Date.getTime());
xToken = new StringTokenizer(jComboBox1.getSelectedItem().toString() , "-");
firstval = xToken.nextToken().trim();
secondVal= xToken.nextToken().trim();
CreatedVoucher = secondVal+"-"+DateVal+"-"+MaxVoucher.toString();
jTextField1.setText(CreatedVoucher);
}
}
void FetchCOF()
{
try{
Query = "select cof, cofname from accountchart ";
preparedStatement = connection.prepareStatement(Query, ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
AccountChartSet = preparedStatement.executeQuery();
Query = "select count(vcounter) from vouchercounter ";
preparedStatement = connection.prepareStatement(Query, ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
resultSet = preparedStatement.executeQuery();
resultSet.next();
MaxVoucher = resultSet.getInt(1);
MaxVoucher++;
// jTextField2.requestFocus();
}catch(SQLException sdfsda){}
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JComboBox<String> jComboBox1;
private javax.swing.JComboBox<String> jComboBox2;
private com.toedter.calendar.JDateChooser jDateChooser1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JList<String> jList1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable jTable1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
private javax.swing.JTextField jTextField4;
private javax.swing.JTextField jTextField5;
private javax.swing.JTextField jTextField6;
// End of variables declaration
}
I am having some trouble taking a screenshot. If you followed along with the tut, at: http://doc.babylonjs.com/tutorials/render_scene_on_a_png you see that they only provided one line which is BABYLON.Tools.CreateScreenshot(engine, camera, size);
With size and your camera being the variables that you can change. When I implemented this, I would get a black screenshot. I first thought that maybe the it was taking a screenshot before the page rendered so I added a simple loop to and added an alert box to wait until the scene loaded before the screenshot would execute. But for some reason I am still getting a black screenshot.
Thank you for your input :D
var canvas = document.querySelector("#renderCanvas");
var engine = new BABYLON.Engine(canvas, true);
//Needed for the CreateScene Function
var createScene = function () {
var scene = new BABYLON.Scene(engine);
// Setup camera
var camera = new BABYLON.ArcRotateCamera("Camera", 0, 10, 0, BABYLON.Vector3.Zero(), scene);
camera.setPosition(new BABYLON.Vector3(-10, 10, 25));
camera.attachControl(canvas, true);
// Lights
var light0 = new BABYLON.PointLight("Omni0", new BABYLON.Vector3(0, 10, 5), scene);
var light1 = new BABYLON.PointLight("Omni1", new BABYLON.Vector3(0, -10, 5), scene);
var light2 = new BABYLON.PointLight("Omni2", new BABYLON.Vector3(10, 0, 5), scene);
var light3 = new BABYLON.DirectionalLight("Dir0", new BABYLON.Vector3(1, -1, 2), scene);
var light4 = new BABYLON.SpotLight("Spot0", new BABYLON.Vector3(0, 5, -10), new BABYLON.Vector3(0, -1, 0), 0.8, 3, scene);
var light5 = new BABYLON.HemisphericLight("Hemi0", new BABYLON.Vector3(0, 1, 0), scene);
var material = new BABYLON.StandardMaterial("kosh", scene);
var sphere = BABYLON.Mesh.CreateSphere("Sphere", 16, 3, scene);
var cylinder = BABYLON.Mesh.CreateCylinder("cylinder", 7.5, 3, 6, 6, 1, scene);
var box = BABYLON.Mesh.CreateBox("box", 6.0, scene);
// Creating light sphere
var lightSphere0 = BABYLON.Mesh.CreateSphere("Sphere0", 16, .5, scene);
var lightSphere1 = BABYLON.Mesh.CreateSphere("Sphere1", 16, 0.5, scene);
var lightSphere2 = BABYLON.Mesh.CreateSphere("Sphere2", 16, 0.5, scene);
//Shifting position up of Sphere
sphere.position.y = 5;
box.position.y = -2;
//generating shadows
var shadowGenerator = new BABYLON.ShadowGenerator(1024, light3);
shadowGenerator.getShadowMap().renderList.push(box);
shadowGenerator.getShadowMap().renderList.push(sphere);
shadowGenerator.getShadowMap().renderList.push(cylinder);
//Colors
lightSphere0.material = new BABYLON.StandardMaterial("red", scene);
lightSphere0.material.diffuseColor = new BABYLON.Color3(0, 0, 0);
lightSphere0.material.specularColor = new BABYLON.Color3(0, 0, 0);
lightSphere0.material.emissiveColor = new BABYLON.Color3(1, 0, 0);
lightSphere1.material = new BABYLON.StandardMaterial("green", scene);
lightSphere1.material.diffuseColor = new BABYLON.Color3(0, 0, 0);
lightSphere1.material.specularColor = new BABYLON.Color3(0, 0, 0);
lightSphere1.material.emissiveColor = new BABYLON.Color3(0, 1, 0);
lightSphere2.material = new BABYLON.StandardMaterial("blue", scene);
lightSphere2.material.diffuseColor = new BABYLON.Color3(0, 0, 0);
lightSphere2.material.specularColor = new BABYLON.Color3(0, 0, 0);
lightSphere2.material.emissiveColor = new BABYLON.Color3(0, 0, 1);
// Sphere material
material.diffuseColor = new BABYLON.Color3(1, 1, 1);
sphere.material = material;
// Lights colors
light0.diffuse = new BABYLON.Color3(1, 0, 0);
light0.specular = new BABYLON.Color3(1, 0, 0);
light1.diffuse = new BABYLON.Color3(0, 1, 0);
light1.specular = new BABYLON.Color3(0, 1, 0);
light2.diffuse = new BABYLON.Color3(0, 0, 1);
light2.specular = new BABYLON.Color3(0, 0, 1);
light3.diffuse = new BABYLON.Color3(1, 1, 1);
light3.specular = new BABYLON.Color3(1, 1, 1);
light4.diffuse = new BABYLON.Color3(1, 0, 0);
light4.specular = new BABYLON.Color3(1, 1, 1);
light5.diffuse = new BABYLON.Color3(1, 1, 1);
light5.specular = new BABYLON.Color3(1, 1, 1);
light5.groundColor = new BABYLON.Color3(0, 0, 0);
//Adding the SkyBox
var skybox = BABYLON.Mesh.CreateBox("skyBox", 100.0, scene);
var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", scene);
skyboxMaterial.backFaceCulling = false;
skyboxMaterial.reflectionTexture = new BABYLON.CubeTexture("../textures/TropicalSunnyDay", scene);
skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
skyboxMaterial.diffuseColor = new BABYLON.Color3(0, 0, 0);
skyboxMaterial.specularColor = new BABYLON.Color3(0, 0, 0);
skyboxMaterial.disableLighting = true;
skybox.material = skyboxMaterial;
// Animations
var alpha = 0;
scene.beforeRender = function () {
light0.position = new BABYLON.Vector3(10 * Math.sin(alpha), 0, 10 * Math.cos(alpha));
light1.position = new BABYLON.Vector3(10 * Math.sin(alpha), 0, -10 * Math.cos(alpha));
light2.position = new BABYLON.Vector3(10 * Math.cos(alpha), 0, 10 * Math.sin(alpha));
lightSphere0.position = light0.position;
lightSphere1.position = light1.position;
lightSphere2.position = light2.position;
lightSphere0.position.y = 5;
lightSphere1.position.y = 5;
lightSphere2.position.y = 5;
alpha += 0.01;
};
//ground
var ground = BABYLON.Mesh.CreateGround("ground1", 100, 100, 2, scene);
ground.receiveShadows = true;
var materialGround = new BABYLON.StandardMaterial("grassTexture", scene);
materialGround.diffuseColor = new BABYLON.Color3(1,1,1);
materialGround.diffuseTexture = new
BABYLON.Texture("../textures/grass.png",scene);
ground.material = materialGround;
//wait loop for the screenshot
size = { width: 600, height: 400};
var i = 1;
function myLoop () {
setTimeout(function () {
alert('Taking Screenshot!');
//Creating png screenshot
BABYLON.Tools.CreateScreenshot(engine, camera, size);
i++;
if (i < 1) {
myLoop();
}
}, 2000)
}
myLoop();
//Returning the scene
return scene;
};
var scene = createScene();
engine.runRenderLoop(function () {
scene.render();
});
window.addEventListener("resize", function () {
engine.resize();
});
The cool fellow (DeltaKosh) over at htmlgameDevs helped me out. He said that when you are creating an engine for a Screenshot or rendering a PNG file that you must define it this way:
engine = new BABYLON.Engine(canvas, true, { preserveDrawingBuffer: true, stencil: true });
I also added a loop that waited a second until after the scene renders to take the screenshot
var scene = createScene();
var booleanR = false;
var size = 512;
engine.runRenderLoop(function () {
scene.render();
});
function myLoop () {
setTimeout(function () {
if(booleanR == false){
BABYLON.Tools.CreateScreenshot(engine, camera, size);
booleanR = true;
}
}, 1000)
}
This is the link from his response: http://www.html5gamedevs.com/topic/32765-getting-a-black-screenshot-with-babylonjs/?tab=comments#comment-187819
I am developing Microsoft Band2 Apps, I want to add Additional icons to my app tile in a band, like setting tile in Band2. I followed the below code to add Additional icons to the tile
Guid pageguid = Guid.NewGuid();
var panel = new ScrollFlowPanel
{
Rect = new PageRect(0, 0, 260, 128),
};
panel.Elements.Add(new FlowPanel
{
Rect = new PageRect(0, 0, 32, 32),
HorizontalAlignment = Microsoft.Band.Tiles.Pages.HorizontalAlignment.Center,
});
panel.Elements.Add(new Icon
{
HorizontalAlignment = Microsoft.Band.Tiles.Pages.HorizontalAlignment.Center,
Rect= new PageRect(0, 0, 32, 32),
ColorSource= ElementColorSource.BandHighlight,
});
var layout = new PageLayout(panel);
BandTile tile = new BandTile(tileGuid)
{
Name = "EmergencyHelp ",
TileIcon = await LoadIcon("ms-appx:///Assets/User that is member of security group.png"),
SmallIcon = await LoadIcon("ms-appx:///Assets/User that is member of security groupSmall.png"),
};
int firstIconIndex = tile.AdditionalIcons.Count + 2; // First 2 are used by the Tile itself
tile.AdditionalIcons.Add(await LoadIconMethod(AdjustUriMethod("ms-appx:///Assets/User that is member of security groupSmall.png")));
pageLayoutData.ById<IconData>(3).IconIndex = (ushort)(firstIconIndex + 0);
tile.PageLayouts.Add(layout);
if (tile.TileId != null)
{
await client.TileManager.RemoveTileAsync(tile.TileId);
}
await client.TileManager.AddTileAsync(tile);
await client.TileManager.SetPagesAsync(
tileGuid,
new PageData(pageguid, 0, new TextButtonData(1, "Emergency")));
I am getting the exception as shown in below figure,
please help to test this code using junit
#Override
public void start(Stage primaryStage) {
primaryStage.setTitle("JavaFX Welcome");
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(25, 25, 25, 25));
Text scenetitle = new Text("Welcome");
scenetitle.setFont(Font.font("Tahoma", FontWeight.NORMAL, 20));
grid.add(scenetitle, 0, 0, 2, 1);
Label userName = new Label("User Name:");
grid.add(userName, 0, 1);
TextField userTextField = new TextField();
grid.add(userTextField, 1, 1);
Label pw = new Label("Password:");
grid.add(pw, 0, 2);
PasswordField pwBox = new PasswordField();
grid.add(pwBox, 1, 2);
Label status = new Label();
status.setId( "status-label" );
Button btn = new Button("Sign in");
btn.setId("btn");
HBox hbBtn = new HBox(10);
hbBtn.setAlignment(Pos.BOTTOM_RIGHT);
hbBtn.getChildren().add(btn);
grid.add(hbBtn, 1, 4);
grid.add(status, 1, 8);
final Text actiontarget = new Text();
grid.add(actiontarget, 1, 6);
// ImageView imageView = new ImageView(new Image(getClass().getResourceAsStream("person.png"), 0, 65, true, true));
//grid.add(imageView, 0, 0,2,2);
//btn.setOnAction( ( e ) -> status.setText( computeStatus() ) );
//private String computeStatus() {
// return "Name: " + userTextField.getText() + ", Password: " + pwBox.getText();
//}
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
actiontarget.setFill(Color.CORNFLOWERBLUE);
actiontarget.setText("Name: " + userTextField.getText() + ", Password: " + pwBox.getText());
}
});
Scene scene = new Scene(grid, 300, 275);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
I keep getting the error "the function display() does not exist. I'm just trying to put my own image in instead of a pre drawn ellipse in processing. Here is my code:
import processing.serial.*;
import cc.arduino.*;
import com.tinkerkit.*;
Arduino arduino;
//declare the button
TKButton but;
TKButton but1;
{
arduino = new Arduino(this, Arduino.list()[2], 57600);
}
PFont myFont;
PImage ball1;
int pScore;
// don't touch em!
int gameState; //0= pre game 1= in game 2= game over
//setting up perimeter to contain ball character
int width = 600;
int height = 600;
void setup() {
size(width, height);
smooth();
//myFont = loadFont("MyFutura.vlw");
//textFont(myFont);
gameState = 0;
ball1 = loadImage("ball.gif");
pScore = 0;
}
{
but = new TKButton(arduino, TK.I0);
but1 = new TKButton(arduino, TK.I1);
}
void draw() {
background(0);
if (gameState==0) {
fill(255, 255, 255, 70);
rect(-10, 30, 370, 70, 7);
fill(255, 255, 255, 70);
rect(-10, 120, 330, 50, 7);
fill(255);
textSize(60);
text("Ball Game", 30, 85);
textSize(40);
text("Press B to Start", 30, 157);
if (keyPressed && key == 'b') {
gameState = 1;
}
}
if (gameState == 2) {
fill(255, 255, 255, 70);
rect(-10, 30, 370, 70, 7);
fill(255, 255, 255, 70);
rect(-10, 120, 250, 50, 7);
fill(255, 255, 255, 70);
rect(-10, 190, 330, 50, 7);
fill(255);
textSize(50);
text("Final Score:", 20, 85);
text(pScore, 280, 85);
textSize(30);
text("Play Again?", 30, 157);
textSize(30);
text("Press R to Restart", 30, 225);
if (keyPressed && key == 'r') {
gameState = 0;
setup();
}
}
ball1.display();
ball1.keyPressed();
}
void display() {
fill(255);
noStroke();
}
void reset() {
...
}
class ball1 {
float x;
float y;
float speed;
float r; //radius
color c = color(255, 20, 245);
ball1(float tempX, float tempY, float tempR) {
x = tempX;
y = tempY;
r = tempR;
speed = 0;
}
void change() {
c = color(random(255), random(220), random(245));
}
void display() {
fill (c);
noStroke();
ellipse(x, y, r, r);
}
//key commands
//ball flies off page in response to key command
void keyPressed() {
if (key == CODED) {
}
if (but.read ()== TK.HIGH) {
x = x+5;
if (x >= width - 25) {
x = width - 25;
}
println(but.read());
} else if (but1.read() == TK.HIGH) {
x = x-5;
if (x <= 25) {
x = 25;
}
println(but1.read());
}
}
}
Your ball1 variable is of type PImage.
The PImage class does not have a display() method.
Maybe your ball1 variable should be inside the ball1 class? If so, rename your class to something sane like Ball (in other words, follow the standard naming conventions and don't use the same name for a class and variable). Then rename your ball1 variable to something sane like ballImage. Then inside your Ball class's display() function, call image(ballImage, x, y) or one of the other image() functions.
Recommended reading:
https://processing.org/reference/PImage.html
https://processing.org/reference/image_.html