How to use polymorphism instead of generic in C# - c#

I have a generic base Interface IGameble (for the example move is generic) and Classes: Chess and Tic-Tac-Toe (and more board games) which derived from the generic Interface IGmable but are no longer generic.
I want to design class Agent (there might be several kind of these) that will play any kind of game (not in the same time), but the problem is that I cant
for example:
interface IGame<T_move,T_matrix>
{
T_matrix[,] game_state { get; }
void MakeMove(Move mov);
List<Move> ListAllMoves();
...// some more irrelevant code
}
class Tic_Tac_Toe : IGameble<Tuple<int,int>,int>
{
public int turn;
public int[,] game_state;
public List<Tuple<int,int>> ListAllMoves() {...}
public void MakeMove(Tuple<int,int> mov) {...}
}
public Chess : IGameble <some other kind> //...
// so on more classes which uses other kind in the generic.
interface IAgent<Move>
{
Move MakeMove();
}
public RandomAgent<T_Move,T_Matrix> : IAgent
{
public IGameble<T_move> game;
public D(IGameble game_) {game = game_}
public T_Move MakeMove() {//randomly select a move}
}
public UserAgent<T_Move,T_Matrix> : IAgent {get the move from the user}
The problems is that I want 1 instance of the random agent (or any other agent) to play all the games (1 game at a time) and using the generic enforce me to specifically choose the types of T_Move and T_Matrix that I want to use.
I might have it all wrong and used the generic poorly.
There was a suggestion to use IMovable and IBoardable instead of the generic. Is it the correct design? Would it solve all the problems?
I'm still a noobie in design pattern in C# :(
Also I will be appreciate it very much if some one can get a link to some design pattern that can help me here (if there is one..).

I think you can just use the is keyword:
public D(IA<T> a_)
{
if (a_ is B)
{
//do something
}
else if (a_ is C)
{
//do something else
}
}
Generics in C# aren't nearly as flexible as C++, so as some commenters pointed out, you may not want to do things this way. You may want to design an intermediate interface, say IMove, that your algorithm can use to enumerate the moves in a generic way.

I don't know is that what you want, but you can do it without generics.
Sample code:
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main (string[] args)
{
var game = new TicTacToe (
(x) => new UserAgent (x, "John"),
(x) => new RandomAgent (x));
game.Play ();
Console.ReadKey ();
}
}
public interface IGame
{
IMove[] GetAvailableMoves ();
}
public interface IMove
{
void MakeMove ();
string Description { get; }
}
public interface IAgent
{
string Name { get; }
IMove SelectMove ();
}
public delegate IAgent AgentCreator (IGame game);
public class RandomAgent : IAgent
{
private readonly IGame game;
private readonly Random random = new Random ();
public RandomAgent (IGame game)
{
this.game = game;
}
public string Name => "Computer (random moves)";
public IMove SelectMove ()
{
var availableMoves = game.GetAvailableMoves ();
int moveIndex = random.Next (availableMoves.Length);
return availableMoves[moveIndex];
}
}
public class UserAgent : IAgent
{
private readonly IGame game;
public UserAgent (IGame game, string playerName)
{
this.game = game;
Name = playerName;
}
public string Name { get; }
public IMove SelectMove ()
{
var availableMoves = game.GetAvailableMoves ();
Console.WriteLine ("Choose your move:");
for (int i = 0; i < availableMoves.Length; i++)
{
Console.WriteLine (i + " " + availableMoves[i].Description);
}
int selectedIndex = int.Parse (Console.ReadLine ());
return availableMoves[selectedIndex];
}
}
public class TicTacToe : IGame
{
enum CellState { Empty = 0, Circle, Cross }
CellState[] board = new CellState[9]; // 3x3 board
int currentPlayer = 0;
private IAgent player1, player2;
public TicTacToe (AgentCreator createPlayer1, AgentCreator createPlayer2)
{
player1 = createPlayer1 (this);
player2 = createPlayer2 (this);
}
public void Play ()
{
PrintBoard ();
while (GetAvailableMoves ().Length > 0)
{
IAgent agent = currentPlayer == 0 ? player1 : player2;
Console.WriteLine ($"{agent.Name} is doing a move...");
var move = agent.SelectMove ();
Console.WriteLine ("Selected move: " + move.Description);
move.MakeMove (); // apply move
PrintBoard ();
if (IsGameOver ()) break;
currentPlayer = currentPlayer == 0 ? 1 : 0;
}
Console.Write ("Game over. Winner is = ..."); // some logic to determine winner
}
public bool IsGameOver ()
{
return false;
}
public IMove[] GetAvailableMoves ()
{
var result = new List<IMove> ();
for (int i = 0; i < 9; i++)
{
var cell = board[i];
if (cell != CellState.Empty) continue;
int index = i;
int xpos = (i % 3) + 1;
int ypos = (i / 3) + 1;
var move = new Move ($"Set {CurrentPlayerSign} on ({xpos},{ypos})", () =>
{
board[index] = currentPlayer == 0 ? CellState.Cross : CellState.Circle;
});
result.Add (move);
}
return result.ToArray ();
}
private char CurrentPlayerSign => currentPlayer == 0 ? 'X' : 'O';
public void PrintBoard ()
{
Console.WriteLine ("Current board state:");
var b = board.Select (x => x == CellState.Empty ? "." : x == CellState.Cross ? "X" : "O").ToArray ();
Console.WriteLine ($"{b[0]}{b[1]}{b[2]}\r\n{b[3]}{b[4]}{b[5]}\r\n{b[6]}{b[7]}{b[8]}");
}
}
public class Move : IMove // Generic move, you can also create more specified moves like ChessMove, TicTacToeMove etc. if required
{
private readonly Action moveLogic;
public Move (string moveDescription, Action moveLogic)
{
this.moveLogic = moveLogic;
Description = moveDescription;
}
public string Description { get; }
public void MakeMove () => moveLogic.Invoke ();
}
}

