Public void int increment by 1 every loop (Beginner) - c#

I'd basically like to know how I can increase Player.SetPoints(); by 1 every time it loops. I got this in my class public void SetPoints(int p) { points = p; }, just thought that would be worth mentioning. So far the only way I've gotten this to work is to use Player.SetPoints(+1); but that only puts 1 to the scoreboard and never increases again. Sorry If I'm not clear enough, I'm very new to programming. This is a sample of my code so you might be able to understand it a bit more, I'm making a tic tac toe game as an assignment for school.
if (Btn1.Text != "" && Btn2.Text != "" && Btn3.Text != "")
{
if (Btn1.Text == Btn2.Text && Btn1.Text == Btn3.Text)
{
Btn1.BackColor = Color.Green;
Btn1.ForeColor = Color.White;
Btn2.BackColor = Color.Green;
Btn2.ForeColor = Color.White;
Btn3.BackColor = Color.Green;
Btn3.ForeColor = Color.White;
if (Btn1.Text == "X")
{
MessageBox.Show(lblpl1.Text + " Has Won!");
Player1.SetPoints(+0);
playerscore1.Text = Player1.GetPoints().ToString();
}
else
{
MessageBox.Show(lblpl2.Text + " Has Won!");
Player2.SetPoints(+0);
playerscore2.Text = Player2.GetPoints().ToString();
}
click1++;
click2++;
click3++;
click4++;
click5++;
click6++;
click7++;
click8++;
click9++;
restartbtn.Visible = true;
}
}

In order increase something in each button click you need to save the previous value in a variable. You are doing a similar think with clicks:
click1++;
Your method sets the points to a given value. If you give it 1 it sets it to 1. It looks like you don't want to set points to an individual value, you want to increase it each time, so instead of declaring a method like that you can change it to:
public void IncreasePoints()
{
points++;
}
And simply call it without passing any value.
Player1.IncreasePoints();

Related

How to choose the Nth picturebox

I am trying to make a memory game. I have 16 different pictureboxes(pbx1, pbx2...).
And now I am trying to make them revert to questionmarks after a wrong guess. This is what I've so far done:
void questionMarker(int lastBoxCLicked)
{
if(lastBoxClicked == 1)
{
pbx1.Image = Image.FromFile("../Bilder/Frågetecken.png");
}
else if(lastBoxClicked == 2)
{
pbx2.Image = Image.FromFile("../Bilder/Frågetecken.png");
}
else if (lastBoxClicked == 3)
{
pbx3.Image = Image.FromFile("../Bilder/Frågetecken.png");
}
else if (lastBoxClicked == 5)
{
pbx4.Image = Image.FromFile("../Bilder/Frågetecken.png");
}
}
But this becomes quite tedious and horrendous to look at as I have 16 pbx'es. Is there any way to write it like this?:
void questionMarker(int lastBoxClicked)
{
pbx[lastBoxClicked].Image = Image.FromFile("../Bilder/Frågetecken.png");
}
If I put this code in it just says that there is nothing named pbx.
Try this:
PictureBox[] PictureBoxArray = new PictureBox[3];
This creates an array of 3 picture boxes called PictureBoxArray.
You can loop through like an ordinary array or access certain picture boxes using PictureBoxArray[i]
Just use the "recurse" option of Controls.Find(). This will find the control "by name" no matter where or how deeply nested it is on the form:
Image questionMark = Image.FromFile("../Bilder/Frågetecken.png");
void questionMarker(int lastBoxCLicked)
{
PictureBox pb = this.Controls.Find("pbx" + lastBoxCLicked, true).FirstOrDefault() as PictureBox;
if (pb != null)
{
pb.Image = questionMark;
}
}

Take the full path waypoints of a railway

