The snake head 0 does not move anywhere when Console.ReadKey() happens.
Here is the full code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SimpleSnakeGame_ConsoleApp
{
internal class Program
{
public bool gameOver = true;
public int width = 20;
public int height = 20;
//HEAD POS
public int x, y;
//FRUIT POS
public int fruitX, fruitY;
public int score;
//bir kere basınca oraya gitmeni sağlayacak enum
enum eDirection { STOP = 0, LEFT, RIGHT, UP, DOWN };
eDirection dir; //enum class gibi çalışıyor enum'dan dir isimli bir object yarattık
static void Main(string[] args)
{
Program oyun = new Program();
oyun.Setup();
oyun.Draw();
oyun.Input();
oyun.Logic();
Console.ReadLine();
}
//Setting Up the MAP
public void Setup()
{
gameOver = false;
string a = "!!!!! SİMPLE SNAKE GAME !!!!!";
Console.WriteLine(gameOver.ToString() + " " + a, "{0}" + "{1}");
dir = eDirection.STOP;
x = width / 2;
y = height / 2;
Random rnd = new Random();
fruitX = rnd.Next(1, 19);
fruitY = rnd.Next(1, 19);
score = 0;
}
void Draw()
{
for (int j = 0; j < height; j++)
{
for (int i = 0; i < width; i++)
{
if (i == y && j == x)
{
Console.Write("0");
}
else if (i == fruitY && j == fruitX)
{
Console.Write("F");
}
else if (j > 0 && j < height - 1 && i > 0 && i < width - 1)
{
Console.Write(" ");
}
else
{
Console.Write("#");
}
}
Console.WriteLine();
}
Console.WriteLine();
}
void Input()
{
ConsoleKey key;
// Key is available - read it
key = Console.ReadKey(true).Key;
if (key == ConsoleKey.A)
{
dir = eDirection.LEFT;
}
else if (key == ConsoleKey.D)
{
dir = eDirection.RIGHT;
}
else if (key == ConsoleKey.W)
{
dir = eDirection.UP;
}
else if (key == ConsoleKey.S)
{
dir = eDirection.DOWN;
}
else if (key == ConsoleKey.X)
{
gameOver=true;
}
}
void Logic()
{
switch (dir)
{
case eDirection.LEFT:
x--;
break;
case eDirection.RIGHT:
x++;
break;
case eDirection.UP:
y--;
break;
case eDirection.DOWN:
y++;
break;
default:
break;
}
}
}
}
I guess the problem is Console.ReadKey() function here:
void Input()
{
ConsoleKey key;
// Key is available - read it
key = Console.ReadKey(true).Key;
if (key == ConsoleKey.A)
{
dir = eDirection.LEFT;
}
else if (key == ConsoleKey.D)
{
dir = eDirection.RIGHT;
}
else if (key == ConsoleKey.W)
{
dir = eDirection.UP;
}
else if (key == ConsoleKey.S)
{
dir = eDirection.DOWN;
}
else if (key == ConsoleKey.X)
{
gameOver=true;
}
}
However I do not know what to replace Console.ReadKey() with and how to do it.
Here is the OUTPUT:
You are correct about Console.ReadKey() being the problem as it is blocking and will pause the game until a key is pressed.
You will need to do something like this:
if (Console.KeyAvailable)
{
ConsoleKeyInfo key = Console.ReadKey(true);
// process key here
}
This way you are reading from the console without blocking until a key is pressed.
Related
This is the card I'm working with and I'm very confused to why the dealer isn't hitting when instructed to. I've rearranged my code tried different methods but it still doesn't seem to be working. If someone can help me solve this C# script I'd be very thankful.
using System;
using System.Collections.Generic;
public class MainClass
{
public static int PlayerTotal;
public static int DealerTotal;
static Random random = new Random();
public static List<int> cards = new List<int>();
public static List<int> hand = new List<int>();
public static List<int> DealerHand = new List<int>();
public static bool GameOver = false;
public static void Main (string[] args)
{
// Players hand gets created
for (int i = 2; i <= 11; i++)
{
cards.Add(i);
}
for (int i = 0; i < 2; i++)
{
int index = random.Next(cards.Count);
hand.Add(cards[index]);
}
foreach (int a in hand)
{
Console.WriteLine("{0}", a);
PlayerTotal = PlayerTotal + a;
if(PlayerTotal == 22 || PlayerTotal == 21)
{
Console.WriteLine("You won!");
GameOver = true;
}
}
Console.WriteLine("Your hand total is " + PlayerTotal);
// Dealer hand being created
for(int i = 0; i < 2; i++)
{
int index = random.Next(cards.Count);
DealerHand.Add(cards[index]);
}
foreach(int a in DealerHand)
{
Console.WriteLine("{0}", a);
DealerTotal = DealerTotal + a;
if(DealerTotal == 22 || DealerTotal == 21)
{
Console.WriteLine("The dealer won!");
GameOver = true;
}
}
Console.WriteLine("The dealer hand total is " + DealerTotal);
// Player choice to hit or stay
while (PlayerTotal < 21 && GameOver == false)
{
Console.WriteLine("Do you want to hit or stand? h/s");
string choice = Console.ReadLine();
if (choice == "h")
{
PlayerHit();
}
else if (choice == "s")
{
Console.WriteLine("You stood");
}
}
while (DealerTotal < 21 && GameOver == false )
{
if(DealerTotal <= 16)
{
DealerHit();
}
else
{
Console.WriteLine("The dealer stood");
}
}
}
public static void PlayerHit()
{
for (int i = 0; i < 1; i++)
{
int index = random.Next(cards.Count);
int hitCard = cards[index];
hand.Add(hitCard);
PlayerTotal = PlayerTotal + hitCard;
Console.WriteLine("You got a " + hitCard);
Console.WriteLine("Your new total is " + PlayerTotal);
if(PlayerTotal > 21)
{
Console.WriteLine("You lost!");
GameOver = true;
}
else if (PlayerTotal == 21)
{
Console.WriteLine("You won!");
GameOver = true;
}
}
}
public static void DealerHit()
{
for (int i = 0; i < 1; i++)
{
int index = random.Next(cards.Count);
int DealerHitCard = cards[index];
DealerHand.Add(DealerHitCard);
DealerTotal = DealerTotal + DealerHitCard;
int DealerHitCardNew = DealerHitCard;
Console.WriteLine("The dealer got a " + DealerHitCardNew);
Console.WriteLine("The dealers total is now " + DealerTotal);
if (DealerTotal > 21)
{
Console.WriteLine("You Won!");
GameOver = true;
}
else if (DealerTotal == 21)
{
Console.WriteLine("You Lost!");
GameOver = true;
}
}
}
}
Any help would be very appreciated. My school has set us homework that we have to create a sort of application, and i thought this would be fun to make.
This line here:
while(PlayerTotal < 21 && GameOver == false) {
That will only be true if you bust or get 21. If you stand, you will never exit this loop. Add a break to the stand option:
} else if(choice == "s"){
Console.WriteLine("You stood");
break;
}
Unfortunately, you have the same issue in the following loop:
while(DealerTotal < 21 && GameOver == false ) {
Add a break to the correct block to exit the loop when the dealer stands. Finally, you will need to add winning/losing logic after both the player and the dealer have stood.
I really don't know how to phrase my title, help me out.
I am having an issue with a game I am making. The game's objective is to eat an apple that appears on the map for points. When you eat it, another apple appears in a random location inside the little box.
As you see the apple goes out of the bounds. But it doesn't always happen on the first time I get to it. Also, there is a # at the very far right for some reason.
Here is the code:
The drawing happens in the Draw() method, so you should look at that first.
using System;
public class MainClass
{
public const int WIDTH = 20, HEIGHT = 20;
public static int Points, X, Y, FruitX, FruitY;
public static bool GameOver = false;
public static string Direction;
public static Random Rand = new Random();
public static void Start()
{
Console.Clear();
GameOver = false;
Direction = "Stop";
X = WIDTH/2;
Y = HEIGHT/2;
FruitX = Rand.Next(100)%WIDTH/2;
FruitY = Rand.Next(100)%HEIGHT/2;
}
public static void Draw()
{
Console.Clear();
for (int i = 0; i < WIDTH; i++)
{
Console.Write("# ");
}
for (int i = 0; i < HEIGHT - 1; i++)
{
for (int j = 0; j < WIDTH; j++)
{
Console.Write(j == 0 ? "# " : " ");
if (j == WIDTH - 1)
{
Console.Write("# ");
}
if (i == Y && j == X)
{
Console.Write("O");
}
else if (i == FruitY && j == FruitX)
{
Console.Write("🍎");
}
else
{
Console.Write(" ");
}
}
Console.WriteLine();
}
for (int i = 0; i < WIDTH + 1; i++)
{
Console.Write("# ");
}
Console.WriteLine($"\nPoints: {Points}");
}
public static void InputHandler()
{
ConsoleKeyInfo UserInput = Console.ReadKey();
switch (UserInput.KeyChar)
{
case 'w':
Direction = "Up";
break;
case 'a':
Direction = "Left";
break;
case 's':
Direction = "Down";
break;
case 'd':
Direction = "Right";
break;
case 'x':
GameOver = true;
break;
default:
break;
}
}
public static void GameHandler()
{
switch (Direction)
{
case "Up":
Y--;
break;
case "Down":
Y++;
break;
case "Left":
X--;
break;
case "Right":
X++;
break;
default:
break;
}
GameOver = X > WIDTH || X < 0 || Y < 0 || Y > HEIGHT;
if (X == FruitX && Y == FruitY)
{
Points += 10;
FruitX = Rand.Next(100)%WIDTH/2;
FruitY = Rand.Next(100)%HEIGHT/2;
}
}
public static void Main(string[] args)
{
Start();
while (!GameOver)
{
Draw();
InputHandler();
GameHandler();
}
Console.Clear();
}
}
Good day. I have a problem using unity with arduino,i am using serial port as means of communication of unity to arduino. I am just sending strings from unity to arduino.
After the first player turn an IOException : Access is Denied occurs?. I am unable to play the second players turn because unity stopped after the first player turn.
Then it throws , IOException: Access is Denied
UNITY CODE
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using System.IO.Ports;
public class SceneManagement : MonoBehaviour
{
SerialPort sp = new SerialPort("COM3", 9600);
// Use this for initialization
public void CountPlayer()
{
SceneManager.LoadScene("CountPlayer");
}
public void RandomSubject()
{
SceneManager.LoadScene("RandomSubject");
}
public void Game()
{
if (!sp.IsOpen)
{
sp.Open();
sp.WriteTimeout = 100;
Debug.Log("Port successfully opened");
}
sp.Write("green");
SceneManager.LoadScene("Game1");
}
}
The Above code is the fisrt to execute it will send "green" string to arduino
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO.Ports;
public class ButtonCheckAnswerController : MonoBehaviour {
SerialPort sp = new SerialPort("COM3", 9600);
public Text CorrectWrongText;
public GameManager GameManager;
public CheckSubjectAndDifficultyController CheckSubjectAndDifficultyController;
public NextPlayerTurn NextPlayerTurn;
public string correct = "CORRECT";
public string wrong = "WRONG";
public GameObject bgwrong;
public GameObject bgcorrect;
public GameObject GameObject;
public GameObject CorrectAudio;
public GameObject WrongAudio;
public GameObject yehey;
public GameObject awww;
public List<Text> PlayerText;
public List<int> PlayerScores;
public List<GameObject> Players;
public string PlayerString;
public string Difficulty;
public PlayerWinController PlayerWinController;
void Update()
{
if(gameObject.activeInHierarchy == true)
{
Invoke("delayScore", .25f);
}
}
void delayScore()
{
if (PlayerString == "Player1")
{
if(Players[0].activeInHierarchy == false)
{
PlayerText[0].text = "Score = " + PlayerScores[0].ToString();
Players[1].SetActive(false);
Players[2].SetActive(false);
Players[0].SetActive(true);
}
}
else if (PlayerString == "Player2")
{
if (Players[1].activeInHierarchy == false)
{
PlayerText[1].text = "Score = " + PlayerScores[1].ToString();
Players[0].SetActive(false);
Players[2].SetActive(false);
Players[1].SetActive(true);
}
}
else if (PlayerString == "Player3")
{
if (Players[2].activeInHierarchy == false)
{
PlayerText[2].text = "Score = " + PlayerScores[2].ToString();
Players[0].SetActive(false);
Players[1].SetActive(false);
Players[2].SetActive(true);
}
}
if (!sp.IsOpen)
{
sp.Open();
sp.WriteTimeout = 100;
if (PlayerString == "Player3")
{
sp.Write(PlayerScores[2].ToString());
}
else if (PlayerString == "Player2")
{
sp.Write(PlayerScores[1].ToString());
}
else if (PlayerString == "Player1")
{
sp.Write(PlayerScores[0].ToString());
}
}
}
public void checkAnswer(bool isCorrect)
{
if (!sp.IsOpen)
{
sp.Open();
sp.WriteTimeout = 100;
}
CorrectAudio.SetActive(false);
WrongAudio.SetActive(false);
yehey.SetActive(false);
awww.SetActive(false);
bgwrong.SetActive(false);
bgcorrect.SetActive(false);
Difficulty = CheckSubjectAndDifficultyController.Difficulty;
if (isCorrect == true)
{
CorrectWrongText.text = correct;
bgwrong.SetActive(false);
bgcorrect.SetActive(true);
CorrectAudio.SetActive(true);
yehey.SetActive(true);
if (PlayerString == "Player1")
{
if (Difficulty == "Easy")
{
PlayerScores[0]++;
}
else if (Difficulty == "Medium")
{
PlayerScores[0] += 3;
}
else
{
PlayerScores[0] += 5;
}
Debug.Log(PlayerScores[0]);
sp.Write(PlayerScores[0].ToString());
//sp.Close();
}
else if (PlayerString == "Player2")
{
if (Difficulty == "Easy")
{
PlayerScores[1]++;
}
else if (Difficulty == "Medium")
{
PlayerScores[1] += 3;
}
else
{
PlayerScores[1] += 5;
}
sp.Write(PlayerScores[1].ToString());
}
else if (PlayerString == "Player3")
{
if (Difficulty == "Easy")
{
PlayerScores[2]++;
}
else if (Difficulty == "Medium")
{
PlayerScores[2] += 3;
}
else
{
PlayerScores[2] += 5;
}
sp.Write(PlayerScores[2].ToString());
}
PlayerWinController.checkScores();
}
else
{
CorrectWrongText.text = wrong;
bgwrong.SetActive(true);
bgcorrect.SetActive(false);
WrongAudio.SetActive(true);
awww.SetActive(true);
if (PlayerString == "Player1")
{
if (Difficulty == "Easy")
{
PlayerScores[0]--;
if (PlayerScores[0] < 0)
{
PlayerScores[0] = 0;
}
}
else if (Difficulty == "Medium")
{
PlayerScores[0] -= 3;
if (PlayerScores[0] < 0)
{
PlayerScores[0] = 0;
}
}
else
{
PlayerScores[0] -= 5;
if (PlayerScores[0] < 0)
{
PlayerScores[0] = 0;
}
}
sp.Write(PlayerScores[0].ToString());
}
else if (PlayerString == "Player2")
{
if (Difficulty == "Easy")
{
PlayerScores[1]--;
if (PlayerScores[1] < 0)
{
PlayerScores[1] = 0;
}
}
else if (Difficulty == "Medium")
{
PlayerScores[1] -= 3;
if (PlayerScores[1] < 0)
{
PlayerScores[1] = 0;
}
}
else
{
PlayerScores[1] -= 5;
if (PlayerScores[1] < 0)
{
PlayerScores[1] = 0;
}
}
sp.Write(PlayerScores[1].ToString());
}
else if (PlayerString == "Player3")
{
if (Difficulty == "Easy")
{
PlayerScores[2]--;
if (PlayerScores[2] < 0)
{
PlayerScores[2] = 0;
}
}
else if (Difficulty == "Medium")
{
PlayerScores[2] -= 3;
if (PlayerScores[2] < 0)
{
PlayerScores[2] = 0;
}
}
else
{
PlayerScores[2] -= 5;
if (PlayerScores[2] < 0)
{
PlayerScores[2] = 0;
}
}
sp.Write(PlayerScores[2].ToString());
}
}
GameManager.disableRemoveFromList();
GameManager.Timer = GameManager.DefaultTimer;
}
}
in here the it will send the initial players score and the score after answering a question
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO.Ports;
public class NextPlayerTurn : MonoBehaviour
{
SerialPort sp = new SerialPort("COM3", 9600);
public GameObject Player1Turn;
public GameObject Player2Turn;
public GameObject Player3Turn;
public GameObject PanelPlayerTurn;
public string CheckPlayer;
public string PlayerTurn;
int players;
public ButtonCheckAnswerController ButtonCheckAnswerController;
public void checkNextPlayer()
{
PanelPlayerTurn.SetActive(true);
players = PlayerPrefs.GetInt("CountPlayingPlayers");
PlayerTurn = CheckPlayer;
if (!sp.IsOpen)
{
sp.Open();
}
else
{
if (players == 2)
{
if (CheckPlayer == "Player1")
{
Player1Turn.SetActive(false);
Player2Turn.SetActive(true);
CheckPlayer = "Player2";
}
else
{
Player1Turn.SetActive(true);
Player2Turn.SetActive(false);
CheckPlayer = "Player1";
}
}
else
{
if (CheckPlayer == "Player1")
{
Player1Turn.SetActive(false);
Player2Turn.SetActive(true);
Player3Turn.SetActive(false);
CheckPlayer = "Player2";
}
else if (CheckPlayer == "Player2")
{
Player1Turn.SetActive(false);
Player2Turn.SetActive(false);
Player3Turn.SetActive(true);
CheckPlayer = "Player3";
}
else
{
Player1Turn.SetActive(true);
Player2Turn.SetActive(false);
Player3Turn.SetActive(false);
CheckPlayer = "Player1";
}
}
if (CheckPlayer == "Player1")
{
sp.Write("green");
}
else if (CheckPlayer == "Player2")
{
sp.Write("red");
}
else if (CheckPlayer == "Player3")
{
sp.Write("blue");
}
ButtonCheckAnswerController.PlayerString = CheckPlayer;
gameObject.SetActive(false);
}
}
}
and lastly here is where to switch or go to next players turn
ARDUINO CODE
#include <FastLED.h>
#define LED_PIN 5
#define NUM_LEDS 51
#define BRIGHTNESS 20
#define LED_TYPE WS2812B
#define COLOR_ORDER RGB
CRGB leds[NUM_LEDS];
String playerColor = "";
String playerQdiff = "";
String playerAnswer = "";
String playerAnsCndtn = "";
String difficulty = "";
String answerCndtn = "";
int i,Red,Green,Blue;
int lastile,initile;
String tileStrt="";
String tileEnd="";
void showProgramRandom(int numIterations, long delayTime) {
for (int iteration = 0; iteration < numIterations; ++iteration) {
for (int i = 0; i < NUM_LEDS; ++i) {
leds[i] = CHSV(random8(),245,255); // hue, saturation, value
}
FastLED.show();
delay(delayTime);
}
}
void showProgramShiftMultiPixel(long delayTime) {
for (int i = 0; i < NUM_LEDS; ++i) {
for (int j = i; j > 0; --j) {
leds[j] = leds[j-1];
}
CRGB newPixel = CHSV(random8(), 255, 255);
leds[0] = newPixel;
FastLED.show();
delay(delayTime);
}
}
String getdatainit() {
while (!Serial.available()) {
showProgramShiftMultiPixel(50);
}
return Serial.readStringUntil("\n");
}
void LedsCleanUp() {
for (int led = 0; led < NUM_LEDS; ++led) {
leds[led] = CRGB::Black;
}
FastLED.show();
}
void setup() {
Serial.begin(9600);
FastLED.addLeds<LED_TYPE, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection( TypicalLEDStrip );
FastLED.setBrightness( BRIGHTNESS );
}
void loop() {
GetPlayerColor();
GetPlayerInitialTile();
GetPlayersLastTile();
}
void GetPlayerColor()
{
while(!Serial.available())
{
showProgramRandom(10, 250);
}
LedsCleanUp();
playerColor = Serial.readString();
Serial.flush();
if (playerColor == "red")
{
Red = 255;
Green = 0;
Blue = 0;
}
else if(playerColor == "green")
{
Red = 0;
Green = 255;
Blue = 0;
}
else if(playerColor == "blue")
{
Red = 0;
Green = 0;
Blue = 255;
}
}
void ShowPlayerColor()
{
for (i = 0; i <= NUM_LEDS; i++)
{
leds[i] = CRGB (Green, Red, Blue);
FastLED.show();
}
delay(2000);
}
void GetPlayerInitialTile()
{
while(!Serial.available())
{
showProgramRandom(10,250);
}
Serial.flush();
tileStrt = Serial.readString();
LedsCleanUp();
initile = tileStrt.toInt();
leds[initile] = CRGB (Green, Red, Blue);
FastLED.show();
delay(2000);
}
void GetPlayersLastTile()
{
while(!Serial.available())
{
;
}
Serial.flush();
tileEnd = Serial.readString();
LedsCleanUp();
lastile = tileEnd.toInt();
if (lastile < initile)
{
for (i = initile; i >= lastile; i--)
{
leds[i] = CRGB (Green, Red, Blue);
delay(650);
FastLED.show();
}
delay(650);
LedsCleanUp();
}
else
{
for (i = initile; i <= lastile; i++)
{
leds[i] = CRGB (Green, Red, Blue);
delay(650);
FastLED.show();
}
delay(650);
LedsCleanUp();
}
for (i = 0; i<=3; i++ )
{
leds[lastile] = CRGB (Green, Red, Blue);
delay(650);
FastLED.show();
leds[lastile] = CRGB (0,0,0);
delay(650);
FastLED.show();
}
}
Only one process can use a specific serial port at a time.
COM3 is already opened by SceneManagement , so when others asks to access COM3 will occur access deny.
Use a manager class to handle the SerialPort object, or just call
GetComponent<SceneManagement>().GetSP()
to get the existing serial port in other scripts.
so i made this simple snake game i made with a guide for as a school project now i want to improve it by adding a score counter and increase the movement speed of the snake every time you get the food help is appreciated
this is the problem i'm currently having
enter image description here
namespace Snake
{
class Program
{
static void Main(string[] args)
{
Console.WindowHeight = 32;
Console.WindowWidth = 64;
int screenwidth = Console.WindowWidth;
int screenheight = Console.WindowHeight;
Random randomnummer = new Random();
int emtiaz = 5;
int bakht = 0;
pixel gz = new pixel();
gz.xpos = screenwidth / 2;
gz.ypos = screenheight / 2;
gz.rangsafe = ConsoleColor.Red;
string movement = "RIGHT";
List<int> xposlijf = new List<int>();
List<int> yposlijf = new List<int>();
int berryx = randomnummer.Next(0, screenwidth);
int berryy = randomnummer.Next(0, screenheight);
DateTime tijd = DateTime.Now;
DateTime tijd2 = DateTime.Now;
string buttonpressed = "no";
while (true)
{
Console.Clear();
if (gz.xpos == screenwidth - 1 || gz.xpos == 0 || gz.ypos == screenheight - 1 || gz.ypos == 0)
{
bakht = 1;
}
for (int i = 0; i < screenwidth; i++)
{
Console.SetCursorPosition(i, 0);
Console.Write("*");
}
for (int i = 0; i < screenwidth; i++)
{
Console.SetCursorPosition(i, screenheight - 1);
Console.Write("*");
}
for (int i = 0; i < screenheight; i++)
{
Console.SetCursorPosition(0, i);
Console.Write("*");
}
for (int i = 0; i < screenheight; i++)
{
Console.SetCursorPosition(screenwidth - 1, i);
Console.Write("v");
}
Console.ForegroundColor = ConsoleColor.Green;
if (berryx == gz.xpos && berryy == gz.ypos)
{
emtiaz++;
berryx = randomnummer.Next(1, screenwidth - 2);
berryy = randomnummer.Next(1, screenheight - 2);
}
for (int i = 0; i < xposlijf.Count(); i++)
{
Console.SetCursorPosition(xposlijf[i], yposlijf[i]);
Console.Write("*");
if (xposlijf[i] == gz.xpos && yposlijf[i] == gz.ypos)
{
bakht = 1;
}
}
if (bakht == 1)
{
break;
}
Console.SetCursorPosition(gz.xpos, gz.ypos);
Console.ForegroundColor = gz.rangsafe;
Console.Write("*");
Console.SetCursorPosition(berryx, berryy);
Console.ForegroundColor = ConsoleColor.DarkBlue;
Console.Write("*");
tijd = DateTime.Now;
buttonpressed = "no";
while (true)
{
tijd2 = DateTime.Now;
if (tijd2.Subtract(tijd).TotalMilliseconds > 500) { break; }
if (Console.KeyAvailable)
{
ConsoleKeyInfo toets = Console.ReadKey(true);
if (toets.Key.Equals(ConsoleKey.UpArrow) && movement != "DOWN" && buttonpressed == "no")
{
movement = "UP";
buttonpressed = "yes";
}
if (toets.Key.Equals(ConsoleKey.DownArrow) && movement != "UP" && buttonpressed == "no")
{
movement = "DOWN";
buttonpressed = "yes";
}
if (toets.Key.Equals(ConsoleKey.LeftArrow) && movement != "RIGHT" && buttonpressed == "no")
{
movement = "LEFT";
buttonpressed = "yes";
}
if (toets.Key.Equals(ConsoleKey.RightArrow) && movement != "LEFT" && buttonpressed == "no")
{
movement = "RIGHT";
buttonpressed = "yes";
}
}
}
xposlijf.Add(gz.xpos);
yposlijf.Add(gz.ypos);
switch (movement)
{
case "UP":
gz.ypos--;
break;
case "DOWN":
gz.ypos++;
break;
case "LEFT":
gz.xpos--;
break;
case "RIGHT":
gz.xpos++;
break;
}
if (xposlijf.Count() > emtiaz)
{
xposlijf.RemoveAt(0);
yposlijf.RemoveAt(0);
}
}
Console.SetCursorPosition(screenwidth / 5, screenheight / 2);
Console.WriteLine("bazi ra bakhti, emtiaz: " + emtiaz);
Console.SetCursorPosition(screenwidth / 5, screenheight / 2 + 1);
}
class pixel
{
public int xpos { get; set; }
public int ypos { get; set; }
public ConsoleColor rangsafe { get; set; }
}
}
}
take a look at the following 2 pieces of code
if (tijd2.Subtract(tijd).TotalMilliseconds > 500)
make a variable and use that instead of 500
Than use that variable in the following block
if (berryx == gz.xpos && berryy == gz.ypos)
{
emtiaz++;
berryx = randomnummer.Next(1, screenwidth - 2);
berryy = randomnummer.Next(1, screenheight - 2);
}
and test and make changes and see how your game behaves, it will guide you to what you are trying to do.
Your variable emtiaz is already counting number of times snake gets food
{
static int[] location = { 0, 0 };
static int player = 0;
static void runGame()
{
int start = Convert.ToInt32(Console.ReadLine());
if (start == 1)
{
location1();
}
else if (start == 2)
{
location2();
}
else if (start == 3)
{
location3();
}
else if (start == 4)
{
location4();
}
}
static void swapPlayer()
{
if (player == 1)
{
player = 0;
}
else
{
player = 1;
}
}
static void location1()
{
Console.WriteLine(" Player " + (player + 1) + " , you are in the kitchen you can go to either \n1: Living room \n2: Bathroom ");
int input = int.Parse(Console.ReadLine());
if (input == 1) {
location[player] = 2;
start = 2;
swapPlayer();
location2();
}
else if (input == 2) {
location[player] = 3;
start = 3;
swapPlayer();
location3();
}
}
static void location2()
{
Console.WriteLine(" Player " + (player + 1) + " you are in the living room you can go to either \n1: Kitchen\n2: Bedroom ");
int input = int.Parse(Console.ReadLine());
if (input == 1) {
location[player] = 1;
start = 1;
swapPlayer();
location1();
}
else if (input == 2) {
location[player] = 4;
start = 4;
swapPlayer();
location4();
}
}
static void location3()
{
Console.WriteLine(" Player " + (player + 1) + " you are in the bathroom you can go to either \n1: Kitchen \n2: Bedroom ");
int input = int.Parse(Console.ReadLine());
if (input == 1)
{
location[player] = 1;
start = 1;
swapPlayer();
location1();
}
else if (input == 2)
{
location[player] = 4;
start = 4;
swapPlayer();
location4();
}
}
static void location4() {
Console.WriteLine(" Player " + (player + 1) + ", you are in the kitchen you can go to either \n1: Living room \n2: Bathroom ");
int input = int.Parse(Console.ReadLine());
if (input == 1)
{
location[player] = 1;
start = 1;
swapPlayer();
location2();
}
else if (input == 2)
{
location[player] = 4;
start = 4;
swapPlayer();
location3();
}
}
static void Main(string[] args)
{
Console.WriteLine("welcome , find the ghost and navigate through the house");
Console.Write("You are in the main hall way you can go to any of these rooms");
Console.Write(" kitchen, living room, bath room , bedroom");
Console.WriteLine("choose a room number 1 , 4 from the list ");
int start = Convert.ToInt32(Console.ReadLine());
bool play = true;
while (play== true)
{
runGame();
}
}
}
Here is the code behind a simple 2 player text adventure I am making , I was wondering where I have used the variable start in the runGame procedure how can i access that outside of the procedure , or is that not possible in which case do you have another solution on how I can get around this.
You can't, and that's the point of local variables: the world outside shouldn't care about their value (or even their existence)
If you want to access the vatiable from multiple methods, you'll have to elevate it to a (in this case static) class member:
static int[] location = { 0, 0 };
static int player = 0;
static int start;