How to lose control in few seconds? - c#

At the starting of GameState.Running, i want to stop input key in 3 seconds, after that, every time when my character take damage, i want to lose control in 1 second, could anyone show me how to do that?
public override void Update(GameTime gameTime, KeyboardState Current, KeyboardState Old)
{
float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
if (TimeGetReady < 0)
{
LockKey = false;
}
else
{
LockKey = true;
TimeGetReady -= elapsed;
}
if (LockKey == false)
{
CurrentKeys = Current;
OldKeys = Old;
}
if (CurrentKeys.IsKeyDown(Keys.P))
{
if (!OldKeys.IsKeyDown(Keys.P))
if (IsPause == true)
IsPause = false;
else
IsPause = true;
}
if (IsPause == true)
{
return;
}
Update(elapsed);
if (CurrentKeys.IsKeyDown(Keys.Left))
{
KeyLeft = true;
if (HPF < 3)
HPF += 2;
PushHorizontal += 5;
Face = -1;
}
else
if (Old.IsKeyDown(Keys.Left))
{
KeyLeft = false;
}
if (CurrentKeys.IsKeyDown(Keys.Right))
{
KeyRight = true;
PushHorizontal += 5;
if (HPF < 3)
HPF += 2;
Face = 1;
}
else
if (Old.IsKeyDown(Keys.Right))
{
KeyRight = false;
}
if (KeyLeft == true || KeyRight == true)
{
KeyMove = true;
}
else
{
KeyMove = false;
}
if (KeyLeft == true && KeyRight == true)
{
KeyLeft = false;
KeyRight = false;
KeyMove = false;
}
if (CurrentKeys.IsKeyDown(Keys.X))
{
if (LockKeyX == false)
{
KeyJump = true;
LockKeyX = true;
PushVertical += 500;
}
if (VPF < 8)
VPF += 3;
}
else
if (Old.IsKeyDown(Keys.X))
{
KeyJump = false;
}
if (CurrentKeys.IsKeyUp(Keys.X))
{
if (Down == true)
{
LockKeyX = false;
}
}
if (CurrentKeys.IsKeyDown(Keys.Z))
{
if (LockKeyZ == false)
{
KeyDash = true;
KeyJump = false;
LockKeyZ = true;
PushHorizontal += 100;
}
if (KeyDash == true)
{
HPF = 1;
PushVertical += Gravity;
VPF = Gravity;
}
}
else
if (Old.IsKeyDown(Keys.Z))
{
KeyDash = false;
}
if (CurrentKeys.IsKeyUp(Keys.Z))
{
if (KeyMove == false && Down == true)
LockKeyZ = false;
}
if (CurrentKeys.IsKeyDown(Keys.C))
{
ChargeTime += elapsed;
if (LockKeyC == false)
{
LockKeyC = true;
TimeShot += 10f;
StayShot.ResetFrame();
}
}
else
if (Old.IsKeyDown(Keys.C))
{
if (ChargeTime > 0)
{
TimeShot += 0.4f;
ChargeTime = 0;
}
LockKeyC = false;
}
Update(elapsed);
UpdateInteraction();
if (TimeGetReady <= 0)
{
UpdateStatus(gameTime);
}
UpdateFrameStatus(elapsed);
LastStatus = RockmanStatus;
}

You need some InputManager that you update only when you need. Here is example of basic verstion of InputManager.
public override void Update(){
if(updateKeyboard) {InputManager.Update()}
}
new InputManager Class
public static class InputManager
{
public static void Update()
{
_previousKeyboardState = _currentKeyboardState;
_currentKeyboardState = Keyboard.GetState();
}
public static bool IsKeyDown(Keys key)
{
return _currentKeyboardState.IsKeyDown(key);
}
public static bool IsKeyUp(Keys key)
{
return _currentKeyboardState.IsKeyUp(key);
}
public static bool OnKeyDown(Keys key)
{
return _currentKeyboardState.IsKeyDown(key) && _previousKeyboardState.IsKeyUp(key);
}
public static bool OnKeyUp(Keys key)
{
return _currentKeyboardState.IsKeyUp(key) && _previousKeyboardState.IsKeyDown(key);
}
private static KeyboardState _currentKeyboardState;
private static KeyboardState _previousKeyboardState;
}

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

How can I lower the opacity of a game object in an array when a specific event occurs?

