Reverse timer to increase life - c#

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?

Related

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();
}

Unity saving via playerprefs bugged?

Sorry, I that I included all the code but I really can't find the error: I play and save and after I buy something with the BuyTaxes or Buymarket and quit and stop it and play it again it shows all the UI shows and all the prices for the market and the discount use are set to 0. But I cant figure out why.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameScript : MonoBehaviour
{
public Text GoldText;
public Text ArmyPowerText;
public Text PlayerNametext;
public Text Button1Text;
public Text Button2Text;
public int gold;
public int armypower;
public string PlayerName;
public int Level;
public int Income;
public int incomeboost;
public int discount;
public float lvlremainder;
public GameObject ButtonHolder;
public Slider LevelBar;
public float LevelProgress;
private float FillSpeed = 0.5f;
public GameObject UIHolder;
public GameObject StartForm;
public InputField NameInput;
public GameObject ArmyUI;
public GameObject InvestUI;
public GameObject LaboratoryUI;
private float time = 0.0f;
public float IncomePerdiod = 5f;
public bool GameStart = true;
//Invest Prices
//Market
public int marketprice;
public int marketlevel;
public Text marketpricetext;
public Text markettext;
//Taxes
public int taxesprice;
public int taxeslevel;
public Text taxespricetext;
public Text taxestext;
void Start()
{
Load();
if(GameStart == true)
{
gold = 100;
armypower = 0;
Level = 1;
LevelProgress = 0;
//Laboratory
discount = 1;
Income = 1;
incomeboost = 1;
//Invest
marketlevel = 0;
taxeslevel = 0;
ArmyUIHide();
InvestUIHide();
ButtonHide();
UIHide();
StartForm.SetActive(true);
Save();
}
if (GameStart == false)
{
StartForm.SetActive(false);
ArmyUIHide();
InvestUIHide();
ButtonShow();
UIShow();
Save();
}
}
void Update()
{
if(time >= IncomePerdiod)
{
time = 0.0f;
gold += Income * incomeboost;
}
time += Time.deltaTime;
Save();
GoldText.text = "Gold: " + gold;
ArmyPowerText.text = "Army Power: " + armypower;
PlayerNametext.text = PlayerName + " LVL " + Level;
//Market
markettext.text = "Market LVL " + marketlevel;
marketpricetext.text = marketprice.ToString();
marketprice = 50 * discount;
//Taxes
taxestext.text = "Taxes LVL " + taxeslevel;
taxespricetext.text = taxesprice.ToString();
taxesprice = 250 * discount;
if (LevelBar.value < LevelProgress)
{
LevelBar.value += FillSpeed * Time.deltaTime;
}
if (LevelBar.value > LevelProgress)
{
LevelBar.value = LevelProgress;
}
if (LevelProgress >= 1)
{
Level++;
LevelProgress = 0;
}
}
public void Save()
{
//UI
PlayerPrefs.SetString("gold", gold.ToString());
PlayerPrefs.SetString("armypower", armypower.ToString());
PlayerPrefs.SetString("GameStart", GameStart.ToString());
PlayerPrefs.SetString("PlayerName", PlayerName.ToString());
PlayerPrefs.SetString("Level", Level.ToString());
PlayerPrefs.SetString("LevelProgress", LevelProgress.ToString());
//Laboratory
PlayerPrefs.SetString("discount", discount.ToString());
PlayerPrefs.SetString("Income", Income.ToString());
PlayerPrefs.SetString("incomeboost", incomeboost.ToString());
//Invest
PlayerPrefs.SetString("marketlevel", marketlevel.ToString());
PlayerPrefs.SetString("taxeslevel", taxeslevel.ToString());
}
public void Load()
{
//UI
gold = int.Parse(PlayerPrefs.GetString("gold", "100"));
armypower = int.Parse(PlayerPrefs.GetString("armypower", "0"));
GameStart = bool.Parse(PlayerPrefs.GetString("GameStart", "true"));
PlayerName = PlayerPrefs.GetString("PlayerName", "Guest");
Level = int.Parse(PlayerPrefs.GetString("Level", "1"));
LevelProgress = int.Parse(PlayerPrefs.GetString("LevelProgress", "0"));
//Laboratory
discount = int.Parse(PlayerPrefs.GetString("discount", "1"));
Income = int.Parse(PlayerPrefs.GetString("Income", "1"));
incomeboost = int.Parse(PlayerPrefs.GetString("incomeboost", "1"));
//Invest
marketlevel = int.Parse(PlayerPrefs.GetString("marketlevel", "50"));
taxeslevel = int.Parse(PlayerPrefs.GetString("taxeslevel", "250"));
}
public void ButtonHide()
{
ButtonHolder.SetActive(false);
}
public void ButtonShow()
{
ButtonHolder.SetActive(true);
}
public void UIHide()
{
UIHolder.SetActive(false);
}
public void UIShow()
{
UIHolder.SetActive(true);
}
public void ArmyUIShow()
{
ArmyUI.SetActive(true);
}
public void ArmyUIHide()
{
ArmyUI.SetActive(false);
}
public void LaboratoryUIShow()
{
LaboratoryUI.SetActive(true);
}
public void LaboratoryUIHide()
{
LaboratoryUI.SetActive(false);
}
public void InvestUIShow()
{
InvestUI.SetActive(true);
}
public void InvestUIHide()
{
InvestUI.SetActive(false);
}
public void EnterName()
{
PlayerName = NameInput.text;
StartForm.SetActive(false);
UIShow();
GameStart = false;
ButtonShow();
}
public void ArmyClick()
{
ArmyUIShow();
ButtonHide();
LaboratoryUIHide();
InvestUIHide();
}
public void InvestClick()
{
InvestUIShow();
ButtonHide();
LaboratoryUIHide();
ArmyUIHide();
}
public void LaboratoryClick()
{
ArmyUIHide();
ButtonHide();
LaboratoryUIShow();
InvestUIHide();
}
public void Home()
{
ArmyUIHide();
InvestUIHide();
ButtonShow();
LaboratoryUIHide();
}
//Buy Invest
public void BuyMarket()
{
if(gold >= marketprice && marketlevel < 5)
{
marketlevel++;
Income += 1;
gold -= marketprice;
if (LevelProgress < 1f - 0.05f)
{
LevelProgress += 0.15f;
}
else
{
lvlremainder += (LevelProgress + 0.05f - 1f);
Level++;
LevelProgress = 0;
LevelProgress += lvlremainder;
}
}
}
public void BuyTaxes()
{
if (gold >= taxesprice && taxeslevel < 10)
{
taxeslevel++;
Income += 3;
gold -= taxesprice;
if (LevelProgress < 1f - 0.15f)
{
LevelProgress += 0.15f;
}
else
{
lvlremainder += (LevelProgress + 0.15f - 1f);
Level++;
LevelProgress = 0;
LevelProgress += lvlremainder;
}
}
}
The saving system in your code is not developed correctly, remove the Save() method call from the Start and Update methods, and call it only when the necessary event occurs, such as the end of the game.
Do local prop like this to save data:
private int Gold
{
get => PlayerPrefs.GetInt("gold");
set => PlayerPrefs.SetInt("gold", value);
}
I found the fault I parsed as int for a float that messed the whole saving system up!

How to use bool operator in

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;
}

