Class Wide Array in C# - c#

I'm trying to create a class wide array in C#, in a Windows Mobile Phone 8.1 project, so that when I create a method I can
What I did at first was:
public sealed partial class GamePage : Page
{
int Score = 0;
int count = 0;
private DispatcherTimer Timer;
public ColorsClass color = new ColorsClass();
public int RandBlue = 0;
int RandGreen = 0;
int RandRed = 0;
int RandYellow = 0;
int RandPurple = 0;
int RandYellowGreen = 0;
int RandOrange = 0;
int RandGray = 0;
bool Equal = true;
int Fail;
int Hit;
int Lives = 10;
Rectangle[] Block = { Block01, Block02, Block03, Block04, Block05, Block06, Block07, Block08, Block09, Block10, Block11, Block12 };
int[] RandomColors = { RandBlue, RandGreen, RandRed, RandYellow, RandPurple, RandYellowGreen, RandGray };
...
}
But it gives me the message that "a field initializer cannot reference the non-static field, method or property..."
Then I tried this option, that I saw when I was search in the internet:
public sealed partial class GamePage : Page
{
int Score = 0;
int count = 0;
private DispatcherTimer Timer;
public ColorsClass color = new ColorsClass();
public int RandBlue = 0;
int RandGreen = 0;
int RandRed = 0;
int RandYellow = 0;
int RandPurple = 0;
int RandYellowGreen = 0;
int RandOrange = 0;
int RandGray = 0;
bool Equal = true;
int Fail;
int Hit;
int Lives = 10;
int []
Random rand = new Random();
public GamePage()
{
this.InitializeComponent();
DispatchTheTime();
RandomColors = new int[] { RandBlue, RandGreen, RandRed, RandYellow, RandPurple, RandYellowGreen, RandGray };
...
}
This way I can reach the array through the methods I created, but the array values are always null..
What can I do?

Everytime when you create a new GamePage you are filling your array with the content of the variables RandGreen, RandRed, ...
At this time, these variables are set to 0. Thus your array contains only 0s. Even if you later assign other values to RandGreen, RandRed, ... the values within the array will not change.
I hope this example will make it clearer:
RandBlue = 0;
var RandomColors = new int[] { RandBlue, RandGreen };
// RandColors[0] is 0
RandBlue = 5;
// RandColors[0] is still 0
Edit:
The error message "a field initializer cannot reference the non-static field, method or property..." should be self-explaining. You could make your color variables const in order to make it work. But I suppose this would not make any sense for you.

Keep in mind that integers are valuetypes. If you create an array of integers like with the RandomColors, you'll just put a copy of your value in the array. At this point, RandGreen and RandomColors[1] point to different memory locations and a change of either won't propagate to the other.
You have to decide whether you want to keep your values in a lot of fields like you actually declared or if you want to keep your integers in an array.
You are propably better off using a Dictionary for your usecase and only access the integers from there.
On class level declare your RandomColors:
Dictionary<string, int> RandomColors = new Dictionary<string, int>();
public GamePage()
{
RandomColors.Add("RandGreen", 0);
RandomColors.Add("RandRed", 0);
//change like this:
RandomColors["RandGreen"] = 5;
//access like this:
int x = RandomColors["RandGreen"];
}

Related

I want to create an array of scene indexes and use it, when i need. The problem is that i don't know how to create the array itself

I did this
public int[] sceneIndex;
public Text[] texts;
IEnumerator ChoosingModes()
{
string[] modes = new string[] { "Cocks", "Tanks", "Cars" };
sceneIndex = new int[] { };
for (int i = 0; i < 5; i++)
{
int x = Random.Range(0, modes.Length);
texts[i].text = modes[x];
sceneIndex[i] = x + 3;
yield return new WaitForSeconds(0.75f);
}
}
It obviously doesn't work, what to do with my in array named 'sceneIndex'?
When you do sceneIndex = new int[] { };, you're locking the length of the length of sceneIndex to 0. Instead, try either sceneIndex = new int[number or scenes]; (locking the length of sceneIndex to the number of scenes you have) or just doing nothing. Since the array is public, you can set the values in the inspector and you won't have to define it in the code.

Set value to a random property from list

Please check the code below. I am trying to set value to a random property of a int list. Problem is that even after i set 5 to a random list this value getting inserted to that property. What am I doing wrong here?
var TransactionList = new List<int>();
for (int i = 0; i < 59; i++)
{
TransactionList.Add(0);
}
var randTransaction = TransactionList.OrderBy(x => Guid.NewGuid()).FirstOrDefault();
//here i am trying to set 5 value to a random TrnasactionList but this not being set
randTransaction = 5;
Try like below. new Random().Next(0, 59); will return value between 0 and 59. Or you can better set it like new Random().Next(0, TransactionList.Count); for it to be dynamic with list.
new Random().Next(minValue, maxValue); The maxValue for the upper-bound in the Next() method is exclusive—the range includes minValue, maxValue-1, and all numbers in between.
var TransactionList = new List<int>();
for (int i = 0; i < 59; i++)
{
TransactionList.Add(0);
}
// var index = new Random().Next(0, 59);
// Below will work for dynamic length of list.
var index = new Random().Next(0, TransactionList.Count);
TransactionList[index] = 5;
If you don't mind the original list getting sorted you could do this:
class Program
{
static void Main(string[] args)
{
var transactionList = new List<int>();
for (int i = 0; i < 59; i++)
{
//I initialized the list with i instead of 0 to better see sorting in place
transactionList.Add(i);
}
transactionList.Sort(new RandomComparer());
//changed it to 99 to spot it more easily
transactionList[0] = 99;
foreach (var i in transactionList)
Console.WriteLine(i);
}
}
public class RandomComparer : IComparer<int>
{
private Random _random = new Random();
public int Compare(int x, int y)
{
return _random.Next(-1, 2);
}
}
See it in action:
https://dotnetfiddle.net/NKuPdx
randTransaction is "int" data type, which is primitive data type.
if you want to set randTransaction that reflect to it's object, just set the object it self

How can I add objects Cbook to my class CBooks without using lists

Cbooks has an atribute "CTeam[] Teams" and it is of fixed size (8). If I want to add objects to it using this in the Main:
CBook A1 = new CBook("Title1", "Author1");
CBook A2 = new CBook("Title1", "Author2");
CBooks ArrayOfBooks = new CBooks(8);
ArrayOfBooks.Add(A1);
ArrayOfBooks.Add(A2);
then position 0 and 1 are ocuppied, and the positions from 2 to 7 are null. What I want to do is, using a variable "int aux=0", count the ocupied positions like this:
for (int k = 0; k < NumberOfTeams; k++)
{
if (Teams[k].Name=="")
Aux += 1;
}
So, Aux in this case would be 2, then I want to do "Teams[Aux] = A" so that A would be in the position 2 and now I should have three objects in my array. But I'm getting "Index out of bound"
Your implementation then should look similar to this:
public class Program
{
public static void Main(string[] args)
{
Element a = new Element("A");
Element b = new Element("B");
MyArray array = new MyArray(8);
array.Add(a);
array.Add(b);
Console.WriteLine(array.Count()); //2 Elements are in the array
}
}
//Sample element class.
public class Element{
public readonly String MyString;
public Element(String myString){
MyString = myString;
}
}
//Sample array class.
public class MyArray{
private readonly Element[] myArray;
private int count; //Use a property here
public MyArray(int size){
//Be careful -> check if size is >= 0.
myArray = new Element[size];
}
public bool Add(Element element){
if(myArray.Length == count) // return false if no more elements fit.
return false;
myArray[count] = element;
count++;
return true;
}
public int Count(){
return count;
}
}
So there is no need for creating an extra count loop. Your "count" variable in "MyArray" class holds always the correct value.
Anyway the implementation or use case of this code is a little bit clunky.
Why are you cant use directly a more safe list or something. That would be a better solution.
What do you need CBooks for? From what I understand, it's just an array of 8 CBook objects so why not use CBook[]?
CBook A1 = new CBook("Title1", "Author1");
CBook A2 = new CBook("Title1", "Author2");
CBooks[] ArrayOfBooks = new CBook[8];
ArrayOfBooks[0] = A1;
ArrayOfBooks[1] = A2;
int aux = 0;
for (int k = 0; k < ArrayOfBooks.Length; k++)
{
//break the loop because we know there are no more books
if (ArrayOfBooks[k] == null)
break;
aux++;
}
The question doesn't cover what the variables NumberOfTeams and Teams are for but could those be added to the implementation of CBook?

Creating a List of Arrays in C#?

So I'm working on a game that uses a coordinate system, and I want to populate the map with a certain number of trees. The way I'm doing it (and it may not be the best way) is picking a random set of coordinates, checking to see if those coordinates are in the list of locations with trees in them, and if not adding the tree to the map, and adding those coordinates to the list. My instinct was to store the coordinates as an array, however I can't seem to figure out the syntax for it. Here's what I have:
int boardWidth = 10;
int boardHeight = 10;
int numTrees = 75;
List<int[]> hasTree = new List<int[]>();
public Transform tree;
Transform[,] SetTrees(Transform[,] map) {
int treex = Random.Range(0,boardWidth-1);
int treey = Random.Range(0,boardHeight-1);
int[] treeCoords = new int[] { treex,treey };
int treeCount = 0;
while(treeCount < numTrees){
if (hasTree.Contains(treeCoords)){
treex = Random.Range(0,boardWidth-1);
treey = Random.Range(0,boardHeight-1);
}
else{
map[treex,treey] = (Transform)Instantiate(tree, new Vector3(i*tileWidth, 10, j*tileHeight), Quaternion.AngleAxis(90, Vector3.left));
hasTree.Add(treeCoords);
treex = Random.Range(0,boardWidth-1);
treey = Random.Range(0,boardHeight-1);
treeCount++;
}
}
return(map);
}
Any thoughts?
If I were you I'd try something like this:
int boardWidth = 10;
int boardHeight = 10;
int numTrees = 75;
var rnd = new Random();
var query =
from x in Enumerable.Range(0, boardWidth)
from y in Enumerable.Range(0, boardHeight)
orderby rnd.NextDouble()
select new { x, y };
var board = new bool[boardWidth, boardHeight];
foreach (var pair in query.Take(numTrees))
{
board[pair.x, pair.y] = true;
}
Keep It Simple Silly:
Transform[,] SetTrees(Transform[,] map) {
for(int treeCount = 0; treeCount < numTrees; treeCount++){
int treex = Random.Range(0,boardWidth-1);
int treey = Random.Range(0,boardHeight-1);
map[treex,treey] = new TreeTransform(treex, treey}
}
return(map);
}
Bury the details of Tree creation in its constructor TreeTransform, where it belongs.
Who cares about a creation ordering of the trees on the board? it has no use.
There is no reason for the number of trees to be exact, so just ignore duplicates.
Simplify the code then it might be easier to determine your best course of action.
I simplify by breaking down the problem until its so simple I can't really see how not to do it !!!
I am guessing how some of this code works here but I think you want something like this ...
Transform[,] SetTrees(Transform[,] map) {
for (int i = 0; i < numTrees; i++){
if(!AddTreeTo(map)){
--i;
}
}
return(map);
}
bool AddTreeToMap(Transform[,] map)
{
int[] treeCoord = GetRandomCoord(map.Width, map.Height);
if (!map[treeCoord[0],treeCoord[1]].HasTree()){
map[treex,treey] = (Transform)Instantiate(tree, new Vector3(i*tileWidth, 10, j*tileHeight), Quaternion.AngleAxis(90, Vector3.left));
map[treeCoord[0],treeCoord[1]].Add(treeCoords);
return true;
}
return false;
}
int[] GetRandomTreeCoord(int maxX, int maxY)
{
int treex = Random.Range(0,maxX-1);
int treey = Random.Range(0,maxY-1);
int[] treeCoords = new int[] { treex,treey };
return treeCoords;
}

Nested Loop not iterating

In my code I have a nested loop which does not iterate with the exception of an if statement that always occurs no matter what the condition. Without the if statement the portion of the for loop's code which iterates the loop becomes unreachable. No matter what I have tried I have not been able to get the inside loop to iterate.
class Map
{
public int Width { get; set; }
public int Height { get; set; }
public Vector2[] positions = new Vector2[500*500];
private GroundVoxel[,] map = new GroundVoxel[500, 500];
private Vector2 voxelPosition = new Vector2(0,0);
private static int sizeX = 499, sizeY = 499, airLevel = 425;
private int positionX = 0, positionY = 0, vectorNumber = 0;
public Map()
{
}
public Vector2[] Initialize()
{
for (int i = 0; i <= sizeY; i++)
{
for (int j = 0; j <= sizeX; j++) <-- This does not iterate.
{
map[positionX, positionY] = new GroundVoxel(voxelPosition);
voxelPosition.X += 80;
positions[vectorNumber] = voxelPosition;
vectorNumber += 1;
if (j == sizeX) <-- This always executes even though j != sizeX.
{
break;
}
}
voxelPosition.Y += 80;
voxelPosition.X = 0;
}
return positions;
}
}
}
You have to use the fully qualified name to refer to a static class member variable like your sizeX and sizeY. Here is an article on the subject.
Hope this helps!
I think we'll need more code. I've copied your code into a basic winforms test application and both of my loops iterates as expected.
I'm not familiar with XNA or what a "VoxelPosition" is, but I think you have a lurking bug here:
voxelPosition.X += 80;
positions[vectorNumber] = voxelPosition;
You are simply storing the same pointer in a very large array -- all of the entries will be pointing to the same object.
You will need to declare another object every time through the loop to store individal vector entries.
Hope this helps?

Categories

Resources