For example, in my game, I want these small player icons to turn transparent when the player dies. I already have a function called PlayerDead, but when I put the game object in the function, I can't access the sprite renderer. I would preferably like to not attach my main script to the icon, but I really have no clue how to do it. For reference, _checkForGameOver is a counter to see how many times the player/enemy has died. When the player dies, a question mark in place of where the icon is destroyed, and the icon is instantiated in that spot. Here is a portion of the code from the main script:
public GameObject[] playerPrefab;
public GameObject[] enemyPrefab;
public GameObject[] icon;
public GameObject[] questionMarks;
public Transform playerSpawn;
public Transform enemySpawn;
public Transform topSpawn;
public Transform middleSpawn;
public Transform bottomSpawn;
public Transform topSpawnEnemy;
public Transform middleSpawnEnemy;
public Transform bottomSpawnEnemy;
Unit playerUnit;
Unit enemyUnit;
int randomIntPlayer;
int randomIntEnemy;
public bool playerPassDamage;
public BattleHUD playerHUD;
public BattleHUD enemyHUD;
public BattleState state;
public Button attackButton;
public Button passButtonDamage;
public Button healButton;
public Button passButtonResistance;
public GameObject playAgain;
public GameObject circleAttack;
public GameObject squareAttack;
public IconColor iconColor;
public Shake shake;
private int _checkForGameOverPlayer { get; set; } = 0;
private int _checkForGameOverEnemy { get; set; } = 0;
void Start()
{
shake = GameObject.FindGameObjectWithTag("ScreenShake").GetComponent<Shake>();
state = BattleState.START;
StartCoroutine(SetupBattle());
}
IEnumerator SetupBattle()
{
randomIntPlayer = Random.Range(0, playerPrefab.Length);
GameObject playerGO = Instantiate(playerPrefab[randomIntPlayer], playerSpawn);
playerUnit = playerGO.GetComponent<Unit>();
if(randomIntPlayer == 0)
{
Instantiate(icon[0], topSpawn);
}
else if (randomIntPlayer == 1)
{
Instantiate(icon[1], topSpawn);
}
else if (randomIntPlayer == 2)
{
Instantiate(icon[2], topSpawn);
}
else if (randomIntPlayer == 3)
{
Instantiate(icon[3], topSpawn);
}
randomIntEnemy = Random.Range(0, enemyPrefab.Length);
GameObject enemyGO = Instantiate(enemyPrefab[randomIntEnemy], enemySpawn);
enemyUnit = enemyGO.GetComponent<Unit>();
if (randomIntEnemy == 0)
{
Instantiate(icon[0], topSpawnEnemy);
}
else if (randomIntEnemy == 1)
{
Instantiate(icon[1], topSpawnEnemy);
}
else if (randomIntEnemy == 2)
{
Instantiate(icon[2], topSpawnEnemy);
}
else if (randomIntEnemy == 3)
{
Instantiate(icon[3], topSpawnEnemy);
}
playerUnit.GetComponentInChildren<SpriteRenderer>().enabled = true;
enemyUnit.GetComponentInChildren<SpriteRenderer>().enabled = true;
playerHUD.SetHUD(playerUnit);
enemyHUD.SetHUD(enemyUnit);
playerPassDamage = false;
didPlayerHeal = false;
if (playerUnit.speed > enemyUnit.speed)
{
state = BattleState.PLAYERTURN;
PlayerTurn();
}
else if (enemyUnit.speed > playerUnit.speed)
{
passButtonDamage.interactable = false;
attackButton.interactable = false;
healButton.interactable = false;
passButtonResistance.interactable = false;
state = BattleState.ENEMYTURN;
yield return new WaitForSeconds(1.2f);
StartCoroutine(EnemyTurn());
}
}
public IEnumerator EnemyDead()
{
_checkForGameOverEnemy++;
if (_checkForGameOverEnemy == 1)
{
if (randomIntEnemy == 0)
{
}
else if (randomIntEnemy == 1)
{
}
else if (randomIntEnemy == 2)
{
}
else if (randomIntEnemy == 3)
{
}
}
if (_checkForGameOverEnemy == 3)
{
state = BattleState.WON;
EndBattle();
}
yield return new WaitForSeconds(.25f);
randomIntEnemy = Random.Range(0, enemyPrefab.Length);
GameObject enemyGO = Instantiate(enemyPrefab[randomIntEnemy], enemySpawn);
enemyUnit = enemyGO.GetComponent<Unit>();
if (_checkForGameOverEnemy == 1)
{
Destroy(questionMarks[2]);
if (randomIntEnemy == 0)
{
Instantiate(icon[0], middleSpawnEnemy);
}
else if (randomIntEnemy == 1)
{
Instantiate(icon[1], middleSpawnEnemy);
}
else if (randomIntEnemy == 2)
{
Instantiate(icon[2], middleSpawnEnemy);
}
else if (randomIntEnemy == 3)
{
Instantiate(icon[3], middleSpawnEnemy);
}
}
if (_checkForGameOverEnemy == 2)
{
Destroy(questionMarks[3]);
if (randomIntEnemy == 0)
{
Instantiate(icon[0], bottomSpawnEnemy);
}
else if (randomIntEnemy == 1)
{
Instantiate(icon[1], bottomSpawnEnemy);
}
else if (randomIntEnemy == 2)
{
Instantiate(icon[2], bottomSpawnEnemy);
}
else if (randomIntEnemy == 3)
{
Instantiate(icon[3], bottomSpawnEnemy);
}
}
enemyHUD.SetHUD(enemyUnit);
if (playerUnit.speed > enemyUnit.speed)
{
state = BattleState.PLAYERTURN;
PlayerTurn();
}
else if (enemyUnit.speed > playerUnit.speed)
{
passButtonDamage.interactable = false;
attackButton.interactable = false;
healButton.interactable = false;
passButtonResistance.interactable = false;
yield return new WaitForSeconds(1f);
state = BattleState.ENEMYTURN;
StartCoroutine(EnemyTurn());
}
}
IEnumerator PlayerDead()
{
_checkForGameOverPlayer++;
if (_checkForGameOverEnemy == 1)
{
if (randomIntPlayer == 0)
{
}
else if (randomIntPlayer == 1)
{
}
else if (randomIntPlayer == 2)
{
}
else if (randomIntPlayer == 3)
{
}
}
if (_checkForGameOverPlayer == 3)
{
state = BattleState.LOST;
EndBattle();
}
yield return new WaitForSeconds(.25f);
randomIntPlayer = Random.Range(0, playerPrefab.Length);
GameObject playerGO = Instantiate(playerPrefab[randomIntPlayer], playerSpawn);
playerUnit = playerGO.GetComponent<Unit>();
if (_checkForGameOverPlayer == 1)
{
Destroy(questionMarks[0]);
if (randomIntPlayer == 0)
{
Instantiate(icon[0], middleSpawn);
}
else if (randomIntPlayer == 1)
{
Instantiate(icon[1], middleSpawn);
}
else if (randomIntPlayer == 2)
{
Instantiate(icon[2], middleSpawn);
}
else if (randomIntPlayer == 3)
{
Instantiate(icon[3], middleSpawn);
}
}
if (_checkForGameOverPlayer == 2)
{
Destroy(questionMarks[1]);
if (randomIntPlayer == 0)
{
Instantiate(icon[0], bottomSpawn);
}
else if (randomIntPlayer == 1)
{
Instantiate(icon[1], bottomSpawn);
}
else if (randomIntPlayer == 2)
{
Instantiate(icon[2], bottomSpawn);
}
else if (randomIntPlayer == 3)
{
Instantiate(icon[3], bottomSpawn);
}
}
playerHUD.SetHUD(playerUnit);
if (playerUnit.speed > enemyUnit.speed)
{
state = BattleState.PLAYERTURN;
PlayerTurn();
}
else if (enemyUnit.speed > playerUnit.speed)
{
passButtonDamage.interactable = false;
attackButton.interactable = false;
healButton.interactable = false;
passButtonResistance.interactable = false;
yield return new WaitForSeconds(1f);
state = BattleState.ENEMYTURN;
StartCoroutine(EnemyTurn());
}
}
If you're using SpriteRenderer to render the icon, then you can use GetComponent<SpriteRenderer>().color to access it's color, and your opacity value can be accessed via Color.a, which means alpha. 0 means it's transparent, 1 means it's full-visible. Here's my suggestion:
foreach (var g in icon)
{
if (g == null) continue;
var sprite = g.GetComponent<SpriteRenderer>();
var color = sprite.color;
sprite.color = new Color(color.r, color.g, color.b, 0)
}
Be careful that since it contains GetComponent(), it's not recommended to do like so in Update() function. Only do this when the event has "Actually" occured.