I'm developing a Train Valley game, just like 2D. The construction of the railway is different. I have a grid and I can take a rail and put it somewhere in the grid and so the railway is built. The main problem I am facing is that I do not know how to create the way for the train to follow .... each sine has a point, this point I add in a Vector3 type list, but if I jump over a cell and put there sine , then go back to the skipped cell and put the rail there, then the list will no longer be sorted.
I'm attaching code, but it's a lot. In general, if anyone has any idea how to build this path, the train will run correctly by all means.
void Start()
{
foreach (TrainCell cell in Grid)
cell.gameObject.AddComponent<TrainCellMouseEvent>().MouseEvent += OnCellClickEvent;
MouseEventProccessor.Instance.captureMouseMouveEvents = true;
StartCoroutine(SpawnStations());
}
private void OnCellClickEvent(TrainCell target, MouseEventType type)
{
if (type == MouseEventType.CLICK)
{
if (canDestroy)
{
if ((int)target.CurrentChildIndex != 0)
{
target.CurrentChild.GetComponent<PolygonCollider2D>().enabled = false;
target.setCurrentChildIndex(0);
Instantiate(BoomFX, target.transform.position, Quaternion.identity);
target.used = false;
WayPoints.Remove(target.transform.position);
if (BuildDone != null)
BuildDone(price, false);
}
foreach (TrainCell cell in Grid)
{
if (!cell.underBuilding)
{
if (cell.CurrentChildIndex == 0 && cell.used)
cell.used = false;
}
}
return;
}
if (rail.SelectedRail == null || target.used || outOfGridBounds)
return;
int railIndex = (int)rail.SelectedRail.GetComponent<ObjectSequence>().CurrentChildIndex;
target.setCurrentChildIndex(railIndex + 1);
target.CurrentChild.GetComponent<PolygonCollider2D>().enabled = true;
MouseEventProccessor.Instance.captureMouseMouveEvents = true;
SpriteRenderer render = target.CurrentChild.GetComponent<SpriteRenderer>();
render.color = Vector4.one;
target.used = true;
if (BuildDone != null)
BuildDone(price, true);
if (target.CurrentChild.transform.childCount == 0)
WayPoints.Add(target.transform.position);
else
{
for (int i = 0; i < target.CurrentChild.transform.childCount; i++)
WayPoints.Add(target.CurrentChild.transform.GetChild(i).transform.position);
}
}
else if (type == MouseEventType.OVER)
{
if (mainLevel.isHammer)
{
if (target.CurrentChildIndex != 0)
target.CurrentChild.GetComponent<SpriteRenderer>().color = Color.red;
return;
}
if (rail.SelectedRail == null || target.used)
return;
foreach (TrainCell cell in Grid)
{
if (cell.CurrentChildIndex != 0)
{
if (cell != target)
{
if (cell.CurrentChild.GetComponent<SpriteRenderer>().color != Color.white && !cell.used && !cell.underBuilding)
{
if (cell.GetComponentInChildren<ObjectSequenceNumberDisplay>() != null)
Destroy(GetComponentInChildren<ObjectSequenceNumberDisplay>().gameObject);
cell.setCurrentChildIndex(0);
}
}
}
}
int railIndex = (int)rail.SelectedRail.GetComponent<ObjectSequence>().CurrentChildIndex;
target.setCurrentChildIndex(railIndex + 1);
RenderColor(target);
}
else if (type == MouseEventType.EXIT)
{
if (target.CurrentChildIndex != 0)
target.CurrentChild.GetComponent<SpriteRenderer>().color = Color.white;
if (shapePrice != null)
Destroy(shapePrice.gameObject);
if (target.used)
return;
target.setCurrentChildIndex(0);
}
}
As far as I suppose based on your code I'll try to answer your question based on the following statements:
You have a station where you generate the train
You define a direction for the train to follow from the station (left, right, up, down) depending on the railway design
Having that statements I propose the following solution:
Create a method that takes the station point as the origin and the starting direction from that point. Having that you start following the railway, first on that direction and after that you search in 4 directions for more rails, adding all of them to the Vector3 array. This way you will have the array sorted.
Example:
private void SortedRailway(Vector2 origin, Vector2? direction = null, Vector2? lastDirection = null){
if(direction.HasValue){
if(origin + direction is TrainCell){
WayPoints.add(origin + direction);
SortedRailway(origin + direction, null, direction);
}
//(else will be used if direction (just used for the initial one) is wrong, so error there)
}else{
if(origin + Vector2.up is TrainCell && Vector2.up != lastDirection){
WayPoints.add(origin + Vector2.up);
SortedRailway(origin + Vector2.up, null, Vector2.down); //lastDirection is always the opposite to the matching one
}
//... (Repeat for all 4 directions. If none fits, then we asume is the end of the railway)
}
}
Hope this helps you!