Pacman game - how to fix

I am creating really simple pacman game as a homework. I am working in Visual Studio, in c#. The problem is, when I click run, only the winform shows with nothing on it. Can someone tell me what have I done wrong?
namespace pacman
{
public partial class Form1 : Form
{
Timer timer;
Pacman pacman;
static readonly int TIMER_INTERVAL = 250;
static readonly int WORLD_WIDTH = 15;
static readonly int WORLD_HEIGHT = 10;
Image foodImage;
bool[][] foodWorld;
public Form1()
{
InitializeComponent();
foodImage = Properties.Resources.orange_detoure;
DoubleBuffered = true;
newGame();
}
public void newGame()
{
pacman = new Pacman();
this.Width = Pacman.radius * 2 * (WORLD_WIDTH + 1);
this.Height = Pacman.radius * 2 * (WORLD_HEIGHT + 1);
foodWorld = new bool[WORLD_WIDTH][];
timer = new Timer();
timer.Interval = TIMER_INTERVAL;
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
timer.Interval = TIMER_INTERVAL - 1;
if (TIMER_INTERVAL == 0)
{
timer.Stop();
}
pacman.Move(WORLD_WIDTH, WORLD_HEIGHT);
Invalidate();
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (Keys.Up != 0)
{
pacman.ChangeDirection("UP");
}
if (Keys.Down != 0)
{
pacman.ChangeDirection("DOWN");
}
if (Keys.Left != 0)
{
pacman.ChangeDirection("LEFT");
}
if (Keys.Right != 0)
{
pacman.ChangeDirection("RIGHT");
}
Invalidate();
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics;
g.Clear(Color.White);
for (int i = 0; i < foodWorld.Length; i++)
{
for (int j = 0; j < foodWorld[i].Length; j++)
{
if (foodWorld[i][j])
{
g.DrawImageUnscaled(foodImage, j * Pacman.radius * 2 + (Pacman.radius * 2 - foodImage.Height) / 2, i * Pacman.radius * 2 + (Pacman.radius * 2 - foodImage.Width) / 2);
}
}
}
pacman.Draw(g);
}
}
}
And here is the class Pacman:
namespace pacman
{
public class Pacman
{
public enum dir {UP, DOWN, RIGHT, LEFT};
public float x { get; set; }
public float y { get; set; }
public string direction { get; set; }
static public int radius = 20;
public double speed { get; set; }
public bool open { get; set; }
public Brush brush = new SolidBrush(Color.Yellow);
public Pacman() {
this.x = 7;
this.y = 5;
this.speed = 20;
this.direction = Convert.ToString(dir.RIGHT);
this.open = false;
}
public void ChangeDirection(string direct)
{
// vasiot kod ovde
for (int i = 0; i < 3; i++) {
if(direct == Convert.ToString(dir.RIGHT))
{
direction = "RIGHT";
}
if (direct == Convert.ToString(dir.LEFT))
{
direction = "LEFT";
}
if (direct == Convert.ToString(dir.UP))
{
direction = "UP";
}
if (direct == Convert.ToString(dir.DOWN))
{
direction = "DOWN";
}
}
}
public void Move(float width, float height)
{
if (direction == Convert.ToString(dir.RIGHT))
{
x = x + 1;
if (x > width) {
x = 1;
}
}
else if (direction == Convert.ToString(dir.LEFT))
{
x = x - 1;
if (x < 0) {
x = 14;
}
}
else if (direction == Convert.ToString(dir.UP))
{
y = y + 1;
if (y > height) {
y = 1;
}
}
else if (direction == Convert.ToString(dir.DOWN))
{
y = y - 1;
if (y < 0) {
y = 14;
}
}
}
public void Draw(Graphics g)
{
if (!open) {
g.FillEllipse(brush, 7, 5, 15, 15);
}
}
}
}
It should look like this http://prntscr.com/70e0jt.
I will be grateful if someone can tell me what should I fix so it finally works..
Add this to your constructor:
this.Paint += Form1_Paint;
What is happening is that you made a Paint handler, but never assigned the paint event to handle it (that I can see, its possible that the event was assigned in the other partial part of the class).
The other problem is that you did not fully define the "food world" variable, you initialized the first rank, but not the second. You need to fully initialize this and set the booleans inside of it.

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