Xamarin : Different behaviour Android / iOS (static class ?)

I'm taking over a project on Xamarin.
It work on android and I want it to work on iOS.
Initially, it have been done for that so I expected it work with maybe only settings ?
Anyway it work on Android but not on iOS.
I have this code :
public App()
{
Debug.WriteLine(Current.Properties); //return default value
try
{
ViewModelLocator.MainViewModel.RestoreState(Current.Properties);
BindingContext = ViewModelLocator.MainViewModel;
MainTabPage = new SGC400Tab();
MainPage = MainTabPage;
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
public static class ViewModelLocator
{
private static GlobalViewModel _myViewModel = new GlobalViewModel();
public static GlobalViewModel MainViewModel
{
get
{
return _myViewModel;
}
}
}
public class GlobalViewModel : INotifyPropertyChanged
{
public void RestoreState(IDictionary<string, object> dictionary)
{
Thing1.SelectedUnitySystem_Presure = GetDictionaryEntry(dictionary, "SavedUnitySystem_Pression", "Bars");
Thing1.SelectedUnitySystem_Flow = GetDictionaryEntry(dictionary, "SavedUnitySystem_Debit", "m3/h");
Thing1.SelectedUnitySystem_Temperature = GetDictionaryEntry(dictionary, "SavedUnitySystem_Temperature", "°C");
Thing1.SelectedLanguageKey = GetDictionaryEntry(dictionary, "SavedLanguage", "en");
}
}
Which return an error :
System.NullReferenceException on line :
private static GlobalViewModel _myViewModel = new GlobalViewModel();
I'm a bit puzzled by the fact it work on android... but not on iOS...
I have to tell I'm pretty new on Xamarin, may you give me some pointer ?
Thank you in advance !
PS : Class GlobalViewModel here :
public class GlobalViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
//#####################################
//Enneigeur
public Enneigeur _Enneigeur1 = new Enneigeur();
public Enneigeur Enneigeur1
{
get { return _Enneigeur1; }
set
{
_Enneigeur1 = value;
}
}
//Com
public ComSGC400 _comSGC400 = new ComSGC400();
public ComSGC400 ComSGC400
{
get { return _comSGC400; }
set { _comSGC400 = value; }
}
public const int TIMOUT_COM_MS = 500;
public const int DELAI_ENTRE_TRAME_MS = 1000;
//#####################################
//Bluetooth
public ObservableCollection<string> ListOfDevices { get; set; } = new ObservableCollection<string>();
public string inputBuffer;
public string SelectedBthDevice { get;set; } = "";
private bool _isConnected { get; set; } = false;
public bool IsConnected {
get { return _isConnected; }
set
{
_isConnected = value;
if (_isConnected == true)
{
((App)Application.Current).AddPages();
} else
{
((App)Application.Current).RemovePages();
}
}
}
private bool _isSelectedBthDevice { get { if (string.IsNullOrEmpty(SelectedBthDevice)) return false; return true; }}
public bool IsConnectEnabled { get { if (_isSelectedBthDevice == false) return false; return !IsConnected; }}
public bool IsDisconnectEnabled { get { if (_isSelectedBthDevice == false) return false; return IsConnected; } }
public Color ConnectBackgroundcolor { get { if (IsConnectEnabled) return Color.Green; return Color.FromRgb(48, 48, 48); } }
public Color DisconnectBackgroundColor { get { if (IsDisconnectEnabled) return Color.Red; return Color.FromRgb(48, 48, 48); } }
public bool IsConnectionInit { get { if (EtatGrafcet_loop < 2 || IsConnected == false ) return false; return true; } }
public bool IsModeManuOK { get { if (EtatGrafcet_loop >= 2 && IsConnected == true && _Enneigeur1.Manu == true) return true; return false; } }
public bool IsBoutonRotaOK { get { if (EtatGrafcet_loop >= 2 && IsConnected == true && ( _Enneigeur1._VersionSGC400 > 10213 || _Enneigeur1.Manu == true)) return true; return false; } }
public bool IsPickerEnabled { get { return !IsConnected; }}
public bool IsBalayageDispo { get { if (EtatGrafcet_loop < 2 || IsConnected == false || _Enneigeur1.OptionBalayageDispo == false) return false; return true; } }
public LocalizedResources Resources { get; private set;}
public Color Mode_Manu_Button_Text_Color
{
get
{
if (EtatGrafcet_loop < 2)
return Color.Gray;
else
return Color.White;
}
}
public Color Mode_Manu_Button_Color {
get {
if (EtatGrafcet_loop < 2)
return Color.FromRgb(48, 48, 48);
else
{
if (_Enneigeur1.ModeMarche == 1) return Color.Green; return Color.Black;
}
}
}
public Color Mode_Stop_Button_Text_Color
{
get
{
if (EtatGrafcet_loop < 2)
return Color.Gray;
else
return Color.White;
}
}
public Color Mode_Stop_Button_Color {
get
{
if (EtatGrafcet_loop < 2)
return Color.FromRgb(48, 48, 48);
else
{
if (_Enneigeur1.ModeMarche == 2) return Color.Green; return Color.Black;
}
}
}
public Color Mode_Forcage_Button_Text_Color
{
get
{
if (EtatGrafcet_loop < 2)
return Color.Gray;
else
return Color.White;
}
}
public Color Mode_Forcage_Button_Color
{
get
{
if (EtatGrafcet_loop < 2)
return Color.FromRgb(48, 48, 48);
else
{
if (_Enneigeur1.ModeMarche == 0) return Color.Green; return Color.Black;
}
}
}
private CancellationTokenSource _ct { get; set; }
private int EtatGrafcet_loop { get; set; }
private DateTime timer_send = DateTime.Now;
private bool envoiContinu = false;
private string envoiWrite = "";
private async Task Loop()
{
string bufferEnvoi = "";
bool res;
int erreur_cryptage = 0;
EtatGrafcet_loop = 0;
int reponseLen = 0;
_Enneigeur1.ResetValues();
_ct = new CancellationTokenSource();
ComSGC400.AddrSGC400 = Convert.ToUInt16(SelectedBthDevice.Substring(5));
while (_ct.IsCancellationRequested == false)
{
switch (EtatGrafcet_loop)
{
case 0://Envoi trame clé crypté
if (DateTime.Now > timer_send.AddMilliseconds(DELAI_ENTRE_TRAME_MS)) //Temps entre trames
{
//Test d'echange de clé de cryptage
inputBuffer = "";
reponseLen = ComSGC400.Create_Trame_getKey(ref bufferEnvoi);
if (bufferEnvoi.Length > 0)
{
Xamarin.Forms.MessagingCenter.Send<App, string>((App)Xamarin.Forms.Application.Current, "WriteDatas", bufferEnvoi);
timer_send = DateTime.Now;
EtatGrafcet_loop = 1;
}
}
break;
case 1: //attente reception clé crypté
if (DateTime.Now > timer_send.AddMilliseconds(TIMOUT_COM_MS)){ EtatGrafcet_loop = 0; break; } //timeout
if (inputBuffer != null)
{
ComSGC400.Trame_RechercheDebutTrame(ref inputBuffer);
if (inputBuffer.Length >= reponseLen)
{
inputBuffer = inputBuffer.Substring(0, reponseLen);
res = ComSGC400.Update_ProtectionKey( inputBuffer);
if (res == true)
{
//cle cryptage OK
bufferEnvoi = "";
EtatGrafcet_loop = 2;
erreur_cryptage = 0;
}
else
{
//cle cryptage non ok
bufferEnvoi = "";
EtatGrafcet_loop = 0;
}
inputBuffer = "";
}
}
break;
case 2: //envoi trame readMain
if (envoiWrite != "")
EtatGrafcet_loop = 10; //envoi write
else
{
if (DateTime.Now > timer_send.AddMilliseconds(DELAI_ENTRE_TRAME_MS)) //Temps entre trames
{
reponseLen = ComSGC400.Create_Trame_ReadMain(ref bufferEnvoi);
if (bufferEnvoi.Length > 0)
{
inputBuffer = "";
Xamarin.Forms.MessagingCenter.Send<App, string>((App)Xamarin.Forms.Application.Current, "WriteDatas", bufferEnvoi);
timer_send = DateTime.Now;
EtatGrafcet_loop = 3;
}
}
}
break;
case 3: //attente reponse trame readMain
if (DateTime.Now > timer_send.AddMilliseconds(TIMOUT_COM_MS)) {
EtatGrafcet_loop = 20; break;
} //timeout
if (inputBuffer != null)
{
ComSGC400.Trame_RechercheDebutTrame(ref inputBuffer);
if (inputBuffer.Length >= reponseLen)
{
inputBuffer = inputBuffer.Substring(0, reponseLen);
res = ComSGC400.Update_Enneigeur( inputBuffer, ref _Enneigeur1);
if (res == true)
{
//Message OK
bufferEnvoi = "";
EtatGrafcet_loop = 4;//Passage readCom
erreur_cryptage = 0;
_Enneigeur1.LastRead = DateTime.Now;
}
else
{
//Message NON OK
EtatGrafcet_loop = 20;
}
inputBuffer = "";
}
}
break;
case 4: //envoi trame readCom
if (envoiWrite != "")
EtatGrafcet_loop = 10; //envoi write
else
{
if (DateTime.Now > timer_send.AddMilliseconds(50)) //Temps entre trames
{
reponseLen = ComSGC400.Create_Trame_ReadCom(ref bufferEnvoi);
if (bufferEnvoi.Length > 0)
{
inputBuffer = "";
Xamarin.Forms.MessagingCenter.Send<App, string>((App)Xamarin.Forms.Application.Current, "WriteDatas", bufferEnvoi);
timer_send = DateTime.Now;
EtatGrafcet_loop = 5;
}
}
}
break;
case 5: //attente reponse trame readCom
if (DateTime.Now > timer_send.AddMilliseconds(TIMOUT_COM_MS)) {
EtatGrafcet_loop = 21; break;
} //timeout
if (inputBuffer != null)
{
ComSGC400.Trame_RechercheDebutTrame(ref inputBuffer);
if (inputBuffer.Length >= reponseLen)
{
inputBuffer = inputBuffer.Substring(0, reponseLen);
res = ComSGC400.Update_Enneigeur( inputBuffer, ref _Enneigeur1);
if (res == true)
{
//Message OK
bufferEnvoi = "";
EtatGrafcet_loop = 2; //Retour read main
erreur_cryptage = 0;
_Enneigeur1.LastRead = DateTime.Now;
if (_Enneigeur1.Reset)
Send_value_bluetooth("reset", false);
}
else
{
//Message NON OK
EtatGrafcet_loop = 21;
}
inputBuffer = "";
}
}
break;
case 10: //envoi trame Write
inputBuffer = "";
Xamarin.Forms.MessagingCenter.Send<App, string>((App)Xamarin.Forms.Application.Current, "WriteDatas", envoiWrite);
timer_send = DateTime.Now;
EtatGrafcet_loop =11;
break;
case 11: //attente reponse trame Write
if (DateTime.Now > timer_send.AddMilliseconds(TIMOUT_COM_MS)) { EtatGrafcet_loop = 20; break; } //timeout
if (inputBuffer != null)
{
ComSGC400.Trame_RechercheDebutTrame(ref inputBuffer);
if (inputBuffer.Length >= 16)
{
bufferEnvoi = "";
if (envoiContinu)
{
EtatGrafcet_loop = 10; //envoi continu
}
else
{
envoiWrite = "";
EtatGrafcet_loop = 2; //Retour read main
}
erreur_cryptage = 0;
_Enneigeur1.LastWrite = DateTime.Now;
inputBuffer = "";
}
}
break;
case 20://Erreur de reception trame readMain
bufferEnvoi = "";
erreur_cryptage = erreur_cryptage + 1;
envoiWrite = "";
if (erreur_cryptage > 3)
{
_Enneigeur1.ResetValues();
erreur_cryptage = 0;
EtatGrafcet_loop = 0;
}
else
{
EtatGrafcet_loop = 2;
}
break;
case 21://Erreur de reception trame readCom
bufferEnvoi = "";
erreur_cryptage = erreur_cryptage + 1;
envoiWrite = "";
if (erreur_cryptage > 3)
{
_Enneigeur1.ResetValues();
erreur_cryptage = 0;
EtatGrafcet_loop = 0;
}
else
{
EtatGrafcet_loop = 4;
}
break;
default:
EtatGrafcet_loop = 0;
break;
}
await Task.Delay(10);
}
EtatGrafcet_loop = 0;
}
public void Send_value_bluetooth(string nom_param, bool value)
{
if (value == true) Send_value_bluetooth( nom_param, 1); else Send_value_bluetooth(nom_param, 0);
}
public void Send_value_bluetooth(string nom_param, double value)
{
//la modif de Enneigeur1 entraine l'envoi d'une trame WRITE en bluetooth (si la liaison est OK)
string bufferEnvoi = "";
if (EtatGrafcet_loop >= 2)
{
switch(nom_param.ToLower())
{
Cases...
}
}
}
public void ExitApp()
{
// Disconnect from bth device
DependencyService.Get<IBtInterface>().Disconnect();
MessagingCenter.Unsubscribe<App, string>(this, "ReadDatas");
IsConnected = false;
if (_ct != null)
{
System.Diagnostics.Debug.WriteLine("Send a cancel to task!");
_ct.Cancel();
}
}
public GlobalViewModel()
{
Resources = new LocalizedResources(typeof(AppResources), Enneigeur1._SelectedLanguageKey
);
MessagingCenter.Subscribe<App>(this, "Sleep", (obj) =>
{
// When the app "sleep", I close the connection with bluetooth
if (IsConnected)
DependencyService.Get<IBtInterface>().Disconnect();
});
MessagingCenter.Subscribe<App>(this, "Resume", (obj) =>
{
// When the app "resume" I try to restart the connection with bluetooth
if (IsConnected)
DependencyService.Get<IBtInterface>().Connect(SelectedBthDevice);
});
this.InitCommand = new Command(() =>
{
// Try to connect to a bth device
DependencyService.Get<IBtInterface>().Init();
});
this.ConnectCommand = new Command(() =>
{
EtatGrafcet_loop = 0;
// Try to connect to a bth device
IsConnected = DependencyService.Get<IBtInterface>().Connect(SelectedBthDevice);
//second essai
if (IsConnected == false) IsConnected = DependencyService.Get<IBtInterface>().Connect(SelectedBthDevice);
if (IsConnected == true)
{
// initialisation des echange de données
MessagingCenter.Subscribe<App, string>(this, "ReadDatas", (sender, arg) =>
{
//inputBuffer = inputBuffer + arg;
inputBuffer = inputBuffer + arg;
});
Task.Run(async () => Loop());
}else
{
//erreur aux 2 tentatives de connection
//Task.Run(async () => ((App)Application.Current).OpenTextBoxDialog());
((App)Application.Current).OpenTextBoxDialog();
}
});
this.DisconnectCommand = new Command(() =>
{
EtatGrafcet_loop = 0;
ExitApp();
});
this.RefreshListDeviceCommand = new Command(() =>
{
try
{
ListOfDevices = DependencyService.Get<IBtInterface>().PairedDevices();
}
catch (Exception ex)
{
Application.Current.MainPage.DisplayAlert("Attention", ex.Message, "Ok");
}
});
// At startup, I load all paired devices
try
{
ListOfDevices = DependencyService.Get<IBtInterface>().PairedDevices();
}
catch (Exception ex)
{
Application.Current.MainPage.DisplayAlert("Attention", ex.Message, "Ok");
}
}
private object Await(App current)
{
throw new NotImplementedException();
}
public ICommand InitCommand { get; protected set; }
public ICommand ConnectCommand { get; protected set; }
public ICommand DisconnectCommand { get; protected set; }
public ICommand RefreshListDeviceCommand { get; protected set; }
public void SaveState(IDictionary<string, object> dictionary)
{
dictionary["SavedLanguage"] = Enneigeur1._SelectedLanguageKey;
dictionary["SavedUnitySystem_Pression"] = Enneigeur1.SelectedUnitySystem_Presure;
dictionary["SavedUnitySystem_Debit"] = Enneigeur1.SelectedUnitySystem_Flow;
dictionary["SavedUnitySystem_Temperature"] = Enneigeur1.SelectedUnitySystem_Temperature;
}
public void RestoreState(IDictionary<string, object> dictionary)
{
Enneigeur1.SelectedUnitySystem_Presure = GetDictionaryEntry(dictionary, "SavedUnitySystem_Pression", "Bars");
Enneigeur1.SelectedUnitySystem_Flow = GetDictionaryEntry(dictionary, "SavedUnitySystem_Debit", "m3/h");
Enneigeur1.SelectedUnitySystem_Temperature = GetDictionaryEntry(dictionary, "SavedUnitySystem_Temperature", "°C");
Enneigeur1.SelectedLanguageKey = GetDictionaryEntry(dictionary, "SavedLanguage", "en");
}
public T GetDictionaryEntry<T>(IDictionary<string, object> dictionary,
string key, T defaultValue)
{
if (dictionary.ContainsKey(key))
return (T)dictionary[key];
return defaultValue;
}
}

How to prevent duplicated random generated numbers

I have put random numbers into arrays but now I want to prevent it from being shown double in the Listbox. I already got a beginning to start with:
private bool InArray(int getal, int[] getallen, int aantal)
{
}
I think the solution is something like when the number is already in it return true and else just keep going with the code, but I can't think of how I can do this.
This is my code:
namespace Trekking
{
public partial class Form1 : Form
{
private Trekking trekking;
public Form1()
{
InitializeComponent();
btnLaatZien.Enabled = false;
btnSerie.Enabled = false;
btnSorteer.Enabled = false;
btnStart.Enabled = true;
btnStop.Enabled = false;
btnTrek.Enabled = false;
}
private void btnStart_Click(object sender, EventArgs e)
{
int AantalGewenst = Convert.ToInt32(tbInvoerAantalGewenst.Text);
int Maxwaarde = Convert.ToInt32(tbInvoerMaxwaarde.Text);
trekking = new Trekking(Maxwaarde, AantalGewenst);
btnTrek.Enabled = true;
btnStop.Enabled = true;
btnStart.Enabled = false;
if (Maxwaarde > 90)
{
MessageBox.Show("Uw getal mag niet boven de 90 zijn!");
btnStart.Enabled = true;
btnTrek.Enabled = false;
btnStop.Enabled = false;
}
else if (Maxwaarde < 0)
{
MessageBox.Show("Dit aantal is niet mogelijk!");
btnStart.Enabled = true;
btnTrek.Enabled = false;
btnStop.Enabled = false;
}
else if (AantalGewenst > 45)
{
MessageBox.Show("Uw getal mag niet boven de 45 zijn!");
btnStart.Enabled = true;
btnTrek.Enabled = false;
btnStop.Enabled = false;
}
if (AantalGewenst < 1)
{
MessageBox.Show("Dit aantal is niet mogelijk!");
btnStart.Enabled = true;
btnTrek.Enabled = false;
btnStop.Enabled = false;
}
else if (Maxwaarde / AantalGewenst < 2)
{
MessageBox.Show("Uw maxwaarde moet minstens het dubbele van Aantal Gewenst zijn!");
btnStart.Enabled = true;
btnTrek.Enabled = false;
btnStop.Enabled = false;
}
else
{
if (AantalGewenst <= 45)
btnStart.Enabled = false;
btnTrek.Enabled = true;
btnStop.Enabled = true;
}
}
public void getSingleNumber(int hoeveel)
{
int Getal = trekking.GeefGetal(hoeveel);
lbResultaat.Items.Add(Getal);
}
public void getTrekkingData()
{
for (int p = 0; p < trekking.AantalGewenst; p++)
{
int alleGetallen = trekking.GeefGetal(p);
lbResultaat.Items.Add(alleGetallen);
}
}
int count = 0;
private void btnTrek_Click(object sender, EventArgs e)
{
int gewenst = trekking.AantalGewenst;
label3.Text = Convert.ToString(count);
btnStop.Enabled = true;
btnSerie.Enabled = false;
trekking.TrekGetal();
getSingleNumber(count);
count++;
if (count == trekking.AantalGewenst)
{
MessageBox.Show("Alle gewenste trekkingen zijn uitgevoerd");
btnTrek.Enabled = false;
btnStop.Enabled = true;
btnSerie.Enabled = false;
}
}
private void btnStop_Click(object sender, EventArgs e)
{
lbResultaat.Items.Clear();
btnLaatZien.Enabled = false;
btnSerie.Enabled = false;
btnSorteer.Enabled = false;
btnStart.Enabled = true;
btnStop.Enabled = false;
btnTrek.Enabled = false;
tbInvoerAantalGewenst.Enabled = true;
tbInvoerMaxwaarde.Enabled = true;
count = 0;
}
private void tbInvoerMaxwaarde_KeyPress(object sender, KeyPressEventArgs e)
{
char ch = e.KeyChar;
e.Handled = !(Char.IsDigit(ch) || (ch == '-') || (ch < ' '));
}
private void k(object sender, KeyPressEventArgs e)
{
char ch = e.KeyChar;
e.Handled = !(Char.IsDigit(ch) || (ch == '-') || (ch < ' '));
}
private bool InArray(int getal, int[] getallen, int aantal)
{
}
}
}
The class:
namespace Trekking
{
class Trekking
{
//attributes
private Random random;
private int[] getallen;
//properties
public int Maxwaarde { get; private set; } //maximum waarde van te trekken getal
public int AantalGetrokken { get; private set; } //aantal getrokken getallen
public int AantalGewenst { get; private set; } //aantal te trekken getallen
public bool IsTenEinde { get; private set; } //true als alle getallen gerokken
//constructor en methoden
public Trekking(int Maxwaarde, int AantalGewenst)
{
this.Maxwaarde = Maxwaarde;
this.AantalGewenst = AantalGewenst;
AantalGetrokken = 0;
IsTenEinde = false;
random = new Random();
getallen = new int[AantalGewenst];
}
//methods
public void TrekGetal()
{
int erbijArray;
for (int i = 0; i < AantalGewenst; i++)
{
erbijArray = random.Next(1, Maxwaarde);
getallen[i] = erbijArray;
AantalGetrokken++;
}
}
public int GeefGetal(int number)
{
return getallen[number];
}
//sorteert getrokken getallen in array "getallen"
public void Sort()
{
Array.Sort(getallen);
}
}
}
I simplified your problem (leaving out min, max, max number etc).
Basically, you can keep a list of things you already encountered:
public class Lottery
{
public HashSet<int> _previousNumbers = new HashSet<int>();
private Random random = new Random();
public int GetNextNumber()
{
int next;
do
{
next = random.Next();
}
while (_previousNumbers.Contains(next));
_previousNumbers.Add(next);
return next;
}
}
A set does not contain duplicates and is efficient in its Contains implementation.

Player cannot double jump

I am following a tutorial on YouTube and everything is working fine until now, except I can only have one jump with this code, any advice ?
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Player : MonoBehaviour {
public float power = 500;
public int jumpHeight = 1000;
public bool isFalling = false;
public int Score;
public Text SCORE;
public GameObject YOUDIED;
private int health = 3;
public GameObject health1;
public GameObject health2;
public GameObject health3;
public int Highscore;
private bool canDoubleJump;
private bool jumpOne;
private bool jumpTwo;
// Use this for initialization
void Start () {
YOUDIED.SetActive(false);
Highscore = PlayerPrefs.GetInt ("Highscore", 0);
jumpOne = false;
jumpTwo = false;
canDoubleJump = false;
}
void Update() {
if(Input.GetMouseButtonDown(0) && health == 0) {
Time.timeScale = 1f;
health = 3;
Application.LoadLevel(0);
}
if (health == 3) {
health1.SetActive (true);
health2.SetActive (true);
health3.SetActive (true);
}
if (health == 2) {
health1.SetActive (true);
health2.SetActive (true);
health3.SetActive (false);
}
if (health == 1) {
health1.SetActive (true);
health2.SetActive (false);
health3.SetActive (false);
}
if (health == 0) {
health1.SetActive (false);
health2.SetActive (false);
health3.SetActive (false);
}
if (health <= 0) {
YOUDIED.SetActive (true);
Time.timeScale = 0.0f;
}
SCORE.text = "Score " + Score;
transform.Translate(Vector2.right * power * Time.deltaTime);
if (Input.GetKeyDown(KeyCode.Space) && isFalling == false) {
jumpOne = true;
canDoubleJump = true;
isFalling = true;
}
if (Input.GetKeyDown(KeyCode.Space) && isFalling == true && canDoubleJump == true) {
jumpTwo = true;
canDoubleJump = false;
}
}
void FixedUpdate() {
if (jumpOne == true) {
GetComponent<Rigidbody2D>().AddForce(Vector2.up * jumpHeight);
jumpOne = false;
}
if (jumpTwo == true) {
GetComponent<Rigidbody2D>().AddForce(Vector2.up * jumpHeight);
jumpTwo = false;
}
}
void OnCollisionStay2D(Collision2D coll) {
if (coll.gameObject.tag == "Ground") {
isFalling = false;
canDoubleJump = false;
}
}
public void ScorePlus(int NewScore) {
Score += NewScore;
if(Score >= Highscore) {
Highscore = Score;
PlayerPrefs.SetInt ("Highscore", Highscore);
}
}
void OnTriggerEnter2D(Collider2D coll) {
if (coll.gameObject.tag == "Death") {
health -= 1;
}
}
}
canDoubleJump should be set to true here
void OnCollisionStay2D(Collision2D coll) {
if (coll.gameObject.tag == "Ground") {
isFalling = false;
canDoubleJump = false;
}
also in the first jump you need to set isFalling to true
if (jumpOne == true) {
GetComponent<Rigidbody2D>().AddForce(Vector2.up * jumpHeight);
jumpOne = false;
isFalling = true;
}
That should do the trick
Solved,
I put an else if statement instead of only an if
if (Input.GetKeyDown(KeyCode.Space) && isFalling == false) {
jumpOne = true;
canDoubleJump = true;
isFalling = true;
}else if (Input.GetKeyDown(KeyCode.Space) && isFalling == true && canDoubleJump == true) {
jumpTwo = true;
canDoubleJump = false;
}

Categories

Resources