How to use bool operator in - c#

My main problem is, how do I send the index to my bool operator?
I tried doing int = 0; and then this player.GetPlayer(i++).KA in my PlayerContainer class, but i = 0 all the time.
player.GetPlayer(i).KA is player's Kills+Assists, if that makes it more understandable.
This code is PlayerContainer.cs class.
class PlayerContainer {
public Player[] Players;
public int Count {
get;
set;
}
public int cycle {
get;
set;
}
public DateTime date {
get;
set;
}
public PlayerContainer(int size) {
Players = new Player[size];
}
public void AddPlayer(Player player) {
Players[Count++] = player;
}
public void AddPlayer(Player player, int index) {
Players[index] = player;
}
public Player GetPlayer(int index) {
return Players[index];
}
public static bool operator < (int max, PlayerContainer player) {
if (max < player.GetPlayer(i++).KA) {
return true;
} else
return false;
}
public static bool operator > (int max, PlayerContainer player) {
int i = 0;
if (max < player.GetPlayer(i++).KA)
return true;
else
return false;
}
This is in a Method BestPlayer in my Program.cs class
Player BestPlayer(PlayerContainer AllPlayers) {
Player player = AllPlayers.GetPlayer(0);
int max = AllPlayers.GetPlayer(0).KA;
for (int i = 0; i < AllPlayers.Count; i++) {
if (max < AllPlayers) {
max = AllPlayers.GetPlayer(i).KA;
player = AllPlayers.GetPlayer(i);
}
}
return player;
}

Player BestPlayer(PlayerContainer AllPlayers)
{
Player player;
int max = AllPlayers.GetPlayer(0).KA;
Player best = AllPlayers.GetPlayer(0);
int tmp;
for (int i = 1; i < AllPlayers.Count; i++)
{
tmp = AllPlayers.GetPlayer(i).KA;
player = AllPlayers.GetPlayer(i);
if (tmp > AllPlayers)
{
max = tmp;
best = player;
}
}
return best;
}

Related

Reverse timer to increase life

I created a reverse timer for the system of lives. i.e., life should be added after 00:00 if the field is empty. I need the timer to work before all the hearts are full, i.e. when one heart is full, the timer turns on again, if all the hearts are in place, then it's just 00:00. I did this:
public int lives;
public int maxLives;
public Image[] Live;
public Sprite FullHearts;
public Sprite EmptyHearts;
//Timer
[SerializeField] private int minutes;
[SerializeField] private int seconds;
private int m, s;
[SerializeField]
private Text timerText;
private void updateTimer()
{
s--;
if (s < 0)
{
if (m == 0)
{
stopTimer();
return;
}
else {
m --;
s= 59;
}
}
writeTimer(m, s);
Invoke("updateTimer", 1f);
}
public void writeTimer(int m, int s) {
if (s < 10)
{
timerText.text = m.ToString() + ":0" + s.ToString();
}
else
{
timerText.text = m.ToString() + ":" + s.ToString();
}
}
public void stopTimer()
{
CancelInvoke();
}
public void StartTimer()
{
m = minutes;
s= seconds;
writeTimer(m, s);
Invoke("updateTimer", 1f);
}
public void setLives()
{
if (lives < maxLives)
{
StartTimer();
lives++;
Debug.Log("Life: " + lives);
}
if (lives > maxLives)
{
lives = maxLives;
}
for (int i = 0; i < Live.Length; i++)
{
if (i < Mathf.RoundToInt(lives))
{
Live[i].sprite = FullHearts;
}
else
{
Live[i].sprite = EmptyHearts;
}
if(i< maxLives)
{
Live[i].enabled = true;
}
else
{
Live[i].enabled = false;
}
}
}
public void TakeHit(int damage)
{
lives -= damage;
if (lives < 1)
{
lives = 0;
}
for (int i = 0; i < Live.Length; i++)
{
if (i < Mathf.RoundToInt(lives))
{
Live[i].sprite = FullHearts;
}
else
{
Live[i].sprite = EmptyHearts;
}
}
}
but for some reason it does not start, please tell me what the error is possible?

Why the range slider is init to value 0 even if i set it's minimum to 1?

[Range(1, 100)]
public int InstantiateObjectsPositionX = 1, InstantiateObjectsPositionY = 1, InstantiateObjectsPositionZ = 1;
In the inspector all the 3 sliders are at value 0. Why they are not at value 1 ?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteAlways]
public class GenerateObjects : MonoBehaviour
{
public GameObject objectPrefab;
[Range(1, 100)]
public int numberOfObjects = 1;
public int maxDepth;
[Range(1, 100)]
public int posX = 1, posY = 1, posZ = 1;
[Range(1, 100)]
public int numberOfChildrenInLevel = 1;
public bool randomNumberOfChildren = false;
private GameObject parent;
private int count = 0;
private int oldNumberOfObjects;
private int currentDepth;
// Start is called before the first frame update
void Start()
{
oldNumberOfObjects = numberOfObjects;
parent = GameObject.Find("Generate Objects");
StartCoroutine(SpawnObjects());
}
// Update is called once per frame
void Update()
{
if (oldNumberOfObjects != numberOfObjects)
{
StartCoroutine(SpawnObjects());
oldNumberOfObjects = numberOfObjects;
}
else
{
StopAllCoroutines();
}
}
IEnumerator SpawnObjects()
{
while (true)
{
yield return new WaitForSeconds(0);
if (objectPrefab != null)
{
GameObject go = InstantiateObjects(parent.transform);
go.tag = "Instantiated Object";
GenerateChildren(go);
}
count++;
if (count == numberOfObjects)
{
StopAllCoroutines();
break;
}
yield return null;
}
}
GameObject child;
private void GenerateChildren(GameObject go)
{
if (currentDepth < maxDepth)
{
if (randomNumberOfChildren)
{
int ggg = Random.Range(1, numberOfChildrenInLevel);
numberOfChildrenInLevel = ggg;
}
for (int i = 0; i < numberOfChildrenInLevel; i++)
{
child = InstantiateObjects(null);
child.transform.parent = go.transform;
}
currentDepth++;
GenerateChildren(child);
}
else
{
currentDepth = 0;
}
}
private GameObject InstantiateObjects(Transform parent)
{
return Instantiate(objectPrefab,
new Vector3(Random.Range(0, posX), Random.Range(0, posY), Random.Range(0, posZ)),
Quaternion.identity, parent);
}
public void ClearObjects()
{
GameObject[] instantiatedObjects = GameObject.FindGameObjectsWithTag("Instantiated Object");
foreach (GameObject go in instantiatedObjects)
{
DestroyImmediate(go);
}
}
}
The result :
Only if i will click now on the sliders and drag them then the slider it self will show and only then i will be able to drag the slider minimum to 1.
but why now in the first init when declaring the variables the sliders values are 0 ?
I tested now if i init all the 3 variables in the Update() to 1 then it will change them in the inspector to value 1. I thought if i init the variables in the top when declaring them they should be in the inspector already as first init at value 1 and not 0.