Related

C# Unity Inventory - List.FindAll() not working as expected

I am super new to C#, so apologies if this is a simple question or has already been answered. I've been looking at other SO questions, trying the exact methods they use, and am still having no luck.
In Unity, I have an Inventory Object class that I can use to create Inventories in my game:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "New Inventory", menuName = "Inventory System/Inventory")]
public class InventoryObject : ScriptableObject
{
public List<InventorySlot> Container = new List<InventorySlot>();
public void AddItem(ItemObject newItem, int itemAmount)
{
bool inventoryHasItem = false;
for (int i = 0; i < Container.Count; i++)
{
if (CurrentSlotHasItem(Container[i], newItem)) {
if (Container.FindAll((InventorySlot currentSlot) => CurrentSlotHasItem(currentSlot, newItem)).Count < newItem.maxStackSize)
{
Container[i].AddAmount(itemAmount);
inventoryHasItem = true;
break;
}
}
}
if (!inventoryHasItem)
{
Container.Add(new InventorySlot(newItem, itemAmount));
}
}
private bool CurrentSlotHasItem(InventorySlot currentSlot, ItemObject item)
{
return currentSlot.item == item;
}
}
[System.Serializable]
public class InventorySlot
{
public ItemObject item;
public int amount;
public InventorySlot(ItemObject _item, int _amount)
{
item = _item;
amount = _amount;
}
public void AddAmount(int value)
{
amount += value;
}
}
This works great, except for this line:
Container.FindAll((InventorySlot currentSlot) => CurrentSlotHasItem(currentSlot, newItem)).Count < newItem.maxStackSize
For some reason, no matter what I use for the findAll() predicate, I always get the same amount in my inspector - 1. Which means that .Count never goes above 1, and I can go way above my ItemObject.maxStackSize.
This is an example ItemObject class I have:
using UnityEngine;
[CreateAssetMenu(fileName = "New Food Object", menuName = "Inventory System/Items/Food")]
public class FoodObject : ItemObject
{
public int healthAmount;
private void Awake() {
type = ItemType.Food;
maxStackSize = 25;
}
}
This is also my Player script that adds the items to the inventory. It just adds them based off of OnTriggerEnter.
public class Player : MonoBehaviour
{
public InventoryObject inventory;
private void OnTriggerEnter(Collider other)
{
var item = other.GetComponent<Item>();
if (item)
{
inventory.AddItem(item.item, 1);
Destroy(other.gameObject);
}
}
}
Here's some screenshots of my Unity console/inspector, with these two lines added to my InventoryObject class. You can see that .Count never going above 1.
if (CurrentSlotHasItem(Container[i], newItem)) {
Debug.Log(Container.FindAll((InventorySlot currentSlot) => CurrentSlotHasItem(currentSlot, newItem)).Count);
Debug.Log(Container[i].amount);
// rest of class
I don't know what I was thinking here. All I needed to do to get maxStackSize to work was changing the logic inside of AddItem:
for (int i = 0; i < Container.Count; i++)
{
if (Container[i].item.id == newItem.id) {
if (Container[i].amount < newItem.maxStackSize)
{
Container[i].AddAmount(itemAmount);
inventoryHasItem = true;
break;
}
}
}
It just compares Container[i].amount to newItem.maxStackSize. If it's under, it will stack the item. Otherwise, it creates a new item in the inventory.

The type or namespace name 'SyncListString' could not be found (are you missing a using directive or an assembly reference? in mirror

Hey i am beginer and i am making a multiplayer game using mirror by watching https://www.youtube.com/watch?v=w0Dzb4axdcw&list=PLDI3FQoanpm1X-HQI-SVkPqJEgcRwtu7M&index=3 this video in this video he has maded match maker script and i have maded it step by step but don't know why i am getting this error i have seen code many times and all the things are same but he is not getting any error but i am plzz help this is my code and plzz explain in simply i am beginner
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mirror;
namespace MirrorBasics {
[System.Serializable]
public class Match {
public string matchID;
public SyncListGameObject players = new SyncListGameObject ();
public Match(string matchID, GameObject player) {
this.matchID = matchID;
players.Add (player);
}
public Match () { }
}
[System.Serializable]
public class SyncListGameObject : SyncList<GameObject> { }
[System.Serializable]
public class SyncListMatch : SyncList<Match> { }
public class MatchMaker : NetworkBehaviour {
public static MatchMaker instance;
public SyncListMatch matches = new SyncListMatch ();
public SyncListString matchIDs = new SyncListString ();
void Start() {
instance = this;
}
public bool HostGame (string _matchID, GameObject _player) {
if (!matchIDs.Contains(_matchID)) {
matchIDs.Add (_matchID) ;
matches.Add (new Match (_matchID, _player));
Debug.Log ($"Match generated");
return true;
} else {
Debug.Log ($"Match ID already exists");
return false;
}
}
public static string GetRandomMatchID () {
string _id = string.Empty;
for (int i = 0; i < 5; i++) {
int random = Random.Range(0, 36);
if (random < 26) {
_id += (char)(random + 65);
} else {
_id += (random - 26).ToString ();
}
}
Debug.Log($"Random Match ID: {_id}");
return _id;
}
}
}
Like SyncListGameObject create SyncList with string like this.
public class SyncListString: SyncList<string>()
Then
public SyncListString matchIDs = new SyncListString();
I made lobby/matchmaking by this tutorial too :)

Dynamic Scramble Game using Unity C# and PHP (Mysql as database)

I have here codes that scramble declared words based on this video.Below are the codes that depends on array of words I declared on Unity Editor. The problem is I want it to be dynamic, like it will fetch words into database. I wrote a code in php that retrieves data from db and a code on csharp that reads the php via WWW method. I can't merge this two process- scramble words and getting words from db, Please help me guys, Thank you.
this is my Unity setup for scramble word. as you can see I attached WordScrambe.cs to Core Gameobject and declared 2 words-"YES" and "YOURS".
CharObject.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CharObject : MonoBehaviour {
public char character;
public Text text;
public Image image;
public RectTransform rectTransform;
public int index;
[Header("Appearance")]
public Color normalColor;
public Color selectedColor;
bool isSelected= false;
public CharObject Init(char c)
{
character = c;
text.text = c.ToString ();
gameObject.SetActive (true);
return this;
}
public void Select()
{
isSelected = !isSelected;
image.color = isSelected ? selectedColor : normalColor;
if (isSelected) {
WordScramble.main.Select (this);
} else {
WordScramble.main.UnSelect();
}
}
}
WordScramble.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Word
{
public string word;
[Header("leave empty if you want randomized")]
public string desiredRandom;
public string GetString()
{
if (!string.IsNullOrEmpty (desiredRandom))
{
return desiredRandom;
}
string result = word;
while (result==word)
{
result = "";
List<char> characters = new List<char> (word.ToCharArray ());
while (characters.Count > 0)
{
int indexChar = Random.Range (0, characters.Count - 1);
//Debug.Log(characters[indexChar]);
result += characters [indexChar];
Debug.Log(word);
characters.RemoveAt (indexChar);
}
}
return result;
}// end of Getstring Method
}
public class WordScramble : MonoBehaviour {
public Word[] words;
[Header("UI REFERENCE")]
public CharObject prefab;
public Transform container;
public float space;
public float lerpSpeed=5;
List<CharObject> charobjects = new List<CharObject>();
CharObject firstSelected;
public int currentWord;
public static WordScramble main;
void Awake()
{
main = this;
}
// Use this for initialization
void Start () {
ShowScramble (currentWord);
}
// Update is called once per frame
void Update ()
{
RepositionObject ();
}
void RepositionObject()
{
if (charobjects.Count==0) {
return;
}
float center = (charobjects.Count -1) / 2;
for (int i = 0; i < charobjects.Count; i++)
{
charobjects[i].rectTransform.anchoredPosition= Vector2.Lerp(charobjects[i].rectTransform.anchoredPosition, new Vector2((i- center)* space, 0), lerpSpeed* Time.deltaTime) ;
charobjects [i].index = i;
}
}
//show a random word to the screen
public void ShowScramble()
{
ShowScramble (Random.Range (0, words.Length - 1));
}
//<summary>Show word from collection with desired index
public void ShowScramble(int index)
{
charobjects.Clear ();
foreach (Transform child in container) {
Destroy (child.gameObject);
}
//Words Finished
if (index > words.Length - 1) {
Debug.LogError ("index out of range, please enter range betwen 0-" + (words.Length - 1).ToString ());
return;
}
char[] chars = words [index].GetString ().ToCharArray ();
foreach (char c in chars)
{
CharObject clone = Instantiate (prefab.gameObject).GetComponent<CharObject> ();
clone.transform.SetParent (container);
charobjects.Add (clone.Init (c));
}
currentWord = index;
}
public void Swap(int indexA, int indexB)
{
CharObject tmpA = charobjects [indexA];
charobjects[indexA] = charobjects [indexB];
charobjects[indexB] = tmpA;
charobjects [indexA].transform.SetAsLastSibling ();
charobjects [indexB].transform.SetAsLastSibling ();
CheckWord ();
}
public void Select(CharObject charObject)
{
if (firstSelected)
{
Swap (firstSelected.index, charObject.index);
//Unselect
firstSelected.Select();
charObject.Select();
} else {
firstSelected = charObject;
}
}
public void UnSelect()
{
firstSelected = null;
}
public void CheckWord()
{
StartCoroutine (CoCheckWord());
}
IEnumerator CoCheckWord()
{
yield return new WaitForSeconds (0.5f);
string word = "";
foreach (CharObject charObject in charobjects)
{
word += charObject.character;
}
if (word == words [currentWord].word) {
currentWord++;
ShowScramble (currentWord);
}
}
}
Below are the codes for retrieving data from db using PHP and passing data to unity.
read.php
<?php
include '../../connection.php';
$query=mysqli_query($conn, "SELECT * FROM words");
while($fetch=mysqli_fetch_array($query)){
echo $get=$fetch["words"];
echo ",";
}
?>
fetch.cs-I attached this to Main Camera on Unity Editor for the mean time.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class fetch : MonoBehaviour {
public string[] dbWords;
IEnumerator Start(){
WWW words=new WWW("http://localhost/bootstrap/android/v2/read.php");
yield return words;
string wordsDataString=words.text;
print(wordsDataString);
dbWords=wordsDataString.Split(',');
}
}
In short I want to make a scramble game in unity that the words of it depends on the database . I have the process of word scramble(but static) and retrieving data from database but not connected to scramble game I made, means my project is not yet dynamic, I'm sorry for uncleared explanations.
Thank you and more power! :)
Welcome to SO!
It is not entirely clear where your problem lies, however I think you mean to say that you are not receiving a result from your database?
Let's start by moving your Database logic to a separate class for good practice.
Also the Start Method of a MonoBehaviour is of returntype void, and not an IENumerator. You need an IENumerator, which you can call with StartCoroutine.
Create a seperate class like below
public static class NetworkManager
{
public static IEnumerator Fetch(Action<string[]> callback)
{
WWW words=new WWW("http://localhost/bootstrap/android/v2/read.php");
yield return words;
string wordsDataString=words.text;
print(wordsDataString);
var result = wordsDataString.Split(',');
callback?.Invoke(result);
}
}
I cannot test your code that you had in your Fetch method because you are using it locally, but let's assume it works for now.
Notice the callback as a parameter.
This allows you to register an action that will fire once your database call is completed.
It is invoked in the last line of the method.
You can then call the method like this:
public class SomeClass : MonoBehaviour
{
StartCoroutine(NetworkManager.Fetch( (words) =>
{
// Do something with the words!
SomeMethod(words);
});
}
As soon as the Coroutine finishes, any code between the brackets is executed. In this case "SomeMethod" accepting words as a parameter will fire.
I hope this clarifies and answers your question!

Array.Indexof confusion

Hellos guys I am a beginner and have 2 classes. Class A has an Array that I need to access in Class B. I've searched through here for the past 36 hours trying different methods and this is what I ended up with any help?
This is the first Class with the Array
[System.Serializable]
public class Cli
{
public string name;
public int money;
};
public class BankManager : MonoBehaviour
{
private static BankManager _instance;
public static BankManager Instance
{
get
{
if (_instance == null)
{
GameObject go = new GameObject("BankManager");
go.AddComponent<BankManager>();
}
return _instance;
}
}
public GameObject player;
private string NaMe;
public Bank[] banks = new Bank[1];
public Cli[] clients = new Cli[1];
void Awake()
{
_instance = this;
}
void Start()
{
banks[0] = new Bank("In But Not Out", 10000);
player = GameObject.Find("Player");
clients[0].money = 1000;
}
void Update()
{
PlayerController pName = player.GetComponent<PlayerController>();
clients[0].name = pName.name;
}
}
The array I am trying to access is the clients[]
public class AccessAtm : MonoBehaviour
{
public Bank bank;
public int clams;
private void OnTriggerEnter2D(Collider2D other)
{
bank = BankManager.Instance.banks[0];
if (other.tag == "Player")
{
clams = Array.IndexOf(BankManager.Instance.clients,
other.GetComponent<PlayerController>().name);
Debug.Log(other.GetComponent<PlayerController>().name);
}
}
}
The debug.log properly tells me I'm getting the player.name I believe my error is in either getting that instance of the array or in the indexof command
The problem is IndexOf expects you to pass a instance of Bank for the 2nd parameter of
clams = Array.IndexOf(BankManager.Instance.clients,
other.GetComponent<PlayerController>().name);
you are passing it a string.
You need to use something else to search for it, the easist solution would be use a for loop.
var clients = BankManager.Instance.clients;
var otherName = other.GetComponent<PlayerController>().name;
int foundAt = -1;
for(int i = 0; i < clients.Length; i++)
{
if(clients[i].name == otherName)
{
foundAt = i;
break;
}
}
claims = foundAt;

C# Poker: how to keep track of players and make game engine (classes) preflop, flop, turn, river?

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.

Categories

Resources