After googling it, I think it is a memory leak but I do not know how to fix this.
Assertion failed: TLS Allocator ALLOC_TEMP_THREAD, underlying allocator ALLOC_TEMP_THREAD has unfreed allocations, size 1528
Im Using Unity 2018.1.0.0f2.
Here is the script that causes the error (Sorry for my awful code organization skills, new to world generation)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WorldGeneration : MonoBehaviour {
public float GenerationDelay;
public float RoomPicker;
public float LevelNumber;
public float RoomCount;
public float MaxRoomCount;
public float LevelSample1Rooms;
public float MaxLevelSample1Rooms;
public float LevelSample2Rooms;
public float MaxLevelSample2Rooms;
public float LevelSample3Rooms;
public float MaxLevelSample3Rooms;
public float LevelSample4Rooms;
public float MaxLevelSample4Rooms;
public float LevelSample5Rooms;
public float MaxLevelSample5Rooms;
public GameObject LevelSample1;
public GameObject LevelSample2;
public GameObject LevelSample3;
public GameObject LevelSample4;
public GameObject LevelSample5;
public Transform SpawnLevelPoint;
public Transform SpawnLevelPoint1;
public bool Leveloadedatpoint1;
public Transform SpawnLevelPoint2;
public bool Leveloadedatpoint2;
public Transform SpawnLevelPoint3;
public bool Leveloadedatpoint3;
public Transform SpawnLevelPoint4;
public bool Leveloadedatpoint4;
public Transform SpawnLevelPoint5;
public bool Leveloadedatpoint5;
public Transform SpawnLevelPoint6;
public bool Leveloadedatpoint6;
void Start()
{
StartCoroutine("Createpoint1room");
}
public IEnumerator Createpoint1room()
{
if (Leveloadedatpoint1 == false)
{
RoomPicker = Random.Range(1, 20);
yield return new WaitForSeconds(GenerationDelay);
if (RoomPicker == 1 || RoomPicker == 2 || RoomPicker == 3 || RoomPicker == 4 || RoomPicker == 5)
{
if (Leveloadedatpoint1 == false)
{
if (LevelSample1Rooms < MaxLevelSample1Rooms)
{
LevelSample1Rooms += 1;
Instantiate(LevelSample1, SpawnLevelPoint1.transform.position, Quaternion.identity);
Leveloadedatpoint1 = true;
yield return new WaitForSeconds(GenerationDelay);
StartCoroutine("Createpoint2room");
}
else
{
StartCoroutine("Createpoint1room");
}
}
else
{
StartCoroutine("Createpoint1room");
}
}
if (RoomPicker == 6 || RoomPicker == 7 || RoomPicker == 8)
{
if (Leveloadedatpoint1 == false)
{
if (LevelSample2Rooms < MaxLevelSample2Rooms)
{
LevelSample2Rooms += 1;
Instantiate(LevelSample2, SpawnLevelPoint1.transform.position, Quaternion.identity);
Leveloadedatpoint1 = true;
yield return new WaitForSeconds(GenerationDelay);
StartCoroutine("Createpoint2room");
}
else
{
StartCoroutine("Createpoint1room");
}
}
else
{
StartCoroutine("Createpoint1room");
}
}
if (RoomPicker == 9 || RoomPicker == 10 || RoomPicker == 11)
{
if (Leveloadedatpoint1 == false)
{
if (LevelSample3Rooms < MaxLevelSample3Rooms)
{
LevelSample3Rooms += 1;
Instantiate(LevelSample3, SpawnLevelPoint1.transform.position, Quaternion.identity);
Leveloadedatpoint1 = true;
yield return new WaitForSeconds(GenerationDelay);
StartCoroutine("Createpoint2room");
}
else
{
StartCoroutine("Createpoint1room");
}
}
else
{
StartCoroutine("Createpoint1room");
}
}
if (RoomPicker == 12 || RoomPicker == 13 || RoomPicker == 14)
{
if (Leveloadedatpoint1 == false)
{
if (LevelSample4Rooms < MaxLevelSample4Rooms)
{
LevelSample4Rooms += 1;
Instantiate(LevelSample4, SpawnLevelPoint1.transform.position, Quaternion.identity);
Leveloadedatpoint1 = true;
yield return new WaitForSeconds(GenerationDelay);
StartCoroutine("Createpoint2room");
}
else
{
StartCoroutine("Createpoint1room");
}
}
else
{
StartCoroutine("Createpoint1room");
}
}
if (RoomPicker == 15 || RoomPicker == 16 || RoomPicker == 17)
{
if (Leveloadedatpoint1 == false)
{
if (LevelSample5Rooms < MaxLevelSample5Rooms)
{
LevelSample5Rooms += 1;
Instantiate(LevelSample5, SpawnLevelPoint1.transform.position, Quaternion.identity);
Leveloadedatpoint1 = true;
yield return new WaitForSeconds(GenerationDelay);
StartCoroutine("Createpoint2room");
}
else
{
StartCoroutine("Createpoint1room");
}
}
else
{
StartCoroutine("Createpoint1room");
}
}
if (RoomPicker == 18 || RoomPicker == 19 || RoomPicker == 20)
{
StartCoroutine("Createpoint1room");
}
Debug.Log("Point 1: The number is " + RoomPicker);
}
else
{
StartCoroutine("Createpoint2room");
}
}
public IEnumerator Createpoint2room()
{
if (Leveloadedatpoint2 == false)
{
RoomPicker = Random.Range(1, 20);
yield return new WaitForSeconds(GenerationDelay);
if (RoomPicker == 1 || RoomPicker == 2 || RoomPicker == 3 || RoomPicker == 4 || RoomPicker == 5)
{
if (Leveloadedatpoint2 == false)
{
if (LevelSample1Rooms < MaxLevelSample1Rooms)
{
LevelSample1Rooms += 1;
Instantiate(LevelSample1, SpawnLevelPoint2.transform.position, Quaternion.identity);
Leveloadedatpoint2 = true;
yield return new WaitForSeconds(GenerationDelay);
StartCoroutine("Createpoint3room");
}
else
{
StartCoroutine("Createpoint2room");
}
}
else
{
StartCoroutine("Createpoint2room");
}
}
if (RoomPicker == 6 || RoomPicker == 7 || RoomPicker == 8)
{
if (Leveloadedatpoint2 == false)
{
if (LevelSample2Rooms < MaxLevelSample2Rooms)
{
LevelSample2Rooms += 1;
Instantiate(LevelSample2, SpawnLevelPoint2.transform.position, Quaternion.identity);
Leveloadedatpoint2 = true;
yield return new WaitForSeconds(GenerationDelay);
StartCoroutine("Createpoint3room");
}
else
{
StartCoroutine("Createpoint2room");
}
}
else
{
StartCoroutine("Createpoint2room");
}
}
if (RoomPicker == 9 || RoomPicker == 10 || RoomPicker == 11)
{
if (Leveloadedatpoint2 == false)
{
if (LevelSample3Rooms < MaxLevelSample3Rooms)
{
LevelSample3Rooms += 1;
Instantiate(LevelSample3, SpawnLevelPoint2.transform.position, Quaternion.identity);
Leveloadedatpoint2 = true;
yield return new WaitForSeconds(GenerationDelay);
StartCoroutine("Createpoint3room");
}
else
{
StartCoroutine("Createpoint2room");
}
}
else
{
StartCoroutine("Createpoint2room");
}
}
if (RoomPicker == 12 || RoomPicker == 13 || RoomPicker == 14)
{
if (Leveloadedatpoint2 == false)
{
if (LevelSample4Rooms < MaxLevelSample4Rooms)
{
LevelSample4Rooms += 1;
Instantiate(LevelSample4, SpawnLevelPoint2.transform.position, Quaternion.identity);
Leveloadedatpoint2 = true;
yield return new WaitForSeconds(GenerationDelay);
StartCoroutine("Createpoint3room");
}
else
{
StartCoroutine("Createpoint2room");
}
}
else
{
StartCoroutine("Createpoint2room");
}
}
if (RoomPicker == 15 || RoomPicker == 16 || RoomPicker == 17)
{
if (Leveloadedatpoint2 == false)
{
if (LevelSample5Rooms < MaxLevelSample5Rooms)
{
LevelSample5Rooms += 1;
Instantiate(LevelSample5, SpawnLevelPoint2.transform.position, Quaternion.identity);
Leveloadedatpoint2 = true;
yield return new WaitForSeconds(GenerationDelay);
StartCoroutine("Createpoint3room");
}
else
{
StartCoroutine("Createpoint2room");
}
}
else
{
StartCoroutine("Createpoint2room");
}
}
if (RoomPicker == 18 || RoomPicker == 19 || RoomPicker == 20)
{
StartCoroutine("Createpoint2room");
}
Debug.Log("Point 2: The number is " + RoomPicker);
}
else
{
StartCoroutine("Createpoint3room");
}
}
public IEnumerator Createpoint3room()
{
if (Leveloadedatpoint3 == false)
{
RoomPicker = Random.Range(1, 20);
yield return new WaitForSeconds(GenerationDelay);
if (RoomPicker == 1 || RoomPicker == 2 || RoomPicker == 3 || RoomPicker == 4 || RoomPicker == 5)
{
if (Leveloadedatpoint3 == false)
{
if (LevelSample1Rooms < MaxLevelSample1Rooms)
{
LevelSample1Rooms += 1;
Instantiate(LevelSample1, SpawnLevelPoint3.transform.position, Quaternion.identity);
Leveloadedatpoint3 = true;
yield return new WaitForSeconds(GenerationDelay);
StartCoroutine("Createpoint4room");
}
else
{
StartCoroutine("Createpoint3room");
}
}
else
{
StartCoroutine("Createpoint3room");
}
}
if (RoomPicker == 6 || RoomPicker == 7 || RoomPicker == 8)
{
if (Leveloadedatpoint3 == false)
{
if (LevelSample2Rooms < MaxLevelSample2Rooms)
{
LevelSample2Rooms += 1;
Instantiate(LevelSample2, SpawnLevelPoint3.transform.position, Quaternion.identity);
Leveloadedatpoint3 = true;
yield return new WaitForSeconds(GenerationDelay);
StartCoroutine("Createpoint4room");
}
else
{
StartCoroutine("Createpoint3room");
}
}
else
{
StartCoroutine("Createpoint3room");
}
}
if (RoomPicker == 9 || RoomPicker == 10 || RoomPicker == 11)
{
if (Leveloadedatpoint3 == false)
{
if (LevelSample3Rooms < MaxLevelSample3Rooms)
{
LevelSample3Rooms += 1;
Instantiate(LevelSample3, SpawnLevelPoint3.transform.position, Quaternion.identity);
Leveloadedatpoint3 = true;
yield return new WaitForSeconds(GenerationDelay);
StartCoroutine("Createpoint4room");
}
else
{
StartCoroutine("Createpoint3room");
}
}
else
{
StartCoroutine("Createpoint3room");
}
}
if (RoomPicker == 12 || RoomPicker == 13 || RoomPicker == 14)
{
if (Leveloadedatpoint3 == false)
{
if (LevelSample4Rooms < MaxLevelSample4Rooms)
{
LevelSample4Rooms += 1;
Instantiate(LevelSample4, SpawnLevelPoint3.transform.position, Quaternion.identity);
Leveloadedatpoint3 = true;
yield return new WaitForSeconds(GenerationDelay);
StartCoroutine("Createpoint4room");
}
else
{
StartCoroutine("Createpoint3room");
}
}
else
{
StartCoroutine("Createpoint3room");
}
}
if (RoomPicker == 15 || RoomPicker == 16 || RoomPicker == 17)
{
if (Leveloadedatpoint3 == false)
{
if (LevelSample5Rooms < MaxLevelSample5Rooms)
{
LevelSample5Rooms += 1;
Instantiate(LevelSample5, SpawnLevelPoint3.transform.position, Quaternion.identity);
Leveloadedatpoint3 = true;
yield return new WaitForSeconds(GenerationDelay);
StartCoroutine("Createpoint4room");
}
else
{
StartCoroutine("Createpoint3room");
}
}
else
{
StartCoroutine("Createpoint3room");
}
}
if (RoomPicker == 18 || RoomPicker == 19 || RoomPicker == 20)
{
StartCoroutine("Createpoint3room");
}
Debug.Log("Point 3: The number is " + RoomPicker);
}
else
{
StartCoroutine("Createpoint4room");
}
}
public IEnumerator Createpoint4room()
{
if (Leveloadedatpoint4 == false)
{
RoomPicker = Random.Range(1, 20);
yield return new WaitForSeconds(GenerationDelay);
if (RoomPicker == 1 || RoomPicker == 2 || RoomPicker == 3 || RoomPicker == 4 || RoomPicker == 5)
{
if (Leveloadedatpoint4 == false)
{
if (LevelSample1Rooms < MaxLevelSample1Rooms)
{
LevelSample1Rooms += 1;
Instantiate(LevelSample1, SpawnLevelPoint4.transform.position, Quaternion.identity);
Leveloadedatpoint4 = true;
yield return new WaitForSeconds(GenerationDelay);
StartCoroutine("Createpoint5room");
}
else
{
StartCoroutine("Createpoint4room");
}
}
else
{
StartCoroutine("Createpoint4room");
}
}
if (RoomPicker == 6 || RoomPicker == 7 || RoomPicker == 8)
{
if (Leveloadedatpoint4 == false)
{
if (LevelSample2Rooms < MaxLevelSample2Rooms)
{
LevelSample2Rooms += 1;
Instantiate(LevelSample2, SpawnLevelPoint4.transform.position, Quaternion.identity);
Leveloadedatpoint4 = true;
yield return new WaitForSeconds(GenerationDelay);
StartCoroutine("Createpoint5room");
}
else
{
StartCoroutine("Createpoint4room");
}
}
else
{
StartCoroutine("Createpoint4room");
}
}
if (RoomPicker == 9 || RoomPicker == 10 || RoomPicker == 11)
{
if (Leveloadedatpoint4 == false)
{
if (LevelSample3Rooms < MaxLevelSample3Rooms)
{
LevelSample3Rooms += 1;
Instantiate(LevelSample3, SpawnLevelPoint4.transform.position, Quaternion.identity);
Leveloadedatpoint4 = true;
yield return new WaitForSeconds(GenerationDelay);
StartCoroutine("Createpoint5room");
}
else
{
StartCoroutine("Createpoint4room");
}
}
else
{
StartCoroutine("Createpoint4room");
}
}
if (RoomPicker == 12 || RoomPicker == 13 || RoomPicker == 14)
{
if (Leveloadedatpoint4 == false)
{
if (LevelSample4Rooms < MaxLevelSample4Rooms)
{
LevelSample4Rooms += 1;
Instantiate(LevelSample4, SpawnLevelPoint4.transform.position, Quaternion.identity);
Leveloadedatpoint3 = true;
yield return new WaitForSeconds(GenerationDelay);
StartCoroutine("Createpoint4room");
}
else
{
StartCoroutine("Createpoint4room");
}
}
else
{
StartCoroutine("Createpoint4room");
}
}
if (RoomPicker == 15 || RoomPicker == 16 || RoomPicker == 17)
{
if (Leveloadedatpoint3 == false)
{
if (LevelSample5Rooms < MaxLevelSample5Rooms)
{
LevelSample5Rooms += 1;
Instantiate(LevelSample5, SpawnLevelPoint4.transform.position, Quaternion.identity);
Leveloadedatpoint3 = true;
yield return new WaitForSeconds(GenerationDelay);
StartCoroutine("Createpoint5room");
}
else
{
StartCoroutine("Createpoint4room");
}
}
else
{
StartCoroutine("Createpoint4room");
}
}
if (RoomPicker == 18 || RoomPicker == 19 || RoomPicker == 20)
{
StartCoroutine("Createpoint4room");
}
Debug.Log("Point 4: The number is " + RoomPicker);
}
else
{
StartCoroutine("Createpoint4room");
}
}
public IEnumerator Createpoint5room()
{
yield return new WaitForSeconds(GenerationDelay);
Debug.Log("Generation finished");
}
}
Edit1:
This error also seems to crash my Editor and crashes the build of the game as well.
I was getting tons of Stack allocator ALLOC_TEMP_THREAD has unfreed allocations, size ... messages. Which is almost, but not exactly the same message you're getting, but that might be because of the different Unity version (I'm on 2018.2.9).
But as described here, simply restarting Unity fixed it for me.
The real solution is really simple and doesn't require the restart of Unity. Just go to preferences and under GI tab, hit Clean Cache button. No more errors for you !-)
I had the same issue in Unity 2021, I tried the Clean Cache method and restarted Unity. The memory error was gone but some new warnings about missing referenced script showed up.
Related
I have tried to program a tic tac toe game in C# (with the help of tutorials). Overall it seems to be working fine (although the amount of code seems very excessive so sorry for that) but there appears to be one problem: Say, player 1 decides on row 1, column 1 and player 2 does the same afterwards, then player 2 overwrites player 1.
So far, this is the code:
namespace TicTacToe
{
class Program
{
static int turns = 1;
static char[] board =
{
' ',' ',' ',' ',' ',' ',' ',' ',' '
};
static char playerSignature = 'X';
private static void Introduction()
{
Console.WriteLine("This is a simple TicTacToe game. Enter y if you have played before and n if you are new to this.");
string input1 = Console.ReadLine();
Console.Clear();
if (input1 == "n")
{
Console.WriteLine("TicTacToeRules:");
Console.WriteLine("1. The game is played on a grid that's 3 squares by 3 squares.");
Console.WriteLine("2. You are X, your friend is O. Players take turns putting their marks in empty squares.");
Console.WriteLine("3. The first player to get 3 of her marks in a row (up, down, across, or diagonally) is the winner.");
Console.WriteLine("4. When all 9 squares are full, the game is over.");
Console.WriteLine("If you have read the rules, press any key to continue.");
Console.ReadKey();
Console.Clear();
DrawBoard(board);
}
else
{
Console.WriteLine("Alright, let's get started, you are X, your friend is O.");
DrawBoard(board);
}
}
private static void PlayAgain()
{
Console.WriteLine("Play again? y/n");
string playagain = Console.ReadLine();
switch (playagain)
{
case "n":
Console.WriteLine("Thanks for playing!");
Console.Clear();
break;
case "y":
Console.Clear();
ResetBoard();
break;
}
}
private static void DrawBoard(char[] board)
{
string row = "| {0} | {1} | {2} |";
string sep = "|___|___|___|";
Console.WriteLine(" ___ ___ ___ ");
Console.WriteLine(row, board[0], board[1], board[2]);
Console.WriteLine(sep);
Console.WriteLine(row, board[3], board[4], board[5]);
Console.WriteLine(sep);
Console.WriteLine(row, board[6], board[7], board[8]);
Console.WriteLine(sep);
}
private static void ResetBoard()
{
char[] newBoard =
{
' ',' ',' ',' ',' ',' ',' ',' ',' '
};
board = newBoard;
DrawBoard(board);
turns = 0;
}
private static void Draw()
{
Console.WriteLine("It's a draw!\n" +
"Press any key to play again.");
Console.ReadKey();
ResetBoard();
//DrawBoard(board);
}
public static void Main()
{
Introduction();
while(true)
{
bool isrow = false;
bool iscol = false;
int row = 0;
int col = 0;
while (!isrow)
{
Console.WriteLine("Choose a row (1-3): ");
try
{
row = Convert.ToInt32(Console.ReadLine());
}
catch
{
Console.WriteLine("Please enter a number between 1 and 3.");
}
if (row == 1 || row == 2 || row == 3)
{
isrow = true;
}
else
{
Console.WriteLine("\nInvalid row!");
}
}
while (!iscol)
{
Console.WriteLine("Choose a column (1-3): ");
try
{
col = Convert.ToInt32(Console.ReadLine());
}
catch
{
Console.WriteLine("Please enter a number between 1 and 3.");
}
if (col == 1 || col == 2 || col == 3)
{
iscol = true;
}
else
{
Console.WriteLine("\nInvalid column!");
}
}
int[] input = { row, col };
int player = 2;
if (player == 2)
{
player = 1;
XorO(player, input);
}
else
{
player = 2;
XorO(player, input);
}
DrawBoard(board);
turns++;
CheckForDiagonal();
CheckForVertical();
CheckForHorizontal();
if (turns == 10 && (board[0] == playerSignature && board[1] == playerSignature && board[2] == playerSignature && board[3] == playerSignature &&
board[4] == playerSignature && board[5] == playerSignature && board[6] == playerSignature && board[7] == playerSignature && board[8] == playerSignature))
{
Draw();
}
}
}
private static void CheckForVertical()
{
char[] PlayerSignature = { 'O', 'X' };
foreach (char Signature in PlayerSignature)
{
if (board[0] == playerSignature && board[3] == playerSignature && board[6] == playerSignature ||
board[1] == playerSignature && board[4] == playerSignature && board[7] == playerSignature ||
board[2] == playerSignature && board[5] == playerSignature && board[8] == playerSignature)
{
if (playerSignature == 'X')
{
Console.WriteLine("Congratulations Player 1, that's a vertical win!\n" +
"Play again (y/n)?");
string playagain = Console.ReadLine();
if (playagain == "y")
{
Console.Clear();
ResetBoard();
turns = 0;
}
else
{
Console.Clear();
}
}
else
{
Console.WriteLine("Congratulations Player 2, that's a vertical win!\n" +
"Play again (y/n)?");
string playagain = Console.ReadLine();
if (playagain == "y")
{
Console.Clear();
ResetBoard();
turns = 0;
}
else
{
Console.Clear();
}
}
}
}
}
private static void CheckForHorizontal()
{
char[] PlayerSignature = { 'O', 'X' };
foreach (char Signature in PlayerSignature)
{
if (board[0] == playerSignature && board[1] == playerSignature && board[2] == playerSignature ||
board[3] == playerSignature && board[4] == playerSignature && board[5] == playerSignature ||
board[6] == playerSignature && board[7] == playerSignature && board[8] == playerSignature)
{
if (playerSignature == 'X')
{
Console.WriteLine("Congratulations Player 1, that's a horizontal win!\n" +
"Play again (y/n)?");
string playagain = Console.ReadLine();
if (playagain == "y")
{
Console.Clear();
ResetBoard();
turns = 0;
}
else
{
Console.Clear();
}
}
else
{
Console.WriteLine("Congratulations Player 2, that's a horizontal win!\n" +
"Play again (y/n)?");
string playagain = Console.ReadLine();
if (playagain == "y")
{
Console.Clear();
ResetBoard();
turns = 0;
}
else
{
Console.Clear();
}
}
}
}
}
private static void CheckForDiagonal()
{
char[] PlayerSignature = { 'O', 'X' };
foreach (char Signature in PlayerSignature)
{
if (board[6] == playerSignature && board[4] == playerSignature && board[2] == playerSignature ||
board[0] == playerSignature && board[4] == playerSignature && board[8] == playerSignature)
{
if (playerSignature == 'X')
{
Console.WriteLine("Congratulations Player 1, that's a diagonal win!\n" +
"Play again (y/n)?");
string playagain = Console.ReadLine();
if (playagain == "y")
{
Console.Clear();
ResetBoard();
turns = 0;
}
else
{
Console.Clear();
}
}
else
{
Console.WriteLine("Congratulations Player 2, that's a diagonal win!\n" +
"Play again (y/n)?");
string playagain = Console.ReadLine();
if (playagain == "y")
{
Console.Clear();
ResetBoard();
turns = 0;
}
else
{
Console.Clear();
}
}
}
}
}
private static void XorO(int player, int[] input)
{
if (player == 1)
{
playerSignature = 'X';
}
else if (player == 2)
{
playerSignature = 'O';
}
if (input[0] == 1 && input[1] == 1)
{
board[0] = playerSignature;
}
else if (input[0] == 1 && input[1] == 2)
{
board[1] = playerSignature;
}
else if (input[0] == 1 && input[1] == 3)
{
board[2] = playerSignature;
}
else if (input[0] == 2 && input[1] == 1)
{
board[3] = playerSignature;
}
else if (input[0] == 2 && input[1] == 2)
{
board[4] = playerSignature;
}
else if (input[0] == 2 && input[1] == 3)
{
board[5] = playerSignature;
}
else if (input[0] == 3 && input[1] == 1)
{
board[6] = playerSignature;
}
else if (input[0] == 3 && input[1] == 2)
{
board[7] = playerSignature;
}
else if (input[0] == 3 && input[1] == 3)
{
board[8] = playerSignature;
}
}
}
}
I have tried adding something like this: if(input[0] == 1 && input[1] == 1 && (board[0] != 'X' && board[0] != 'O') in the XorO method. But that didn't solve my issue.
Does somebody maybe have some suggestions as to how I can fix that?
You are doing way too much work in some of those methods...
For instance, here's a shorter XorO() method that also makes sure the spot is BLANK before assigning it to a player:
private static void XorO(int player, int[] input)
{
playerSignature = (player == 1) ? 'X' : 'O';
int index = ((input[0] - 1) * 3) + (input[1] - 1);
if (board[index] == ' ') {
board[index] = playerSignature;
}
else {
// ... output an error message? ...
Console.WriteLine("That spot is already taken!");
}
}
Could you maybe explain why you set index the way you did?
Sure! Here is the layout of the board, 3 rows with 3 cols, and the corresponding Index value of each position:
1 2 3
1 0 1 2
2 3 4 5
3 6 7 8
Note that because there are 3 columns, the value of the Index as we move down from one row to the next in the same column goes up by 3. Also note that the starting values in column 1 for each row are 0, 3, and 6, which are all multiples of 3. So to convert your row value from 1, 2, and 3 into 0, 3, and 6, we first subtract 1 from the row value and then multiply it by 3.
Next, each column simply increments by one as you move to the right. Thus we subtract one from the column value and add that to the computed beginning row value. This maps the (row, col) to the indices 0 through 8, seen here as a single dimension array:
1,1 | 1,2 | 1,3 | 2,1 | 2,2 | 2,3 | 3,1 | 3,2 | 3,3
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8
But how was am I supposed to think of something like that? I would
never have thought of that.
It's a fairly common setup to represent a 2D structure in a single dimensional array, known as a compact layout. The math involved to convert a row/column to the equivalent index value or vice-versa is just something that all programmers learn at some point.
Lot of refactoring here, look closely:
class Program
{
static int turns;
static char[] board;
static bool playerOne;
public static void Main(string[] args)
{
Introduction();
bool playAgain = true;
while (playAgain)
{
ResetBoard();
bool gameOver = false;
while (!gameOver)
{
DrawBoard(board);
int row = getNumber(true);
int col = getNumber(false);
if (XorO(row, col)) {
turns++; // valid move was made
String msg = "";
String playerNumber = playerOne ? "1" : "2";
if (CheckForDiagonal())
{
gameOver = true;
msg = "Congratulations Player " + playerNumber + ", that's a diagonal win!";
}
else if (CheckForVertical())
{
gameOver = true;
msg = "Congratulations Player " + playerNumber + ", that's a vertical win!";
}
else if (CheckForHorizontal())
{
gameOver = true;
msg = "Congratulations Player " + playerNumber + ", that's a horizontal win!";
}
else if (turns == 9)
{
gameOver = true;
msg = "It's a draw!";
}
else
{
playerOne = !playerOne;
}
if (gameOver)
{
DrawBoard(board); // show last move
Console.WriteLine(msg);
}
}
}
Console.WriteLine("Play again (y/n)?");
string response = Console.ReadLine().ToLower();
playAgain = (response == "y");
}
}
private static void ResetBoard()
{
turns = 0;
playerOne = true;
board = new char[] {
' ',' ',' ',' ',' ',' ',' ',' ',' '
};
}
private static void Introduction()
{
Console.WriteLine("This is a simple TicTacToe game.\nEnter y if you have played before and n if you are new to this.");
string input1 = Console.ReadLine().ToLower();
Console.Clear();
if (input1 == "n")
{
Console.WriteLine("TicTacToeRules:");
Console.WriteLine("1. The game is played on a grid that's 3 squares by 3 squares.");
Console.WriteLine("2. You are X, your friend is O. Players take turns putting their marks in empty squares.");
Console.WriteLine("3. The first player to get 3 of her marks in a row (up, down, across, or diagonally) is the winner.");
Console.WriteLine("4. When all 9 squares are full, the game is over.");
Console.WriteLine("If you have read the rules, press any key to continue.");
Console.ReadKey();
Console.Clear();
}
else
{
Console.WriteLine("Alright, let's get started, you are X, your friend is O.");
}
}
private static void DrawBoard(char[] board)
{
Console.WriteLine(" ___ ___ ___ ");
for(int r=1; r<=3;r++)
{
Console.Write("|");
for(int c=1; c<=3; c++)
{
Console.Write(" {0} |", board[(r - 1) * 3 + (c - 1)]);
}
Console.WriteLine();
Console.WriteLine("|___|___|___|");
}
}
private static int getNumber(bool row)
{
int value = -1;
string description = row ? "row" : "column";
bool isValid = false;
while (!isValid)
{
Console.Write("Player '" + (playerOne ? "X" : "O") + "', choose a " + description + " (1-3): ");
if (int.TryParse(Console.ReadLine(), out value))
{
if (value >= 1 && value <= 3)
{
isValid = true;
}
else
{
Console.WriteLine("Please enter a number between 1 and 3.");
}
}
else
{
Console.WriteLine("\nInvalid " + description + "!");
}
}
return value;
}
private static bool XorO(int row, int col)
{
int index = ((row - 1) * 3) + (col - 1);
if (board[index] == ' ')
{
board[index] = playerOne ? 'X' : 'O';
return true;
}
else
{
Console.WriteLine("That spot is already taken!");
return false;
}
}
private static bool CheckForDiagonal()
{
return ((board[6] != ' ' && board[4] == board[6] && board[2] == board[6]) ||
(board[0] != ' ' && board[4] == board[0] && board[8] == board[0]));
}
private static bool CheckForVertical()
{
for(int c=0; c<=2; c++)
{
if (board[c] != ' ' && board[c+3] == board[c] && board[c+6] == board[c])
{
return true;
}
}
return false;
}
private static bool CheckForHorizontal()
{
for (int r=0; r<=6; r=r+3)
{
if (board[r] != ' ' && board[r + 1] == board[r] && board[r + 2] == board[r])
{
return true;
}
}
return false;
}
}
I am making an RPG sort of text adventure in Visual Studio C# console.
I am trying to create a piece of code that will detect your location. I want it to then respond in the necessary format. I know you can probably do this more effectively with arrays but I'm happy with how it is now. What I want to do is stop it from constantly repeating the message "It worked.". If it only states it once then it has worked. I have tried multiple methods. Please offer a solution to my issues.
Code Here or Underneath
using System;
namespace RPG
{
class MainClass
{
public static void Main(string[] args)
{
//Done(); will check if Cords are at end of game
//variables
string response = "";
string name = "";
bool hastyped = false;
//Coordinates
int xCord = 0; int yCord = 0;
void Done()
{
if (yCord == 5 && xCord == 7)
{
Console.WriteLine("Thanks for playing! You did it!");
}
}
void Move()
{
if (hastyped == true)
{
if (response == "E")
{
xCord = xCord + 1;
}
else if (response == "W")
{
xCord = xCord - 1;
}
else if (response == "N")
{
xCord = xCord + 1;
}
else if (response == "S")
{
xCord = xCord - 1;
}
else
{
Console.WriteLine("That movement is invalid.");
}
hastyped = false;
response = "";
Done();
}
}
//FANCY START LOGO
Console.WriteLine(#"
____________ _____
| ___ \ ___ \ __ \
| |_/ / |_/ / | \/
| /| __/| | __
| |\ \| | | |_\ \
\_| \_\_| \____/
"
);
System.Threading.Thread.Sleep(2500);
while (response != "Y")
{
Console.WriteLine("Please answer with Y for yes and N for no. Please try to answer all questions as simply as possible.\nPlease type N for north, E for east, S for south and W for west.");
Console.WriteLine("Ok?");
response = Console.ReadLine();
if (response == "Y")
{
Console.WriteLine("Well lets start:");
}
else
{
Console.WriteLine("Please try again.");
}
}
//Instructions
Console.WriteLine("LOADING...");
Console.WriteLine("7%");
System.Threading.Thread.Sleep(200);
Console.WriteLine("26 %");
System.Threading.Thread.Sleep(100);
Console.WriteLine("48%");
System.Threading.Thread.Sleep(200);
Console.WriteLine("76%");
System.Threading.Thread.Sleep(600);
Console.WriteLine("87%");
System.Threading.Thread.Sleep(400);
Console.WriteLine("99%");
System.Threading.Thread.Sleep(20);
Console.WriteLine("100%");
//Loading...
Console.WriteLine("Hey buddy, you took that hit pretty hard. Are you alright?");
Console.ReadLine();
Console.WriteLine("Well we need to get you to a hospital.\nSorry, what was your name?");
name = Console.ReadLine();
Console.WriteLine("Well " + name + ", I wish we were meeting under better circumstances.");
Console.WriteLine("Anyway, I'm Dave. Off to the East is a path that looks pretty safe, the only other direction is back to the west where I just found you. So we won't go there.");
Console.WriteLine("YOU MOVED EAST!!!");
xCord = xCord + 1;
//Intro
//GAMEPLAY
while (true)
{
//1,0
if (xCord == 1 && yCord == 0)
{
Console.WriteLine("Hit E then enter for testing.");
response = Console.ReadLine();
hastyped = !string.IsNullOrWhiteSpace(response);
if (hastyped == true)
{
Move();
}
}
//2,0
if (xCord == 2 && yCord == 0)
{
Console.WriteLine("It worked.");
}
//3,0
if (xCord == 3 && yCord == 0)
{
}
//-1,0
if (xCord == -1 && yCord == 0)
{
}
//-2,0
if (xCord == -2 && yCord == 0)
{
}
//-3,0
if (xCord == -3 && yCord == 0)
{
}
//1,1
if (xCord == 1 && yCord == 1)
{
}
//2,1
if (xCord == 2 && yCord == 1)
{
}
//3,1
if (xCord == 3 && yCord == 1)
{
}
//-1,1
if (xCord == -1 && yCord == 1)
{
}
//-2,1
if (xCord == -2 && yCord == 1)
{
}
//-3,1
if (xCord == -3 && yCord == 1)
{
}
//1,2
if (xCord == 1 && yCord == 2)
{
}
//2,2
if (xCord == 2 && yCord == 2)
{
}
//3,2
if (xCord == 3 && yCord == 2)
{
}
//-1,2
if (xCord == -1 && yCord == 2)
{
}
//-2,2
if (xCord == -2 && yCord == 2)
{
}
//-3,2
if (xCord == -3 && yCord == 2)
{
}
//1,3
if (xCord == 1 && yCord == 3)
{
}
//2,3
if (xCord == 2 && yCord == 3)
{
}
//3,3
if (xCord == 3 && yCord == 3)
{
}
//-1,3
if (xCord == -1 && yCord == 3)
{
}
//-2,3
if (xCord == -2 && yCord == 3)
{
}
//-3,3
if (xCord == -3 && yCord == 3)
{
}
//1,-1
if(xCord == 1 && yCord == -1)
{
}
//2,-1
if (xCord == 2 && yCord == -1)
{
}
//3,-1
if (xCord == 3 && yCord == -1)
{
}
//-1,-1
if (xCord == -1 && yCord == -1)
{
}
//-2,-1
if (xCord == -2 && yCord == -1)
{
}
//-3,-1
if (xCord == -3 && yCord == -1)
{
}
//1,-2
if (xCord == 1 && yCord == -2)
{
}
//2,-2
if (xCord == 2 && yCord == -2)
{
}
//3,-2
if (xCord == 3 && yCord == -2)
{
}
//-1,-2
if (xCord == -1 && yCord == -2)
{
}
//-2,-2
if (xCord == -2 && yCord == -2)
{
}
//-3,-2
if (xCord == -3 && yCord == -2)
{
}
//1,-3
if (xCord == 1 && yCord == -3)
{
}
//2,-3
if (xCord == 2 && yCord == -3)
{
}
//3,-3
if (xCord == 3 && yCord == -3)
{
}
//-1,-3
if (xCord == -1 && yCord == -3)
{
}
//-2,-3
if (xCord == -2 && yCord == -3)
{
}
//-3,-3
if (xCord == -3 && yCord == -3)
{
}
//0,3
if (xCord == 0 && yCord == 3)
{
}
//0,2
if (xCord == 0 && yCord == 2)
{
}
//0,1
if (xCord == 0 && yCord == 1)
{
}
//0,0
if (xCord == 0 && yCord == 0)
{
}
//0,-1
if (xCord == 0 && yCord == -1)
{
}
//0,-2
if (xCord == 0 && yCord == -2)
{
}
//0,-3
if (xCord == 0 && yCord == -3)
{
}
//BOUNDARIES:
//RIGHT
if (xCord == 4)
{
Console.WriteLine("This area doesn't exist.");
xCord = xCord - 1;
}
//LEFT
if (xCord == -4)
{
Console.WriteLine("This area doesn't exist.");
xCord = xCord + 1;
}
//TOP
if (yCord == 4)
{
Console.WriteLine("This area doesn't exist.");
yCord = yCord - 1;
}
//BOTTOM
if (yCord == -4)
{
Console.WriteLine("This area doesn't exist.");
yCord = yCord + 1;
}
}
}
}
}
This is a lot of code in one main loop, I would suggest splitting the functionality into more functions.
To answer your question; the reason your console is spamming "It Worked!". Is because your "if" statement is inside a continuous while-loop. You could try adding an extra boolean to your if statement, as such:
//GAMEPLAY
boolean hasMoved = false;
while (true)
{
//2,0
if (xCord == 2 && yCord == 0 && !hasMoved)
{
Console.WriteLine("It worked.");
hasMoved = true;
}
else{
hasMoved = false;
}
why dont you use switch case in place of if else .
also, you can use break; after printing it worked
I have searched the similar games on forum and google but i could not find exactly.
I am making a puzzle game. and user can get point if the nodes (horizontal sticks) are same color then he can get.
when they are in same direction it says colors matched but in generated node whenever i rotate the sticks it says also same.
Can you take a look? and tell me how to fix. Also if you have better idea about this matching I will be appreciated.
---------
void Update()
{
if (Input.GetMouseButtonDown(0))
{
clickTime = Time.time;
rayhit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero, Mathf.Infinity, selectableObjLayerMask);
}
else if (Input.GetMouseButtonUp(0))
{
if (rayhit)
{
if (Time.time - clickTime < .2f)
{
Node node = rayhit.transform.GetComponent<Node>();
if (node != null)
{
for (int i = 0; i < node.sticks.Count; i++)
{
Vector3 newAngles = new Vector3(0, 0, (node.sticks[i].transform.localEulerAngles.z - 45));
newAngles.z = newAngles.z < 0 ? newAngles.z + 180 : newAngles.z;
newAngles.z = newAngles.z >180 ? newAngles.z - 180 : newAngles.z;
node.sticks[i].transform.localEulerAngles = newAngles;
node.sticks[i].degree = (int)newAngles.z;
//******** HERE IS COLOR MATCHING*******
if (node.transform.parent.name=="Node1" && node.sticks[i].degree == 90)
{
colorMatch[1] = node.sticks[i].color;
Debug.Log("COLOR 1___"+ colorMatch[1]);
//Debug.Log(colorMatch1);
}
if (node.transform.parent.name == "Node2" && node.sticks[i].degree == 90)
{
colorMatch[2] = node.sticks[i].color;
Debug.Log("COLOR 2___" + colorMatch[2]);
}
if (node.transform.parent.name == "Node3" && node.sticks[i].degree == 90)
{
colorMatch[3] = node.sticks[i].color;
Debug.Log("COLOR 3___" + colorMatch[3]);
//if (colorMatch[1] == colorMatch[2] && colorMatch[2] == colorMatch[3])
//{
// Debug.Log("COLORS MATCHED : " + colorMatch[1]);
//}
}
if (colorMatch[1]==colorMatch[2] && colorMatch[2]==colorMatch[3])
{
Debug.Log("COLOR MATCHED");
}
}
}
}
else
{
Node currNode = rayhit.transform.GetComponent<Node>();
if(currNode.isMoved == false)
{
smallestId = 0;
smallestDistance = 999;
for (int i = 0; i < nodes.Length; i++)
{
float distance = Vector2.Distance(rayhit.transform.position, nodes[i].transform.position);
if (smallestDistance > distance)
{
smallestDistance = distance;
smallestId = i;
}
}
rayhit.transform.position = nodes[smallestId].transform.position;
if (rayhit.transform.parent != nodes[smallestId].transform)
{
if (nodes[smallestId].transform.childCount > 0 && nodes[smallestId].transform != rayhit.transform.parent)
{
if (currNode != null)
{
for (int i = 0; i < currNode.sticks.Count; i++)
{
nodes[smallestId].transform.GetChild(0).GetComponent<Node>().sticks.Add(currNode.sticks[i]);
currNode.sticks[i].transform.SetParent(nodes[smallestId].transform.GetChild(0));
}
Destroy(rayhit.transform.gameObject);
}
}
else
{
if (currNode != null)
{
currNode.isMoved = true;
}
rayhit.transform.SetParent(nodes[smallestId].transform);
}
}
}
}
}
rayhit = new RaycastHit2D();
}
else if (Input.GetMouseButton(0))
{
if(rayhit.transform != null)
{
Node currNode = rayhit.transform.GetComponent<Node>();
if(currNode != null)
if (currNode.isMoved == false)
{
if (Time.time - clickTime >= 0.2f)
{
Vector2 newPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
rayhit.transform.position = newPos;
}
}
}
}
}
if (node.transform.parent.name=="Node1" && node.sticks[i].degree == 90)
{
colorMatch[1] = node.sticks[i].color;
Debug.Log("COLOR 1___"+ colorMatch[1]);
//Debug.Log(colorMatch1);
}
if (node.transform.parent.name == "Node2" && node.sticks[i].degree == 90)
{
colorMatch[2] = node.sticks[i].color;
Debug.Log("COLOR 2___" + colorMatch[2]);
}
if (node.transform.parent.name == "Node3" && node.sticks[i].degree == 90)
{
colorMatch[3] = node.sticks[i].color;
Debug.Log("COLOR 3___" + colorMatch[3]);
if (colorMatch[1] == colorMatch[2] && colorMatch[2] == colorMatch[3])
{
Debug.Log("COLORS MATCHED : " + colorMatch[1]);
}
}
Here is working code. but how i can destroy the matched sticks?
I am trying to make a string calculator, it works fine with two numbers but I always encounter a problem when evaluating multiple operations:
7*2+4=
Also can you help me with my multiplication and division code. I don't understand why it prints 0 even with just two numbers(7*5)
using System;
using System.Text.RegularExpressions;
namespace Sariling_Calcu
{
class Program
{
private static string exp;
private static int[] i = new int[1000];
private static char[] oper = new char[10];
private static int cntr2;
private static int result;
private static int pluscount;
private static int subcount;
private static int mulcount;
private static int divcount;
static void getNum()
{
string[] strNum = (Regex.Split(exp, #"\D+"));
for (int cntr = 0; cntr < exp.Length; cntr++)
{
foreach (string item in strNum)
{
if (!string.IsNullOrEmpty(item))
{
i[cntr] = int.Parse(item);
cntr += 1;
}
}
}
}
static void counter()
{
for (int cntr = 0; cntr < exp.Length; cntr++)
{
if (exp[cntr] == '+')
{
pluscount++;
}
else if (exp[cntr] == '-')
{
subcount++;
}
else if (exp[cntr] == '*')
{
mulcount++;
}
else if (exp[cntr] == '/')
{
divcount--;
}
}
}
static void oprtr()
{
for (int cntr = 0; cntr < exp.Length; cntr++)
{
if (exp[cntr] != '1'
&& exp[cntr] != '2'
&& exp[cntr] != '3'
&& exp[cntr] != '4'
&& exp[cntr] != '5'
&& exp[cntr] != '6'
&& exp[cntr] != '7'
&& exp[cntr] != '8'
&& exp[cntr] != '9')
{
if (exp[cntr] == '+')
{
result += i[cntr2];
cntr2 += 1;
pluscount--;
if (pluscount == 0 && subcount == 0 && mulcount==0 && divcount==0)
{
cntr2 += 3;
result += i[cntr2];
}
}
else if (exp[cntr] == '-')
{
result -= i[cntr2];
cntr2 += 1;
subcount--;
result = -result;
if (pluscount == 0 && subcount == 0 && mulcount == 0 && divcount == 0)
{
cntr2 += 3;
result -= i[cntr2];
}
}
else if (exp[cntr] == '*')
{
if (result == 0)
{
result += 1;
}
result *= i[cntr2];
cntr2 += 1;
mulcount--;
if (pluscount == 0 && subcount == 0 && mulcount == 0 && divcount == 0)
{
cntr2 += 3;
result *= i[cntr2];
}
}
else if (exp[cntr] == '/')
{
if (result == 0)
{
result += 1;
}
result /= i[cntr2];
cntr2 += 1;
divcount--;
if (pluscount == 0 && subcount == 0 && mulcount == 0 && divcount == 0)
{
cntr2 += 3;
result /= i[cntr2];
}
}
}
}
}
static void Main(string[] args)
{
Console.Write("Expression: ");
exp = Console.ReadLine();
counter();
getNum();
oprtr();
Console.Write("Answer: \n" + result);
Console.ReadLine();
}
}
}
you could use LINQ to reduce your code to a few lines but looks like its a school assignment where you would have to go with Arrays and loops.
I have tried to refine your code a bit and did a few fixes, change getNum(), counter() and oprtr() methods as below and let me know if it works, then I would add some comments in the code to explain changes I made.
static void getNum()
{
string[] strNum = (Regex.Split(exp, #"\D+"));
for (int cntr = 0; cntr < strNum.Length; cntr++)
{
if (!string.IsNullOrEmpty(strNum[cntr]))
{
i[cntr] = int.Parse(strNum[cntr]);
}
}
}
static void counter()
{
cntr2 = 0;
for (int cntr = 0; cntr < exp.Length; cntr++)
{
if (exp[cntr] == '+')
{
oper[cntr2] = '+';
cntr2++;
}
else if (exp[cntr] == '-')
{
oper[cntr2] = '-';
cntr2++;
}
else if (exp[cntr] == '*')
{
oper[cntr2] = '*';
cntr2++;
}
else if (exp[cntr] == '/')
{
oper[cntr2] = '/';
cntr2++;
}
}
}
static void oprtr()
{
result = i[0];
cntr2 = 1;
for (int cntr = 0; cntr < oper.Length; cntr++)
{
if (oper[cntr] == '+')
{
result += i[cntr2];
}
else if (oper[cntr] == '-')
{
result -= i[cntr2];
}
else if (oper[cntr] == '*')
{
result *= i[cntr2];
}
else if (oper[cntr] == '/')
{
if (i[cntr2] == 0)
{
throw new DivideByZeroException();
}
result /= i[cntr2];
}
cntr2 += 1;
}
}
My code is working intermittently, but sometimes gives me the argument out of range error and I can't figure out why, I've narrowed it down to one function:
void corridorFill()
{
int dir = 0;
//Set initial coords
int rand = Random.Range(0,freeCol.Count);
List<int> freeCorRow = new List<int>();
List<int> freeCorCol = new List<int>();
row = freeRow[rand];
col = freeCol[rand];
int fill = 0;
while(fill < area)
{
//Pick a random direction and go that way
//0 = north, 1 = east, 2 = south, 3 = west
dir = Random.Range(0,4);
if(directionIsSafe(dir, row, col, (int)room.Unreserved, roomType)
&& directionIsSafe(dir, row, col, (int)connect.Empty, connections))
{
//move in direction
moveDirection(dir);
freeCorRow.Add(row);
freeCorCol.Add(col);
if(fill > 0)
{
//place exit to previous tile
addExit(row, col, (dir+2)%4);
//change exits of previous room to connect
addExit(freeCorRow[freeCorRow.Count-2], freeCorCol[freeCorCol.Count-2], dir);
}
fill++;
}
else
{
bool set = false;
while(!set)
{
//direction is not safe therefore start again somewhere else, attached to what we already have
int r = Random.Range(0,freeCorRow.Count);
//check if a tile beside a known tile is free
dir = Random.Range(0,4);
//if the direction is safe, go that way
if(directionIsSafe(dir, freeCorRow[r], freeCorCol[r], (int)room.Unreserved, roomType)
&& directionIsSafe(dir, freeCorRow[r], freeCorCol[r], (int)connect.Empty, connections))
{
addExit(freeCorRow[r], freeCorCol[r], dir);
row = freeCorRow[r];
col = freeCorCol[r];
moveDirection(dir); //move in direction
addExit(row, col, (dir+2)%4); //place exit to previous tile
freeCorRow.Add(row);
freeCorCol.Add(col);
set = true;
}
}
fill++;
}
}
}
which uses the addExit function, though I don't think the problem is here:
//check previous tile corridor configuration and change to match current
void addExit(int row, int col, int dir)
{
//Add northourn exit to room
if(dir == 0)
{
if(connections[row,col] == (int)connect.Empty)
{
connections[row,col] = (int)connect.N;
}
else if(connections[row,col] == (int)connect.E)
{
connections[row,col] = (int)connect.NE;
}
else if(connections[row,col] == (int)connect.S)
{
connections[row,col] = (int)connect.NS;
}
else if(connections[row,col] == (int)connect.W)
{
connections[row,col] = (int)connect.NW;
}
else if(connections[row,col] == (int)connect.SE)
{
connections[row,col] = (int)connect.NES;
}
else if(connections[row,col] == (int)connect.SW)
{
connections[row,col] = (int)connect.SWN;
}
else if(connections[row,col] == (int)connect.EW)
{
connections[row,col] = (int)connect.WNE;
}
else if(connections[row,col] == (int)connect.ESW)
{
connections[row,col] = (int)connect.NESW;
}
}
//Add eastern exit to room
if(dir == 1)
{
if(connections[row,col] == (int)connect.Empty)
{
connections[row,col] = (int)connect.E;
}
else if(connections[row,col] == (int)connect.N)
{
connections[row,col] = (int)connect.NE;
}
else if(connections[row,col] == (int)connect.S)
{
connections[row,col] = (int)connect.SE;
}
else if(connections[row,col] == (int)connect.W)
{
connections[row,col] = (int)connect.EW;
}
else if(connections[row,col] == (int)connect.NW)
{
connections[row,col] = (int)connect.WNE;
}
else if(connections[row,col] == (int)connect.SW)
{
connections[row,col] = (int)connect.ESW;
}
else if(connections[row,col] == (int)connect.NS)
{
connections[row,col] = (int)connect.NES;
}
else if(connections[row,col] == (int)connect.SWN)
{
connections[row,col] = (int)connect.NESW;
}
}
//Add southourn exit to room
if(dir == 2)
{
if(connections[row,col] == (int)connect.Empty)
{
connections[row,col] = (int)connect.S;
}
else if(connections[row,col] == (int)connect.N)
{
connections[row,col] = (int)connect.NS;
}
else if(connections[row,col] == (int)connect.E)
{
connections[row,col] = (int)connect.SE;
}
else if(connections[row,col] == (int)connect.W)
{
connections[row,col] = (int)connect.SW;
}
else if(connections[row,col] == (int)connect.NE)
{
connections[row,col] = (int)connect.NES;
}
else if(connections[row,col] == (int)connect.NW)
{
connections[row,col] = (int)connect.SWN;
}
else if(connections[row,col] == (int)connect.EW)
{
connections[row,col] = (int)connect.ESW;
}
else if(connections[row,col] == (int)connect.WNE)
{
connections[row,col] = (int)connect.NESW;
}
}
//Add western exit to room
if(dir == 3)
{
if(connections[row,col] == (int)connect.Empty)
{
connections[row,col] = (int)connect.W;
}
else if(connections[row,col] == (int)connect.N)
{
connections[row,col] = (int)connect.NW;
}
else if(connections[row,col] == (int)connect.E)
{
connections[row,col] = (int)connect.EW;
}
else if(connections[row,col] == (int)connect.S)
{
connections[row,col] = (int)connect.SW;
}
else if(connections[row,col] == (int)connect.NE)
{
connections[row,col] = (int)connect.WNE;
}
else if(connections[row,col] == (int)connect.SE)
{
connections[row,col] = (int)connect.ESW;
}
else if(connections[row,col] == (int)connect.NS)
{
connections[row,col] = (int)connect.SWN;
}
else if(connections[row,col] == (int)connect.NES)
{
connections[row,col] = (int)connect.NESW;
}
}
}
and the directionIsSafe function:
bool directionIsSafe(int dir, int row, int col, int roomname, int[,] checkType)
{
if(dir == 0 && col+1 < stationHeight)
{
if(checkType[row, col+1] == roomname)
{
return true;
}
else
{
return false;
}
}
else if(dir == 1 && row+1 < stationWidth)
{
if(checkType[row+1,col] == roomname)
{
return true;
}
else
{
return false;
}
}
else if(dir == 2 && col > 0)
{
if(checkType[row,col-1] == roomname)
{
return true;
}
else
{
return false;
}
}
else if(dir == 3 && row > 0)
{
if(checkType[row-1,col] == roomname)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
Reading through the code it seems like it should work, and it does some of the time, but not all of the time. I can't figure out why only sometimes it doesn't work. Appreciate any light you might shed on the problem
EDT
freeCol and freeRow are created using:
if(genType == (int)shapes.cross)
{
//for odd numbers
if(stationWidth%2 == 1)
{
for(row = 0; row < stationWidth; row++)
{
for(col = 0; col < stationHeight; col++)
{
if((row <= stationWidth/2 + (crossArmSize/2.0f + 0.5f) - 1 && row >= stationWidth/2 - (crossArmSize/2.0f + 0.5f) + 1)
|| (col <= stationHeight/2 + (crossArmSize/2.0f + 0.5f) - 1 && col >= stationHeight/2 - (crossArmSize/2.0f + 0.5f) + 1))
{
roomType[row,col] = (int)room.Unreserved;
freeRow.Add(row);
freeCol.Add(col);
}
}
}
}
//for even numbers
else if(stationWidth%2 == 0)
{
for(row = 0; row < stationWidth; row++)
{
for(col = 0; col < stationHeight; col++)
{
if((row < stationWidth/2 + crossArmSize/2 && row >= stationWidth/2 - crossArmSize/2)
|| (col < stationWidth/2 + crossArmSize/2 && col >= stationWidth/2 - crossArmSize/2))
{
roomType[row,col] = (int)room.Unreserved;
freeRow.Add(row);
freeCol.Add(col);
}
}
}
}
corridorFill();
}
I think Random.Range is inclusive. Try int rand = Random.Range(0,freeCol.Count - 1);
Are Width and Height swapped in the last function?
Normally rows go along the height and columns along the width.
OK, so I changed:
row = freeRow[rand];
col = freeCol[rand];
to:
row = freeRow[Mathf.RoundToInt(stationWidth/2)];
col = freeCol[Mathf.RoundToInt(stationHeight/2)];
and it works every time now. I just can't figure out why the former was throwing out weird results and just plain not working, if you can shed light on it I'd love to hear it!