How to check if player wins in tic-tac-toe game?

Hi,
Im working on Visual Studio Winforms and I'm trying to build tic-tac-toe.
I got stuck in the Check if player win method.
I have tried to do that in activated. little example:
private void StartForm_Activated(object sender, EventArgs e)
{
if ((_pcb1.Image == imagecircle) && (_pcb2.Image == imagecircle) && (_pcb3.Image == imagecircle))
{
MessageBox.Show("You Win!");
}
if ((_pcb4.Image == imagecircle) && (_pcb5.Image == imagecircle) && (_pcb6.Image == imagecircle))
{
MessageBox.Show("You Win!");
}
if ((_pcb7.Image == imagecircle) && (_pcb8.Image == imagecircle) && (_pcb9.Image == imagecircle))
{
MessageBox.Show("You Win!");
}
}
(I know that there are more situations to win).
It's never get into the method, I trying to find a method that active always when the form is open. please help :)
You should check player's victory after each move of that player. I assume, that your players make their moves by clicking on "Make a Move" button or clicking on the game field. Also I assume, that you have Click event of your button or game field. So you should paste your check code in Click event of your button or game field.
Here is some code that will extend to whatever game size:
public class Level
{
private readonly Team[,] _game;
public Level(int extent)
{
_game = new Team[extent, extent];
}
public bool HasWon(Team team)
{
var yMax = GetYMax();
var xMax = GetXMax();
var won = false;
// check horizontally
for (var y = 0; y < yMax; y++)
{
won = false;
for (var x = 0; x < xMax; x++)
won |= _game[y, x] == team;
if (won) return true;
}
// TODO check vertically
// TODO check diagonally
return won;
}
public void SetTile(Team team, int x, int y)
{
var xMax = GetXMax();
var yMax = GetYMax();
if ((x < 0) || (x > xMax))
throw new ArgumentOutOfRangeException("x");
if ((y < 0) || (y > yMax))
throw new ArgumentOutOfRangeException("y");
_game[y, x] = team;
}
private int GetXMax()
{
var xMax = _game.GetUpperBound(1);
return xMax;
}
private int GetYMax()
{
var yMax = _game.GetUpperBound(0);
return yMax;
}
}
public enum Team
{
Red,
Blue
}
Things for you to do:
implement logic for checking if a team has won vertically or diagonally
implement your game using this class, drawing pictures according the array _game (make it available publicly)
study the | OR operator to understand how it's used in here : https://msdn.microsoft.com/en-us/library/6373h346.aspx
further debug the code (I haven't :)
If you want to find some method that is constantly called, so as to check whether the players have won, you can just create a Timer that runs every 1 millisecond. Then the event handler for Timer.Tick would be such a method.
However, you shouldn't find such a method to check for winning/losing. It's a waste of resources to check for that every 1 millisecond.
Think, what action can affect the result of a game of tic tac toe? It's of course when either player places something (X or O) on the board! That is when you need to check whether someone has won. Also, if the thing placed is a X, you don't need to check whether the player who is playing O has won, because that's simply impossible!
Also, checking whether the image in a picture box is equal to the X or O image is really "non abstract" code. Try to put these things into a model by abstraction.

Dart Scoring Game Using C# Visual Studio 2010 - Alternating player score after evey 3rd score

Just bought a dartboard and thought to create a little scoring application, so far i have set up the player names and individual buttons to start the game. three games - 301, 501 and 1001, these are the targets scores to get to zero by throwing three darts each in turn by two players.
I have included many buttons for the score of each dart from 20 down to 1, each for single, double, triple, bull, outer bull and a no score button. Once the games starts the first three button presses should be attributed to player one then the following three buttons pressed to allocate the corresponding score to player 2. The games ends with the winning player achieving the target score (or whittles it down to zero).
I could have a player selection button to do this but was after some tips on a way of coding the alternate pattern of scoring to be automatic.
Any help greatly appreciated. Thank you
namespace dbstats
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
btnPlay.Visible = false;
btnReset.Visible = false;
btnUndo.Visible = false;
gbDartBoard.Visible = false;
gbScoreBoard.Visible = false;
lbP1Select.Visible = false;;
lbP2Select.Visible = false;
cmbP1.Visible = false;
cmbP2.Visible = false;
string[] lines = File.ReadAllLines(#"playerStats.csv");
foreach (var line in lines)
{
string[] names = line.Split(',');
if (names[0] != "NAME")
{
cmbP1.Items.Add(names[0]);
cmbP2.Items.Add(names[0]);
}
}
}
private void tsm301_Click(object sender, EventArgs e)
{
lbP1Select.Visible = true;
cmbP1.Visible = true;
lbP2Select.Visible = true;
cmbP2.Visible = true;
btnPlay.Visible = true;
tbPlayer1.Text = "301";
tbPlayer2.Text = "301";
gamesToolStripMenuItem.Visible = false;
manageToolStripMenuItem.Visible = false;
}
private void btnPlay_Click(object sender, EventArgs e)
{
if (cmbP1.SelectedItem == cmbP2.SelectedItem || cmbP1.SelectedItem == null || cmbP2.SelectedItem == null)
{
MessageBox.Show("Make Sure:" + "\n\n"
+ "The Players are NOT the same." + "\n"
+ "&" + "\n"
+ "At least one selection is NOT left blank", "Choose Again!");
}
else
{
lbP1Select.Visible = false;
cmbP1.Visible = false;
lbP2Select.Visible = false;
cmbP2.Visible = false;
btnPlay.Visible = false;
lbPlayer1.Text = cmbP1.SelectedItem.ToString();
lbPlayer2.Text = cmbP2.SelectedItem.ToString();
btnReset.Visible = true;
btnUndo.Visible = true;
gbDartBoard.Visible = true;
gbScoreBoard.Visible = true;
lbPlayer1.Visible = true; ;
lbPlayer2.Visible = true;
}
}
}
Keep a turnsEntered member variable to whatever class is managing turns/scoring.
// Call after every time a new score is entered. Start at 0.
turnsEntered++;
if (turnsEntered % 3 == 0)
{
SwitchPlayer(); // However you keep track of current player - switch here
}
After the 3rd score is entered it will switch players...after 3 more it will switch again, etc...
You can later check turnsEntered to determine when the game is over. Set it back to zero when you reinitialize for a new game.

