Итак, я пытаюсь создать монопольную веб-игру, используя asp.net.У меня были проблемы с сохранением переменных из-за обратной передачи, поэтому я создал базу данных, в которой хранится вся информация об игроках, квадратах и т. Д. Однако у меня сейчас проблема, по какой-то причине, текущий идентификатор игрока нехранится / извлекается правильно.Я прошу прощения за относительно длинную стену кода;
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);
}
}
}
Насколько я знаю, код базы данных, который у меня есть, работает нормально, так как я могу возобновить игру, и она установит позицию игрока как квадрат.они были раньше.Но по какой-то причине при запуске игры всегда ход игрока 2, и changeActivePlayer (), похоже, ничего не делает для этого.Я шаг за шагом перебирал код, и после нажатия кнопки EndTurnButton идентификатор игрока изменился, но когда пришло время получать значения из базы данных, он вернулся к идентификатору игрока 2.Я также не уверен, почему по умолчанию используется игрок 2, потому что, когда я вызываю функцию запуска игры, я устанавливаю текущего игрока на игроков [0], так что наверняка это должен быть игрок 1?Буду признателен за любую помощь в этом.