how can i have the high score in 1st in Tetris?

I got some problem with my Tetris game on highscore, here's the game script
/// The width of the Grid...
public static int gridWidth = 10;
/// The weight of the Grid...
public static int gridWeight = 20;
/// The grid...
public static Transform[,] grid = new Transform[gridWidth, gridWeight];
public static bool startingAtLevelZero;
public static int startingLevel;
public int scoreOneLine = 50;
public int scoreTwoLine = 100;
public int scoreThreeLine = 400;
public int scoreFourLine = 1500;
public int currentLevel = 0;
private int numLinesCleared = 0;
public static float fallSpeed = 1.0f;
public AudioClip clearedLineSound;
public Text hud_score;
public Text hud_level;
public Text hud_lines;
private int numberOfRowsThisTurn = 0;
private AudioSource audioSource;
public static int currentScore = 0;
private GameObject previewTetromino;
private GameObject nextTetromino;
private bool gameStarted = false;
private int startingHighScore;
private int startingHighScore2;
private int startingHighScore3;
private Vector2 previewTetrominoPosition = new Vector2(-6.5f, 16);
// Start is called before the first frame update
void Start()
{
currentScore = 0;
hud_score.text = "0";
currentLevel = startingLevel;
hud_level.text = currentLevel.ToString();
hud_lines.text = "0";
SpawnNextTetromino();
audioSource = GetComponent<AudioSource>();
startingHighScore = PlayerPrefs.GetInt("highScore");
startingHighScore2 = PlayerPrefs.GetInt("highscore2");
startingHighScore3 = PlayerPrefs.GetInt("highscore3");
}
void Update()
{
UpdateScore();
UpdateUI();
UpdateLevel();
UpdateSpeed();
}
void UpdateLevel()
{
if ((startingAtLevelZero == true) || (startingAtLevelZero == false && numLinesCleared / 10 > startingLevel))
currentLevel = numLinesCleared / 10;
Debug.Log("current Level : " + currentLevel);
}
void UpdateSpeed()
{
fallSpeed = 1.0f - ((float)currentLevel * 0.1f);
Debug.Log("current Fall Speed : " + fallSpeed);
}
public void UpdateUI()
{
hud_score.text = currentScore.ToString();
hud_level.text = currentLevel.ToString();
hud_lines.text = numLinesCleared.ToString();
}
public void UpdateScore()
{
if (numberOfRowsThisTurn > 0)
{
if (numberOfRowsThisTurn == 1)
{
ClearedOneLine();
}
else if (numberOfRowsThisTurn == 2)
{
ClearedOneLine();
}
else if (numberOfRowsThisTurn == 3)
{
ClearedThreeLine();
}
else if (numberOfRowsThisTurn == 4)
{
ClearedFourLine();
}
numberOfRowsThisTurn = 0;
PlayLineClearedSound();
}
}
public void ClearedOneLine()
{
currentScore += scoreOneLine + (currentLevel * 20);
numLinesCleared++;
}
public void ClearedTwoLine()
{
currentScore += scoreTwoLine + (currentLevel * 25);
numLinesCleared += 2;
}
public void ClearedThreeLine()
{
currentScore += scoreThreeLine + (currentLevel * 30);
numLinesCleared += 3;
}
public void ClearedFourLine()
{
currentScore += scoreFourLine + (currentLevel * 40);
numLinesCleared += 4;
}
public void PlayLineClearedSound()
{
audioSource.PlayOneShot(clearedLineSound);
}
public void UpdateHighScore()
{
if (currentScore > startingHighScore)
{
PlayerPrefs.SetInt("highScore3", startingHighScore2);
PlayerPrefs.SetInt("highScore2", startingHighScore);
PlayerPrefs.SetInt("highscore", currentScore);
}
else if (currentScore > startingHighScore2)
{
PlayerPrefs.SetInt("highScore3", startingHighScore2);
PlayerPrefs.SetInt("highscore2", currentScore);
}
else if (currentScore > startingHighScore3)
{
PlayerPrefs.SetInt("highscore3", currentScore);
}
}
public bool CheckIsAboveGrid(Tetromino tetromino)
{
for (int x = 0; x < gridWidth; ++x)
{
foreach (Transform mino in tetromino.transform)
{
Vector2 pos = Round(mino.position);
if (pos.y > gridWeight - 1)
{
return true;
}
}
}
return false;
}
public bool IsFullRowAt (int y)
{
for (int x = 0; x < gridWidth; ++x)
{
if (grid [x, y] == null)
{
return false;
}
}
numberOfRowsThisTurn++;
return true;
}
public void DeleteMinoAt(int y)
{
for (int x = 0; x < gridWidth; ++x)
{
Destroy(grid[x, y].gameObject);
grid[x, y] = null;
}
}
public void MoveRowDown (int y)
{
for (int x = 0; x < gridWidth; ++x)
{
if (grid[x, y] != null)
{
grid[x,y -1] = grid[x, y];
grid[x, y] = null;
grid[x, y -1].position += new Vector3(0, -1, 0);
}
}
}
public void MoveAllRowsDown (int y)
{
for (int i = y; i < gridWeight; ++i)
{
MoveRowDown(i);
}
}
public void DeleteRow()
{
for (int y = 0; y < gridWeight; ++y)
{
if (IsFullRowAt(y))
{
DeleteMinoAt(y);
MoveAllRowsDown(y + 1);
--y;
}
}
}
public void UpdateGrid (Tetromino tetromino)
{
for (int y = 0; y < gridWeight; ++y)
{
for (int x = 0; x < gridWidth; ++x)
{
if (grid[x, y] != null)
{
if (grid[x,y].parent == tetromino.transform)
{
grid[x, y] = null;
}
}
}
}
foreach (Transform mino in tetromino.transform)
{
Vector2 pos = Round(mino.position);
if (pos.y < gridWeight)
{
grid[(int)pos.x, (int)pos.y] = mino;
}
}
}
public Transform GetTransformAtGridPosition (Vector2 pos)
{
if (pos.y > gridWeight -1)
{
return null;
}
else
{
return grid[(int)pos.x, (int)pos.y];
}
}
public void SpawnNextTetromino()
{
if (!gameStarted)
{
gameStarted = true;
nextTetromino = (GameObject)Instantiate(Resources.Load(GetRandomTetromino(), typeof(GameObject)), new Vector2(5.0f, 20.0f), Quaternion.identity);
previewTetromino = (GameObject)Instantiate(Resources.Load(GetRandomTetromino(), typeof(GameObject)), previewTetrominoPosition, Quaternion.identity);
previewTetromino.GetComponent<Tetromino>().enabled = false;
}
else
{
previewTetromino.transform.localPosition = new Vector2(5.0f, 20.0f);
nextTetromino = previewTetromino;
nextTetromino.GetComponent<Tetromino>().enabled = true;
previewTetromino = (GameObject)Instantiate(Resources.Load(GetRandomTetromino(), typeof(GameObject)), previewTetrominoPosition, Quaternion.identity);
previewTetromino.GetComponent<Tetromino>().enabled = false;
}
}
public bool CheckIsInsideGrid (Vector2 pos)
{
return ((int)pos.x >= 0 && (int)pos.x < gridWidth && (int)pos.y >= 0);
}
public Vector2 Round (Vector2 pos)
{
return new Vector2(Mathf.Round(pos.x), Mathf.Round(pos.y));
}
string GetRandomTetromino()
{
int randomTetromino = Random.Range(1, 8);
string randomTetrominoName = "Prefabs/Tetromino_T";
switch (randomTetromino)
{
case 1:
randomTetrominoName = "Prefabs/Tetromino_T";
break;
case 2:
randomTetrominoName = "Prefabs/Tetromino_Long";
break;
case 3:
randomTetrominoName = "Prefabs/Tetromino_Square";
break;
case 4:
randomTetrominoName = "Prefabs/Tetromino_J";
break;
case 5:
randomTetrominoName = "Prefabs/Tetromino_L";
break;
case 6:
randomTetrominoName = "Prefabs/Tetromino_S";
break;
case 7:
randomTetrominoName = "Prefabs/Tetromino_Z";
break;
}
return randomTetrominoName;
}
public void GameOver()
{
UpdateHighScore();
Application.LoadLevel("GameOver");
}
and here's the game menu script
public Text levelText;
public Text highScoreText;
public Text highScoreText2;
public Text highScoreText3;
// Start is called before the first frame update
void Start()
{
levelText.text = "0";
highScoreText.text = PlayerPrefs.GetInt("highscore").ToString();
highScoreText2.text = PlayerPrefs.GetInt("highscore2").ToString();
highScoreText3.text = PlayerPrefs.GetInt("highScore3").ToString();
}
public void PlayGame()
{
if (Game.startingLevel == 0)
Game.startingAtLevelZero = true;
else
Game.startingAtLevelZero = false;
Application.LoadLevel("tetris");
}
public void ChangedValue (float value)
{
Game.startingLevel = (int)value;
levelText.text = value.ToString();
}
public void LaunchGameMenu()
{
Application.LoadLevel("tetris menu");
}
When I got 1120 score in the Tetris game, it shows up in 2nd score instead of 3rd or 1st ,when I got 720 score, it doesn't show up in 3rd score, when I score 1300 It shows up in 2nd and 1120 in 3rd, but not in 1st, can somehow help me what is wrong?
It appears you have various typographical errors while typing the keys when accessing the player's PlayerPrefs. PlayerPrefs is case-sensitive.
↓↓↓
startingHighScore = PlayerPrefs.GetInt("highScore");
startingHighScore2 = PlayerPrefs.GetInt("highscore2");
startingHighScore3 = PlayerPrefs.GetInt("highscore3");
...
↓↓↓
highScoreText.text = PlayerPrefs.GetInt("highscore").ToString();
Consider the use of the nameof() command. The nameof() command allows you to treat a variable in-code as a string. This is SUPER helpful if you ever re-name the variable for example, the string will be renamed along with it. It also has the added bonus of giving you compilation errors if they are misspelled.
Example:
public Text levelText;
public Text highScoreText;
public Text highScoreText2;
public Text highScoreText3;
// Start is called before the first frame update
void Start()
{
levelText.text = "0";
highScoreText.text = PlayerPrefs.GetInt(nameof(highScoreText)).ToString();
highScoreText2.text = PlayerPrefs.GetInt(nameof(highScoreText2)).ToString();
highScoreText3.text = PlayerPrefs.GetInt(nameof(highScoreText3)).ToString();
}