Tic Tac Toe recursive algorithm

I can see this question (or a similar one) has been asked a few times and I've searched google a lot so that I can try to understand it however I am most definitely stuck.
My task is to use a recursive function that uses a "goodness" variable to determine which is the best move a computer can make, I even have a document that is meant to help with this but for the life of me, I just don't understand it.
If anyone could take some time to help me or break down what I actually need to do i'd be much appreciating, I'll link the code I have so far below but this is an assignment so guidance is preferable to direct answers. I've looked at the MinMax solution and that definitely seems above my grasp, I am very new to programming (especially in C# with only a few months experience) so go easy!
Here is the proposed solution I'm meant to be following:
http://erwnerve.tripod.com/prog/recursion/tictctoe.htm
public partial class Form1 : Form
{
public static string[,] Board = new string[3, 3] { { "1", "2", "3" }, { "4", "5", "6" }, { "7", "8", "9" } };
public bool Winner = false;
public string WinState;
private void Reset()
{
WinState = "";
Winner = false;
Board[0, 0] = "1";
Board[0, 1] = "2";
Board[0, 2] = "3";
Board[1, 0] = "4";
Board[1, 1] = "5";
Board[1, 2] = "6";
Board[2, 0] = "7";
Board[2, 1] = "8";
Board[2, 2] = "9";
btn1.Text = "";
btn2.Text = "";
btn3.Text = "";
btn4.Text = "";
btn5.Text = "";
btn6.Text = "";
btn7.Text = "";
btn8.Text = "";
btn9.Text = "";
}
private void checkWinner()
{
// Top Row
if (Board[0, 0].Equals(Board[0, 1]) && Board[0, 1].Equals(Board[0, 2]))
{
Winner = true;
WinState = Board[0, 0];
}
// Middle Row
if (Board[1, 0].Equals(Board[1, 1]) && Board[1, 1].Equals(Board[1, 2]))
{
Winner = true;
WinState = Board[1, 0];
}
// Bottom Row
if (Board[2, 0].Equals(Board[2, 1]) && Board[2, 1].Equals(Board[2, 2]))
{
Winner = true;
WinState = Board[2, 0];
}
// Left column
if (Board[0, 0].Equals(Board[1, 0]) && Board[1, 0].Equals(Board[2, 0]))
{
Winner = true;
WinState = Board[0, 0];
}
// Middle column
if (Board[0, 1].Equals(Board[1, 1]) && Board[1, 1].Equals(Board[2, 1]))
{
Winner = true;
WinState = Board[0, 1];
}
// Right column
if (Board[0, 2].Equals(Board[1, 2]) && Board[1, 2].Equals(Board[2, 2]))
{
Winner = true;
WinState = Board[0, 2];
}
// Diagonal 1
if (Board[0, 0].Equals(Board[1, 1]) && Board[1, 1].Equals(Board[2, 2]))
{
Winner = true;
WinState = Board[0, 0];
}
// Diagonal 2
if (Board[2, 0].Equals(Board[1, 1]) && Board[1, 1].Equals(Board[0, 2]))
{
Winner = true;
WinState = Board[2, 0];
}
if (Winner == true)
{
if (WinState == "X")
{
MessageBox.Show("Congratulations you win!");
Reset();
}
else if (WinState == "O")
{
MessageBox.Show("Sorry you lose!");
Reset();
}
}
}
private void btn1_Click(object sender, EventArgs e)
{
btn1.Text = "X";
Board[0, 0] = "X";
checkWinner();
}
private void btn2_Click(object sender, EventArgs e)
{
btn2.Text = "X";
Board[0, 1] = "X";
checkWinner();
}
private void btn3_Click(object sender, EventArgs e)
{
btn3.Text = "X";
Board[0, 2] = "X";
checkWinner();
}
private void btn4_Click(object sender, EventArgs e)
{
btn4.Text = "X";
Board[1, 0] = "X";
checkWinner();
}
private void btn5_Click(object sender, EventArgs e)
{
btn5.Text = "X";
Board[1, 1] = "X";
checkWinner();
}
private void btn6_Click(object sender, EventArgs e)
{
btn6.Text = "X";
Board[1, 2] = "X";
checkWinner();
}
private void btn7_Click(object sender, EventArgs e)
{
btn7.Text = "X";
Board[2, 0] = "X";
checkWinner();
}
private void btn8_Click(object sender, EventArgs e)
{
btn8.Text = "X";
Board[2, 1] = "X";
checkWinner();
}
private void btn9_Click(object sender, EventArgs e)
{
btn9.Text = "X";
Board[2, 2] = "X";
checkWinner();
}
}
Don't feel too bad about not understanding recursion as a result of reading that document. It doesn't do a very good job of explaining recursion. (It's a tough concept - I probably won't do that well either). Ultimately, what you have to do is try to make your program do what you would do. I'm going to try to explain it from that point of view.
Recursion is useful, because it lets us code (once) a step in a solution, and then repeat that step using as input the results that were just calculated. Try to look at your problem from your point of view, not some arbitrary goodness algorithm. You're probably trying too hard to understand the algorithm from the paper.
Try thinking like this: At the start of the game player 1 makes a play. Your program has to choose a move for Player 2. But player 2 has to think about the rest of the game (FOR EACH POSSIBLE MOVE).
Player 2 can choose from 8 possible moves.
Player 1 can choose from 7
Player 2 can choose from 6
Player 1 can choose from 5
Player 2 can choose from 4
Player 1 can choose from 3
Player 2 can choose from 2
Player 1 takes the last square.
You can re-word this into:
current player is 2, give a weight to all possible remaining choices for the current player.
current player is 1, give a weight to all possible remaining choices for the current player.
current player is 2, give a weight to all possible remaining choices for the current player.
current player is 1, give a weight to all possible remaining choices for the current player.
current player is 2, give a weight to all possible remaining choices for the current player.
current player is 1, give a weight to all possible remaining choices for the current player.
current player is 2, give a weight to all possible remaining choices for the current player.
current player is 1, give a weight to all possible remaining choices for the current player.
You can reword this into:
given current player,
switch player and give a weight to all possible choices for the current player.
Repeat until no more choices are possible
You can reword this into:
given current player,
switch player and CheckGoodness()
Repeat until no more choices are possible
So, back to your write-up. The author uses players of 1 & -1. Why? Because as you pass the moves deeper and deeper, you must swap players, and it's very easy to switch players as you go down levels like this (I'm only talking about player here:
public int CheckGoodness(bool playerID)
{
playerID = -playerID;
if (!endConditionMet)
{
goodness = CheckGoodness(playerID);
}
return goodness;
}
Along with the player, you have to pass something that represents the state of all possible moves remaining. The problem is that if you pass something that passes as a reference, any change you make will be reflected in your original data. Make sure that isn't happening. That is probably why #CodeInChaos suggested you clone.
Note that in recursion you have to make sure you ALWAYS have a way to end the call sequence. You must modify whatever your end condition is relying on. In this case, your number of possible moves is dropping. Otherwise you call forever and run out of memory.
EDIT: Explanation of board class added.
Think about it from the big picture. A class is a representation of a real world thing (e.g. an object). A thing has attributes that describe it. These are the class's data. A thing also does actions. These are the methods. Another definition of a class that I've heard is a class is data and operations on that data.
Think about what objects the game has. 2 players and a board. Not much else.
A player can move, and has a unique identifier (in this case either 'X' or 'O'), and can be either human or AI. I can't think of anything else (that matters) at the moment, but there are usually more things that could be there but don't really affect the program (like eye color). This is also where you could use inheritance. You have a player class with an abstract move method. A human class that inherits from player with an override move method that accepts input from the UI, a computer/AI class that inherits from player and overrides the move method by calculating the move with the goodness rating.
The board has data:
a 3 by 3 grid of possible play locations (This COULD be a collection of location objects too, by the way)
might need representation for players 1 & 2
The actions of the board COULD be:
accept a player's (Human or AI) move, records it if valid, determines win & returns an indicator of good move, bad move, game over or win
Could have a method to return winner of current game
Probably need a reset method
Could have a move history
You could have a static GoodNess class (might need a better name)
with no data but a single method (or this could be another method on the board class:
accept a board, calculate & return goodness array, or simply return best move
The AI could call the Goodness GetBestMove method before making a move.
The recursion would be isolated to that GetBestMove method.
Note that none of these are set in stone. Classes are defined by what you think should be in it. It's all based on how you percieve would be the best way to solve the problem. If you still have trouble, update your question with the code you've attempted to make work. It really helps to draw out diagrams as you start to lay out your code.
Good luck, hope this helps, and I'll try to do a better job of monitoring StackOverflow notifications.

Categories