So I am using a GUI with a class. I have done it before and I know most of the time you create an event for a button. Then when that button is pushed, you can create a new object. In this project I am working on, I have a TextBox that I type a name and a score into. Then when I hit the enter button that I have, I want to create a new object with the parameterized constructor and place the name and score in different arrays so I can manipulate them. Then I want to produce the highest, lowest, and avg scores. I have had previous projects where I just create a new object when the button is pressed. But with this I am loading in multiple things in the same TextBox. So every time the button was hit I was creating a new object. What I want to do is create the object once with a parameterized constructor and then add the names and scores to arrays within the class. Any suggestions.
The bottom method in my form class I tried to mess around and do it this way, but it wouldn't do anything.
private void nameTextBox_TextChanged(object sender, EventArgs e)
{
//Get the information from the text box and store it in a variable
string userInput = nameTextBox.Text;
//Create a new object with the parameterized constructor
myBowlingTeam = new BowlingTeam(userInput);
}
PLEASE HELP. This is like my only hiccup. If I get this part to work right the program will work. Cause I know how to work with the class to produce the results I want. Thanks in advance.
Here is my class code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Project_9
{
class BowlingTeam
{
const int MAX = 10;
//local variables
int sizeOfName = 0;
int sizeOfScore = 0;
//Declare Private Data Members
private string nameAndScore = "";
private string name = "";
private int score = 0;
private string[] nameArray = new string[MAX];
private int[] scoreArray = new int[MAX];
private string[] nameAndScoreArray = new string[MAX];
//Default Constructor
//Purpose: To set the initial values of an object
//Parameters: None
//Returns: Nothing
public BowlingTeam()
{
nameAndScore = "";
name = "";
score = 0;
for(int i = 0; i < MAX; i++)
{
nameArray[i] = "";
}
for(int i = 0; i < MAX; i++)
{
scoreArray[i] = 0;
}
for (int i = 0; i < MAX; i++)
{
nameAndScoreArray[i] = "";
}
}
//Parameterized Constructor
//Purpose: To set the values of an object
//Parameters: None
//Returns: Nothing
public BowlingTeam(string aString)
{
nameAndScore = aString;
name = "";
score = 0;
for (int i = 0; i < MAX; i++)
{
nameArray[i] = "";
}
for (int i = 0; i < MAX; i++)
{
scoreArray[i] = 0;
}
for (int i = 0; i < MAX; i++)
{
nameAndScoreArray[i] = "";
}
}
//Split the Input Method
//Purpose: To Split up the data in the array
//Parameters: An array of strings
//Returns: Nothing
public void SplitAndDisperseArray()
{
nameAndScoreArray = nameAndScore.Split();
name = nameAndScoreArray[0];
score = int.Parse(nameAndScoreArray[1]);
//Place the name and the score in their one arrays
PlaceInNameArray(name);
PlaceInScoreArray(score);
}
//Find Highest Score Method
//Purpose: To find the highest score
//Parameters: An array of int
//Returns: An int
public int CalcHighestScore()
{
int highestScore = 0;
int size = 0;
for (int i = 0; i < MAX; i++ )
{
if (scoreArray[i] < scoreArray[i + 1])
{
highestScore = scoreArray[i];
}
else
{
highestScore = scoreArray[i + 1];
}
}
return highestScore;
}
//Find Lowest Score Method
//Purpose: To find the lowest score
//Parameters: An array of int
//Returns: An int
public int CalcLowestScore(int[] anArrayOfInts, int sizeOfArray)
{
int lowestScore = 0;
while (sizeOfArray < MAX)
{
if (anArrayOfInts[sizeOfArray] < anArrayOfInts[sizeOfArray + 1])
{
lowestScore = anArrayOfInts[sizeOfArray];
}
else
{
lowestScore = anArrayOfInts[sizeOfArray + 1];
}
}
return lowestScore;
}
//Calulate Avg. Score Method
//Purpose: To calculate the avg score
//Parameters: An array of int
//Returns: An double
public double CalculateAvgScore(int[] anArrayOfInts, int sizeOfArray)
{
int sum = 0;
double avg = 0;
//Add up all of the elements in the array
while(sizeOfArray < MAX)
{
sum += anArrayOfInts[sizeOfArray];
}
//Divide the sum by the size of the array
return avg /= sum;
}
//Set Score Array Method
//Purpose: To put scores in the score array
//Parameters: An int
//Returns: Nothing
public void PlaceInScoreArray(int aScore)
{
scoreArray[sizeOfScore] = score;
sizeOfScore++;
}
//Set Name Array Method
//Purpose: To put names in the names array
//Parameters: A string
//Returns: Nothing
public void PlaceInNameArray(string aName)
{
nameArray[sizeOfName] = name;
sizeOfName++;
}
}
}
Here is my Form1 code for the GUI:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Project_9
{
public partial class Form1 : Form
{
//Declare a reference variable to the class
private BowlingTeam myBowlingTeam;
public Form1()
{
InitializeComponent();
myBowlingTeam = new BowlingTeam();//Create a BowlingTeam object with the default constructor
}
//ExitToolStripMenuItem1_Click
//Purpose: To close the application when clicked
//Parameters: The sending object and the event arguments
//Returns: nothing
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
//AboutToolStripMenuItem1_Click
//Purpose: To display student information
//Parameters: The sending object and the event arguments
//Returns: nothing
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Charlie Barber\nCS 1400-X01\nProject 9");
}
//Enter Button Clicked
//Purpose: To store the info in an array when the button is pressed
//Parameters: The sending object and the event arguments
//Returns: nothing
private void button1_Click(object sender, EventArgs e)
{
//Get the information from the text box and store it in a variable
string userInput = nameTextBox.Text;
if (userInput != "")
{
//Create a new object with the parameterized constructor
// myBowlingTeam = new BowlingTeam(userInput);
//Split the string into two separte pieces of data
myBowlingTeam.SplitAndDisperseArray();
//Clear the text box
nameTextBox.Clear();
}
else
{
int highestScore = myBowlingTeam.CalcHighestScore();
}
}
//Nothing
private void nameTextBox_TextChanged(object sender, EventArgs e)
{
//Get the information from the text box and store it in a variable
string userInput = nameTextBox.Text;
//Create a new object with the parameterized constructor
myBowlingTeam = new BowlingTeam(userInput);
}
}
What is stopping you from using a class for the players inside the team? Keep the arrays synchronised in your solution seems more trouble than its worth.
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace Observable
{
class BowlingTeam
{
public string TeamName { get; set; }
private readonly IList<Player> players = new ObservableCollection<Player>();
public IList<Player> Players
{
get
{
return players;
}
}
public void AddPlayer(string name, int score)
{
AddPlayer(new Player(name, score));
}
public void AddPlayer(Player p)
{
players.Add(p);
}
public Player HighestRanked()
{
if (Players.Count == 0)
{
// no players
return null;
}
int max = 0, index = -1;
for (int i = 0; i < Players.Count; i++)
{
if (Players[i].Score > max)
{
index = i;
max = Players[i].Score;
}
}
if (index < 0)
{
// no players found with a score greater than 0
return null;
}
return Players[index];
}
public BowlingTeam()
{
}
public BowlingTeam(string teamName)
{
this.TeamName = teamName;
}
}
class Player
{
public string Name { get; set; }
public int Score { get; set; }
public Player()
{
}
public Player(string name, int score)
{
this.Name = name;
this.Score = score;
}
public override string ToString()
{
return string.Format("{0} {1:n2}", Name, Score);
}
}
}
which could be manipulated as such
BowlingTeam b1 = new BowlingTeam("SO");
b1.AddPlayer("Player 1", 100);
b1.AddPlayer("Player 2", 135);
b1.AddPlayer("Player 3", 90);
b1.AddPlayer("Player 4", 127);
Console.WriteLine("Highest ranked player: {0}", b1.HighestRanked());
An advantage for later is that you can hang on the OnCollectionChangedEvents of your players, to be notified when players were added/removed.
Related
I am looking to randomly generate 3 items using a loot table. The loot table currently works as expected, it will randomly generate an item based on the item's rarity. However, I don't want there to be duplicates of the same item. How can I set this up? This script is currently attached to 3 separate GameObject item pedestals.
using System.Collections.Generic;
using UnityEngine;
public class ShopItemSpawner : MonoBehaviour
{
[System.Serializable]
public class DropItem
{
public string name;
public GameObject item;
public int dropRarity;
}
public List<DropItem> ShopItemPool = new List<DropItem>();
private void Start()
{
int itemWeight = 0;
for (int i = 0; i < ShopItemPool.Count; i++)
{
itemWeight += ShopItemPool[i].dropRarity;
}
int randomValue = Random.Range(0, itemWeight);
for (int j = 0; j < ShopItemPool.Count; j++)
{
if (randomValue <= ShopItemPool[j].dropRarity)
{
Instantiate(ShopItemPool[j].item, transform.position, Quaternion.identity);
return;
}
randomValue -= ShopItemPool[j].dropRarity;
}
}
}
You could clone the ShopItemPool list and with each item rolled you remove that item from the list. You then need to go all over again by recalculating the total weight.
I find it useful to have a general purpose class for randomizing items with weights, it allows you do this this:
var randomizer = new WeightRandomizer<DropItem>();
foreach (var shopItem in ShopItemPool) {
randomizer.Add(shopItem, shopItem.dropRarity);
}
randomizer.Roll(); // Get a random element based on weight.
randomizer.Take(); // Get a random element based on weight and remove it from the randomizer.
General Purpose Weight Randomizer:
public class WeightRandomizer<T> {
[Serializable]
public class WeightedElement<T> {
public T value;
public int weight;
public WeightedElement (T value, int weight) {
this.value = value;
this.weight = weight;
}
}
private readonly List<WeightedElement<T>> elements = new();
public void Add (T value, int weight) => elements.Add(new WeightedElement<T>(value, weight));
public void AddRange (IEnumerable<WeightedElement<T>> weightedElements) => elements.AddRange(weightedElements);
public int TotalWeight() => elements.Sum(x => x.weight);
public T Roll() => Pick(false);
public T Take() => Pick(true);
private T Pick (bool remove) {
if (elements.Count == 0) {
Debug.LogWarning($"{nameof(WeightRandomizer<T>)} is missing elements.");
return default(T);
}
var roll = Random.Range(0, TotalWeight());
var selectedIndex = elements.Count - 1;
var selected = elements[selectedIndex].value;
for (var i = 0; i < elements.Count; i++) {
var element = elements[i];
// Found an element with a low enough value.
if (roll < element.weight) {
selected = element.value;
selectedIndex = i;
break;
}
// Keep searching for an element with a lower value.
roll -= element.weight;
}
// Sometimes we want to take and remove the element from the pool.
if (remove) elements.RemoveAt(selectedIndex);
return selected;
}
}
I've begun working on an early alpha menu for my game and I've was wondering how to exclude items in an array, specifically in unity. I'm trying to make every item except the currently used one. I don't know how I should go about it, if anyone could help, that would be amazing.
here's my current code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class CS
{
public List<GameObject> CanvasButtons;
}
public class CanvasSwitcher : MonoBehaviour
{
public List<CS> Screen = new List<CS>();
static int switcher;
public static void ScreenSwitchPlus()
{
switcher += 1;
}
public static void ScreenSwitchMinus()
{
switcher -= 1;
}
public void Update()
{
foreach(GameObject l in Screen[switcher].CanvasButtons)
{
l.SetActive(true);
}
}
}
It would be wiser to use for loop instead of foreach loop here:
public void Update()
{
int ignore = 2;
for(int i = 0; i < Screen[switcher].CanvasButtons.Count; i++)
{
if(i != ignore)
Screen[switcher].CanvasButtons[i].SetActive(true);
else
Screen[switcher].CanvasButtons[i].SetActive(false);
}
}
It could be even shorter without if (admit less readable):
public void Update()
{
int ignore = 2;
for(int i = 0; i < Screen[switcher].CanvasButtons.Count; i++)
{
Screen[switcher].CanvasButtons[i].SetActive(i != ignore);
}
}
... and even shorter with taking CanvasButtons out of loop:
public void Update()
{
int ignore = 2;
var collection = Screen[switcher].CanvasButtons;
for(int i = 0; i < collection.Count; i++)
{
collection[i].SetActive(i != ignore);
}
}
I got it! I was a bit null-brained for a while there, I messed up a few values in the second for statement, but I got it. I'll post the code here. I keep forgetting little things in the math. Like I always say, I don't solve problems, I make them.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class CS
{
public List<GameObject> CanvasButtons;
}
public class CanvasSwitcher : MonoBehaviour
{
public List<CS> Screen = new List<CS>();
static int switcher;
public static void ScreenSwitchPlus()
{
switcher += 1;
}
public static void ScreenSwitchMinus()
{
switcher -= 1;
}
public void FixedUpdate()
{
List<CS> csco = Screen;
for(int i1 = 0; i1 < csco.Count;)
{
List<GameObject> collection = csco[i1].CanvasButtons;
for (int i = 0; i < collection.Count; i++)
{
collection[i].SetActive(i1 == switcher);
switch(i == collection.Count - 1)
{
case true:
i1++;
break;
}
}
}
}
}
I think you are making things too complicated.
It could simply be
public void Update()
{
for(var i = 0; i < Screen.Count; i++)
{
foreach(var button in Screen[i].CanvasButtons)
{
button.SetActive(i == switcher);
}
}
}
Two more points though.
First I would make sure that switcher is actually a valid value. You either want to clamp the value to stay within the index range like
public static void ScreenSwitchPlus()
{
switcher = Mathf.Clamp(switcher + 1, 0, Screen.Count);
}
public static void ScreenSwitchMinus()
{
switcher = Mathf.Clamp(switcher - 1, 0, Screen.Count);
}
or you could implement wrap around at the ends according to your needs like
public static void ScreenSwitchPlus()
{
switcher = (switcher + 1) % Screen.Count;
}
public static void ScreenSwitchMinus()
{
switcher -= 1;
if(switcher < 0) switcher = Screen.Count - 1;
}
and then finally as mentioned I wouldn't do this poll fetching the value in Update every frame at all but rather event driven.
If you really need to (I would claim it is just lazyness ;) ) have that value and methods static you could attach to an event like
private static event Action<int> OnSwitcherChanged;
public static void ScreenSwitchPlus()
{
switcher = (switcher + 1) % Screen.Count;
OnSwitcherChanged?.Invoke(switcher);
}
public static void ScreenSwitchMinus()
{
switcher -= 1;
if(switcher < 0) switcher = Screen.Count - 1;
OnSwitcherChanged?.Invoke(switcher);
}
and then listen to that event like
private void OnEnable()
{
OnSwitcherChanged += HandleSwitchChanged;
}
private void OnDisable()
{
OnSwitcherChanged -= HandleSwitchChanged;
}
private void HandleSwitchChanged(int newIndex)
{
for(var i = 0; i < Screen.Count; i++)
{
foreach(var button in Screen[i].CanvasButtons)
{
button.SetActive(i == switcher);
}
}
}
Try this
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class CS {
public List<GameObject> CanvasButtons;
}
public class CanvasSwitcher : MonoBehaviour {
public List<CS> Screen = new List<CS>();
private static bool m_changed = false;
private static int m_lastSwitcher = 0;
private static int m_switcher = 0;
static int switcher {
get {
return m_switcher;
}
set {
if ( switcher != value ) {
m_lastSwitcher = m_switcher;
m_changed = true;
m_switcher = value;
}
}
}
public static void ScreenSwitchPlus() {
switcher += 1;
}
public static void ScreenSwitchMinus() {
switcher -= 1;
}
private void Update() {
if ( m_changed ) {
UpdateCS();
m_changed = false;
}
}
void UpdateCS() {
if ( m_lastSwitcher < Screen.Count ) {
var canvasBtns = Screen[ m_lastSwitcher ].CanvasButtons;
for ( int i = 0; i < canvasBtns.Count; i++ ) {
canvasBtns[ i ].SetActive( false );
}
}
if ( switcher < Screen.Count ) {
var canvasBtns = Screen[ switcher ].CanvasButtons;
for ( int i = 0; i < canvasBtns.Count; i++ ) {
canvasBtns[ i ].SetActive( true );
}
}
}
}
New to c# need help with the following error.
In class Grybai there is an error in Print case 'svoris' does not exist in current context. Print(A, ref n, Svoris); third argument 'Svoris' gives an error.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace C
{
class Grybai
{
public string name;
private int Svoris;
public void Tipas(string nameType, int Weight) { name = nameType; Svoris = Weight; }
public string GetName() { return name; }
public int GetWeight() { return Svoris; }
Tried to do with GetWeight method, still nothing...
}
class Program
{
const string CFd = "..//..//Duom.txt";
const string CFr = "..//..//Rez.txt";
//Duomenu nuskaitymas is failo i masyva
static void Main(string[] args)
{
Grybai[] A = new Grybai[10]; //Sukuriam strukturu masyva
int n = 0;
Read(A, ref n);
Print(A, ref n, Svoris);
The name Svoris does not exist in current context, how to fix it?
}
static void Read(Grybai[] tarp, ref int n)
{
using (StreamReader reader = new StreamReader(CFd))
{
string line;
string[] parts;
if (File.Exists(CFr)) File.Delete(CFr);
while ((line = reader.ReadLine()) != null)
{
parts = line.Split(' ');
tarp[n] = new Grybai();
tarp[n].Tipas(parts[0], int.Parse(parts[1]));
n++;
}
}
}
static void Sort(Grybai[] tarpA, int n)
{
Grybai tarpB;
for (int j = 0; j < n; j++)
{
for (int i = 0; i < n - 1; i++)
{
if (tarpA[i].GetName()[0] > tarpA[i + 1].GetName()[0])
{
tarpB = tarpA[i];
tarpA[i] = tarpA[i + 1];
tarpA[i + 1] = tarpB;
}
}
}
}
static void Print(Grybai[] tarp, int n, int svoris)
{
string top = "|-----------------------------------------------------------|\r\n" +
"| Surusiuoti duomenys |\r\n" +
"|-----------------------------------------------------------|\r\n" +
"|Pavadinimas |Tipas |Svoris |\r\n" +
"|-----------------------------------------------------------|";
In order to resolves argument error on 'Svoris', you can replace a line of code as below.
Old Code : Print(A, ref n, Svoris);
New Code : Print(A, ref n, A.GetWeight());
As per your code, GetWeight() returns value of Svoris. It serves the intended purpose.
private int Svoris;
You "Svoris" is a private class viarable in "Grybai" class. You can't just access it like that in the "Program" class.
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 5 years ago.
thanks for reading, I am working on a small memory card game in C# using Unity. When I run a certain scene I am receiving constant errors.
The errors are as follows:
"NullReferenceException: Object reference not set to an instance of an object
Card.SetUpArt () (at Assets/Scripts/Card.cs:31)
Pairs.SetUpDeck () (at Assets/Scripts/Pairs.cs:62)
Pairs.Update () (at Assets/Scripts/Pairs.cs:23)"
My code is:
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
public class Card : MonoBehaviour {
public static bool NO_TURN = false;
[SerializeField]
private int cardState; //state of card
[SerializeField]
private int cardNumber; //Card value (1-13)
[SerializeField]
private bool _setUp = false;
private Sprite cBack; //card back (Green square)
private Sprite cFace; //card face (1-10 JQKA)
private GameObject pairsManager;
void Begin()
{
cardState = 1; //cards face down
pairsManager = GameObject.FindGameObjectWithTag("PairsManager");
}
public void SetUpArt()
{
cBack = pairsManager.GetComponent<Pairs>().GetBack(); //<--error
cFace = pairsManager.GetComponent<Pairs>().GetFace(cardNumber);
turnCard();//turns the card
}
public void turnCard() //handles turning of card
{
if (cardState == 0)
{
cardState = 1;
}
else if(cardState == 1)
{
cardState = 0;
}
if (cardState == 0 && !NO_TURN)
{
GetComponent<Image>().sprite = cBack; // shows card back
}
else if (cardState == 1 && !NO_TURN)
{
GetComponent<Image>().sprite = cFace; // shows card front
}
}
//setters and getters
public int Number
{
get {return cardNumber;}
set { cardNumber = value;}
}
public int State
{
get { return cardState; }
set { cardState = value; }
}
public bool SetUp
{
get { return _setUp; }
set { _setUp = value; }
}
public void PairCheck()
{
StartCoroutine(pause ());
}
IEnumerator pause()
{
yield return new WaitForSeconds(1);
if (cardState == 0)
{
GetComponent<Image>().sprite = cBack;
}
else if (cardState == 1)
{
GetComponent<Image>().sprite = cFace;
}
}
}
And:
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using UnityEngine;
public class Pairs : MonoBehaviour {
public Sprite[] cardFace; //array of card faces
public Sprite cardBack;
public GameObject[] deck; //array of deck
public Text pairsCount;
private bool deckSetUp = false;
private int pairsLeft = 13;
// Update is called once per frame
void Update () {
if (!deckSetUp)
{
SetUpDeck();
}
if (Input.GetMouseButtonUp(0)) //detects left click
{
CheckDeck();
}
}//Update
void SetUpDeck()
{
for(int i = 0; i <deck.Length; i++)//resets cards
{
deck[i].GetComponent<Card>().SetUp = false;
}
for (int ix = 0; ix < 2; ix++) //sets up cards twice,
{
for(int i = 1; i < 14; i++)//sets up card value (2-10 JQKA)
{
bool test = false;
int val = 0;
while (!test)
{
val = Random.Range(0, deck.Length);
test = !(deck[val].GetComponent<Card>().SetUp);
}//while
//sets up cards
deck[val].GetComponent<Card>().Number = i;
deck[val].GetComponent<Card>().SetUp = true;
}//nested for
}//for
foreach (GameObject crd in deck)
{
crd.GetComponent<Card>().SetUpArt();
}
if (!deckSetUp)
{
deckSetUp = true;
}
}//SetUpDeck
public Sprite GetBack()
{
return cardBack;
}//getBack
public Sprite GetFace(int i)
{
return cardFace[i - 1];
}//getFace
void CheckDeck()
{
List < int > crd = new List<int>();
for(int i = 0; i < deck.Length; i++)
{
if(deck[i].GetComponent<Card>().State == 1)
{
crd.Add(i);
}
}
if(crd.Count == 2)
{
CompareCards(crd);
}
}//CheckDeck
void CompareCards(List<int> crd)
{
Card.NO_TURN = true; //stops cards turning
int x = 0;
if(deck[crd[0]].GetComponent<Card>().Number ==
deck[crd[1]].GetComponent<Card>().Number)
{
x = 2;
pairsLeft--;
pairsCount.text = "PAIRS REMAINING: " + pairsLeft;
if(pairsLeft == 0) // goes to home screen when game has been won
{
SceneManager.LoadScene("Home");
}
}
for(int j = 0; j < crd.Count; j++)
{
deck[crd[j]].GetComponent<Card>().State = x;
deck[crd[j]].GetComponent<Card>().PairCheck();
}
}//CompareCards
}
Any help anyone can offer would be greatly appreciated. Thank you in advance.
Link to GitHub Repository
I don't have knowledge about C#, as I'm working with java. You should initialize your variables. For more information I found this link What is a NullReferenceException, and how do I fix it?
Im recently studying c# and want to create a 'simple' console app poker game.
Ive created classes: player, hand, deck, dealer. Dealer gets cards out of the deck and assigns it to player instances. What I'm struggling with now is how to progress further? I need to make some gameplay possible.
This is what i have coded thusfar:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication10
{
class Program
{
static void Main(string[] args)
{
//Deck d = new Deck();
Player[] players = new Player[2];
Dealer dealer = new Dealer();
players[0] = new Player("M");
players[1] = new Player("T");
foreach (var player in players)
{
Console.WriteLine(player.name);
}
Console.WriteLine();
foreach (var player in players)
{
player.AddCardsToHand(dealer);
}
Console.WriteLine("View hand van player 1");
foreach (string card in players[0].ViewHandCards())
{
Console.WriteLine(card);
}
Console.WriteLine();
Console.WriteLine("View hand van player 2");
foreach (string card in players[1].ViewHandCards())
{
Console.WriteLine(card);
}
Console.WriteLine();
Console.WriteLine("Number of players instantiated:");
Console.WriteLine(Player.playerCount);
Console.WriteLine();
Console.WriteLine("Number of hands instantiated:");
Console.WriteLine(Hand.handCount);
Console.WriteLine();
dealer.SetMoneyAmount(players[0]);
dealer.SetMoneyAmount(players[1], 150);
Console.WriteLine("Money player 1:");
Console.WriteLine(players[0].MoneyAmount);
Console.WriteLine();
Console.WriteLine("Money player 2:");
Console.WriteLine(players[1].MoneyAmount);
Console.WriteLine();
int index = 0;
dealer.SetDealer(players[index]);
Console.WriteLine("Dealer: " + dealer.GetDealer());
// how to know in a class how many players there are and there values?
// create a class containing the players array?
}
}
class Settings
{
// static string dealer;
public static int dealerIndex;
public static string dealerName;
public
}
class User
{
public string name;
}
class Player : User
{
Hand h = new Hand();
public static int playerCount;
private double moneyAmount;
public bool dealerButton;
public double MoneyAmount
{
get
{
return moneyAmount;
}
set
{
moneyAmount = value;
}
}
public int NumOfCardsInHand()
{
return h.cardsInHand;
}
public string[] ViewHandCards()
{
return h.handCards;
}
public void AddCardsToHand(Dealer d)
{
d.DealCard(h);
d.DealCard(h);
}
public Player(string n)
{
this.name = n;
playerCount++;
}
}
class Hand
{
public static int handCount;
public int cardsInHand = 0;
public string[] handCards = new string[2];
public Hand()
{
handCount++;
}
}
class Dealer
{
Deck d = new Deck();
//public void StartGame()
//{
//}
public void DealCard(Hand h)
{
if (h.cardsInHand < 2)
{
if (h.cardsInHand == 0)
h.handCards[0] = d.NextCard();
if (h.cardsInHand == 1)
h.handCards[1] = d.NextCard();
h.cardsInHand++;
}
else
{
Console.WriteLine("Meer dan 2 kaarten per hand is niet toegestaan");
}
}
public void SetMoneyAmount(Player p, double amount = 100)
{
p.MoneyAmount = amount;
}
public void SetDealer(Player p)
{
p.dealerButton = true;
Settings.dealerName = p.name;
}
public string GetDealer()
{
return Settings.dealerName;
}
}
class Deck
{
public int numOfCards = 52;
public string[] cards = new string[13];
public string[] playingCards = new string[52];
public string[] cardsDealt = new string[52];
Random r = new Random();
int y = 0;
public string NextCard()
{
string nextCard = "-";
int x = 0;
while (x < 1)
{
nextCard = playingCards[r.Next(0, playingCards.Length)];
if (!cardsDealt.Contains(nextCard))
{
cardsDealt[y] = nextCard;
y++;
x++;
}
else
{
Console.WriteLine("Reeds gedeelde kaart bijna opnieuw gedeeld!");
x = 0;
}
}
return nextCard;
}
public void ConstructDeck()
{
// spade club heart diamond
this.cards[0] = "A";
this.cards[1] = "K";
this.cards[2] = "Q";
this.cards[3] = "J";
this.cards[4] = "10";
this.cards[5] = "9";
this.cards[6] = "8";
this.cards[7] = "7";
this.cards[8] = "6";
this.cards[9] = "5";
this.cards[10] = "4";
this.cards[11] = "3";
this.cards[12] = "2";
int x = 0;
foreach (string card in this.cards)
{
this.playingCards[x] = card + "s";
x++;
this.playingCards[x] = card + "c";
x++;
this.playingCards[x] = card + "h";
x++;
this.playingCards[x] = card + "d";
x++;
}
}
public Deck()
{
ConstructDeck();
}
}
class Bet
{
public double betAmount;
public Bet(Player p, double betInput)
{
betAmount = betInput;
}
}
}
I have put the player instances in an array and can call them like this players[0] (player 1).
I would like to know if im on the right track here and more specifically how do I keep track of the players I instantiated so that other classes can access the player instance variables? Im assigning one player the dealer status and would need to know where to start asking for other players initiative in the game like needing to bet call check or fold at some given point. I dont know what kind of classes I would need to create for a preflop game, a flop game, a turn game and the river game. Classes for each game name? How would I check if a player finished his action?
I think I should create a class like: preflopgame and identify the dealer than ask initiative (bet fold etc (make classes of betting folding checking etc) of the player thats not the dealer and keep track via a variable that player finished its initiative in the preflopgame class? And if preflopgame is played out: some kind of static boolean field in the class indicating its finished. Than move on to the next game: flopgame. Is this the right way of thinking about this game?
Any suggestions would certainly be much apreciated.
Excuse my English im Dutch from origin.