Set max count in for statement

I have a model with a nested collection:
public class SomeClass
{
public SomeClass()
{
this.OtherPart = new HashSet<OtherPart>();
}
[Key]
public int SomeClassId { get; set; }
public string SomeData { get; set; }
public string SomeOtherData { get; set; }
public virtual ICollection<OtherPart> OtherParts { get; set; }
public void CreateOthers(int count = 1)
{
for (int i = 0; i < count; i++)
{
OtherParts.Add(new OtherPart());
}
}
}
with this Controller action:
public ActionResult Create()
{
var abc = new SomeClass();
abc.CreateOthers();
return View(abc);
}
and it works perfectly. The problem I now have is that for my use case i need to set a maximum number of items to create ( in this case 5).
I have tried the following modification in the void above, but it is ignored:
public void CreateOthers(int count = 1, int max = 5)
{
for (int i = 0; i < count && count < max; i++)
{
OtherParts.Add(new OtherPart());
}
}
Any suggestions on how to effectively limit the max number of items added to the nested collection?
Thanks!
You probably need a custom validator, similar to this:
public class MaxItemsAttribute : ValidationAttribute
{
private readonly int _max;
public MaxItemsAttribute(int max) {
_max = max;
}
public override bool IsValid(object value) {
var list = value as IList;
if (list == null)
return false;
if (list.Count > _max)
return false;
return true;
}
}
In your model code, just do this:
[MaxItems(5)]
public virtual ICollection<OtherPart> OtherParts { get; set; }
Change to i < max
public void CreateOthers(int count = 1, int max = 5)
{
for (int i = 0; i < count && i < max; i++)
{
OtherParts.Add(new OtherPart());
}

What wrong with my loop .Need to calculate a running total

I have to build some logic to write some sort of scoreboard. The idea is this:
There are many stages:
1st stage you have 2 numbers. 7 and 3=10
2nd stage you have another 2 numbers. 5 and 1 =6
After the loop has finished, the wanted result should be:
Stage 1 total score=15 (total 1st Stage + firstTry of secondStage)
Stage 2 total score=21 (total 1st Stage + (firstTry + SecondTry of SecondStage)
What's wrong with my loop? I dont seem to get the wanted resoult.
private void Calculate(Player player)
{
for (int i = 0; i < player.Game.Stages.Length; i++)
{
int firstThrow = player.Game.Stages[i].FirstTry;
int secondThrow = player.Game.Stages[i].SecondTry;
int sumFirstAndSecond = firstThrow + secondThrow;
//If firstTry + SecondTry==10 is spare
if ((sumFirstAndSecond == 10) && (firstThrow != 10) && i != player.Game.Stages.Length- 1)
{
int stageScore= player.Game.Stages[i].TotalScore +
player.Game.Stages[i + 1].FirstTry;
player.Game.Stages[i].TotalScore = stageScore;
}
}
}
public class Stage
{
public int FirstTry { get; set; }
public int SecondTry { get; set; }
public int TotalScore { get; set; }
}
public class Player
{
public Player(string name)
{
Name = name;
Game = new Game(name);
}
public Game Game { get; set; }
public string Name { get; set; }
}
public class Game
{
public Game(string playerName)
{
PlayerName = playerName;
Stages = new Stage[10];
for (int i = 0; i < Stages.Length; i++)
{
Stages[i] = new Stage();
}
}
public Stage[] Stages { get; internal set; }
public string PlayerName { get; set; }
}
Change this:
private void Calculate(Player player)
{
for (int i = 0; i < player.Game.Stages.Length; i++)
{
int firstThrow = player.Game.Stages[i].FirstTry;
int secondThrow = player.Game.Stages[i].SecondTry;
int sumFirstAndSecond = firstThrow + secondThrow;
if ((sumFirstAndSecond == 10) && (firstThrow != 10) && i != player.Game.Stages.Length- 1)
{
int stageScore= player.Game.Stages[i].TotalScore + player.Game.Stages[i + 1].FirstTry;
player.Game.Stages[i].TotalScore = sumFirstAndSecond + stageScore;
}
else if (i > 0) player.Game.Stages[i].TotalScore = player.Game.Stages[i - 1].TotalScore + sumFirstAndSecond;
}
}
Bowling?
Try this, and do not forget to add misses (as 0).
Should work for both running and final scoring.
// All balls, including misses (0)!
public readonly IList<int> _balls = new List<int>();
private int _currentBall;
public int CalculateTotalScore()
{
int score = 0;
_currentBall = 0;
for (var frame = 0; frame < 10; frame++)
{
if (_currentBall >= _balls.Count)
break;
if (_balls[_currentBall] == 10)
{
// Strrrike!
score += AggregateScoreFromCurrentBall(3);
_currentBall++;
}
else if (AggregateScoreFromCurrentBall(2) == 10)
{
// Spare
score += AggregateScoreFromCurrentBall(3);
_currentBall += 2;
}
else
{
score += AggregateScoreFromCurrentBall(2);
_currentBall += 2;
}
}
return score;
}
private int AggregateScoreFromCurrentBall(int numberOfBallsToSum)
{
var sum = 0;
for (var i = 0; i < numberOfBallsToSum; i++)
if (_currentBall + i < _balls.Count)
sum += _balls[_currentBall + i];
return sum;
}

Categories

Resources