Code:
private void sprites_updater_Tick(object sender, EventArgs e)
{
s++;
int x = player.Location.X;
int y = player.Location.Y;
if (s == 1)
if (ModifierKeys.HasFlag(Keys.A))
{
player.Location = new Point(x - 5, y);
}
s = 0;
sprites_updater.Start();
}
So while using timer code, I wrote the same thing above (ModifierKeys.HasFlag(Keys.A)) but it didn´t work. Why?!
BTW, is there any way to show a 3d camera perspective inside a WinForms Panel WITHOUT USING XNA, WPF or any other stuff (only .NET)?!
The best way to get keyboard strokes and processing them later is to catch the Keyboards events in the form using both KeyDown, KeyUp and flags:
bool isAPressed;
...
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
switch(e.KeyCode)
{
case Key.A:
isAPressed = true;
break;
case Key.XXXX:
...
}
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
switch(e.KeyCode)
{
case Key.A:
isAPressed = false;
break;
case Key.XXXX:
...
}
}
Then you can use this information in your timer :
private void sprites_updater_Tick(object sender, EventArgs e)
{
s++;
int x = player.Location.X;
int y = player.Location.Y;
if (s == 1)
if (isAPressed)
{
player.Location = new Point(x - 5, y);
}
s = 0;
sprites_updater.Start();
}
This is particularily interresting to handle player moves this way (arrows).
Related
To make sure that the player knows what difficulty they have chosen to proceed with onto my game, I want the current difficulty to be clearly indicated by the button's forecolour. Here's my code thus far that just changes the forecolour of each button whenever they're pressed:
public Form1()
{
InitializeComponent();
MinimizeBox = false;
MaximizeBox = false;
}
bool diffchosen = false;
public static string difficulty;
public static double multiplier;
public static int lives;
private void Form1_Load(object sender, EventArgs e)
{
}
private void easyButton_Click(object sender, EventArgs e)
{
this.ForeColor = Color.White;
diffchosen = true;
difficulty = "Easy";
multiplier = 0.8;
lives = 4;
}
private void mediumButton_Click(object sender, EventArgs e)
{
this.ForeColor = Color.White;
diffchosen = true;
difficulty = "Medium";
multiplier = 1.0;
lives = 3;
}
private void hardButton_Click(object sender, EventArgs e)
{
this.ForeColor = Color.White;
diffchosen = true;
difficulty = "Hard";
multiplier = 1.5;
lives = 2;
}
private void playButton_Click(object sender, EventArgs e)
{
if (diffchosen == false)
{
MessageBox.Show("Please choose a difficulty before proceeding");
}
else
{
Game_Screen game_Screen = new Game_Screen();
this.Hide();
game_Screen.Show();
}
}
But I had difficulty making sure that when the player decides to choose another option, the other 2 have the black forecolour property. I used this beforehand but it brought about issues like the fact that whenever I pressed a button, the Medium and Hard buttons decided to change their forecolour to white:
if (difficulty == "Hard" || difficulty = "Medium")
{
this.ForeColour = Color.Black;
}
How can I go about creating a loop that would change each button's forecolour depending on the user's choice of button?
Easiest might be just to create a toggle function e.g.
private void ToggleButton(int button)
{
easyButton.ForeColor = Color.Black;
mediumButton.ForeColor = Color.Black;
hardButton.ForeColor = Color.Black;
switch (button)
{
case 1: easyButton.ForeColor = Color.White; break;
case 2: mediumButton.ForeColor = Color.White; break;
case 3: hardButton.ForeColor = Color.White; break;
}
}
and then on every click event you just call this function with the appropriate 'button number'
e.g.
private void easyButton_Click(object sender, EventArgs e)
{
ToggleButton(1);
...
}
private void mediumButton_Click(object sender, EventArgs e)
{
ToggleButton(2);
...
}
private void hardButton_Click(object sender, EventArgs e)
{
ToggleButton(3);
...
}
I am having a problem . I want to use if statement to check if a button is clicked. For Example:
public void button1_Click(object sender, EventArgs e)
{
while (1)
{
...
...
...
if (Button2 == clicked)
{
break;
}
}
}
But it's not working like this, because the ".click" can only be on the left side of "+=" or "-=". Any idea how i can check if Button2 is clicked?
the code is loking like this: and i want to check button2 to stop the "programm".
the check for the Button2 is nearly at the end of the code ;)
public void button1_Click(object sender, EventArgs e)
{
Random rnd = new Random();
int EmFilterPos;
int ExFilterPos;
string String1;
int[] EmLB = new int[126];
int[] ExLB = new int[126];
int LBEmAnzahl = 0;
int LBEmTot = 0;
int LBExAnzahl = 0;
int LBExTot = 0;
UInt32 C_Zyklen;
UInt32 Zyklen;
Roche.DetectionControl2.Device_Filterwheels.ELBPowerState LB_On = Roche.DetectionControl2.Device_Filterwheels.ELBPowerState.LBOn;
Roche.DetectionControl2.Device_Filterwheels.ELBPowerState LB_Off = Roche.DetectionControl2.Device_Filterwheels.ELBPowerState.LBOff;
Roche.DetectionControl2.Device_Filterwheels.fiweGetLBResponse LightBarrier;
string Text = String.Format("Filterrad-Dauertest\r\nGestart am {0:d} um {0:t}\r\n\r\n", DateTime.Now);
System.IO.File.WriteAllText(#"TestLogFile\Filterrad_Dauertest1.txt", Text);
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweInitFilter();
System.Threading.Thread.Sleep(50);
while (Zyklen <= 20)
{
for (int q=1;q<8;q++)
{
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweMove(q,q);
System.Threading.Thread.Sleep(50);
Zyklen++;
}
for (int w=0;w<7;w++)
{
ExFilterPos = rnd.Next(1,8);
EmFilterPos = rnd.Next(1,8);
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweMove(ExFilterPos,EmFilterPos);
System.Threading.Thread.Sleep(50);
Zyklen++;
}
C_Zyklen = Zyklen;
if ((C_Zyklen % 2) < 14)
{
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweInitFilter();
System.Threading.Thread.Sleep(50);
using (System.IO.StreamWriter file = new System.IO.StreamWriter (#"TestLogFile\Filterrad_Dauertest1.txt", true))
{
file.Write("Init bei: ");
String1 = String.Format("{0,7}",Zyklen);
file.Write(String1);
file.Write(file.NewLine);
}
ExFilterPos = 60;
EmFilterPos = 60;
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweRawMove(ExFilterPos,EmFilterPos);
System.Threading.Thread.Sleep(50);
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweSetLB(LB_On);
while (EmFilterPos != -60)
{
LightBarrier = Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweGetLB();
if (LightBarrier.LBEm == Roche.DetectionControl2.Device_Filterwheels.ELBState.LBbright)
{
LBEmAnzahl++;
LBEmTot += EmFilterPos;
}
if (LightBarrier.LBEx == Roche.DetectionControl2.Device_Filterwheels.ELBState.LBbright)
{
LBExAnzahl++;
LBExTot += ExFilterPos;
}
ExFilterPos--;
EmFilterPos--;
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweRawMove(ExFilterPos,EmFilterPos);
}
EmFilterPos = LBEmTot / LBEmAnzahl;
ExFilterPos = LBExTot / LBExAnzahl;
using (System.IO.StreamWriter file = new System.IO.StreamWriter (#"TestLogFile\Filterrad_Dauertest1.txt", true))
{
file.Write("Nullstelle Mittelposition Em-Filter: ");
file.Write(EmFilterPos);
file.Write(file.NewLine);
file.Write("Nullstelle Mittelposition Ex-Filter: ");
file.Write(ExFilterPos);
file.Write(file.NewLine);
file.Write(file.NewLine);
}
Instrument.N1_DetectionControl2_1_Device_Filterwheels.fiweSetLB(LB_Off);
}
if (Button2 == clicked) // or something like this
break;
}
using (System.IO.StreamWriter file = new System.IO.StreamWriter (#"TestLogFile\Filterrad_Dauertest1.txt", true))
{
file.Write("Beendet am {0:d} um {0:t}\r\n", DateTime.Now);
}*/
}
Hm...
bool b1clicked = false, b2clicked = false;
public void button2_Click(object sender, EventArgs e)
{
b2clicked = true;
}
public void button1_Click(object sender, EventArgs e)
{
b1clicked = true;
if (b1clicked && b2clicked)
{
//...
}
}
Beside the weird behavior you want..and since you are not using Threads, you have the following options:
Local functions (.Net > 4.7)
private void B_Click(object sender, EventArgs e)
{
bool clickFlag = false;
void Click(object sender2, EventArgs e2)
{
clickFlag = true;
}
b2.Click += Click;
while (!clickFlag)
{
Thread.Sleep(1);
}
b2.Click -= Click;
//Continue with your stuff
}
Threads
Thread newThread;
private void Button1_Click()
{
newThread = new Thread(YourBreakableProcess);
newThread.Start();
}
private void Button2_Click()
{
newThread.Join();
}
private void YourBreakableProcess()
{
//Your breakable process
}
Async methods.
I hope you find a solution. Cheers.
Edit:
Since what you want is to interrupt the process of whatever you are doing, the only option you have is Local fuctions as shown above, if you are not tied to a specific framework version.
BackgroundWorker and check in every step if the button 2 was pressed with the flag thing mentioned in other answer.
Threads, and make a thread.Join when the button 2 is pressed.
Edit 2:
Updated answer with Threads, I will recommend that if you go with this option it is much better to use a BackgroundWorker instead as you will have the whole control of the process breaking it only in the place where it would be fine to break it.
You can achieve this using a flag variable. Declare and initialize flag value to false.On button2 click change flag value to true as follows,
private bool flag= false;
private void button2_Click(object sender, EventArgs e)
{
flag= true;
}
public void button1_Click(object sender, EventArgs e)
{
//Use flag to check whether button 2 has clicked or not
if (flag)
{
}
else
{
}
}
using System;
using System.Drawing;
using System.IO.Ports;
using System.Windows.Forms;
namespace ek_zıplama
{
public partial class Form1 : Form
{
public enum Directions
{
right,
left,
up,
}
private Directions car_direction;
public SerialPort myPort;
int G = 15;
int force;
bool jump;
public string DATA;
public Form1()
{
InitializeComponent();
myPort = new SerialPort();
myPort.BaudRate = 9600;
myPort.PortName = "COM6";
myPort.Open();
jump = false;
}
private void Form1_Load(object sender, EventArgs e)
{
moves();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (jump)
{
car.Top -= force;
force -= 1;
}
//using block to stay in same position when car is stopped
if (car.Left + car.Width - 1 > block.Left && car.Left + car.Width + 5 < block.Left + block.Width + car.Width
&& car.Top + car.Height >= block.Top && car.Top < block.Top)
{
car.Top = ekran.Height - block.Height - car.Height;
force = 0;
jump = false;
}
}
private void moves()
{
if (label2.Text == "10111" && car_direction != Directions.right)
{
car.Location = new Point(car.Location.X + 130, car.Location.Y);
car_direction = Directions.right;
}
if (label2.Text == "01111" && car_direction != Directions.left)
{
car.Location = new Point(car.Location.X - 130, car.Location.Y);
car_direction = Directions.left;
}
if (!jump && label2.Text == "11011")
{
jump = true;
force = G;
}
}
private void timer3_Tick(object sender, EventArgs e)
{
DATA = myPort.ReadExisting();
label2.Text = DATA;
}
}
}
What I botch about that in move function.
I tried to create a function like
*if DATA is 01111 then my car turns left
*if DATA is 10111 then my car turns right
*if DATA is 11011 then my car jumps
Before I changed,car was controlled with keyboards.Everything was same but "move"function.And it was working.What were instead od "move" function is:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Right&& car_direction != Directions.right)
{
car.Location = new Point(car.Location.X + 130, car.Location.Y);
car_direction = Directions.right;
}
if (e.KeyCode == Keys.Left && car_direction != Directions.left)
{
car.Location = new Point(car.Location.X - 130, car.Location.Y);
car_direction = Directions.left;
}
if (!jump && e.KeyCode == Keys.Up)
{
jump = true;
force = G;
}
}
Hope you get me :)
I'm quite sure it's not going to work if you only call it once in your Form_Load event. Since you maybe want your car to move each time the data in the label has changed, you should just make a reference to the function you created. That means, that you should just put moves(); in private void timer3_Tick(object sender, EventArgs e):
private void timer3_Tick(object sender, EventArgs e)
{
DATA = myPort.ReadExisting();
label2.Text = DATA;
moves();
}
In this way, each time the timer ticks, your car is going to move according to the new data in the label.
When I was doing something with Arduino I used something like this:
private void timer_Tick(object sender, EventArgs e)
{
if (serialPort != null && serialPort.IsOpen && serialPort.BytesToRead > 0)
{
data_as_string += serialPort.ReadLine();
}
}
I'm not sure how DATA is sent, but you can send single lines from Arduino using Serial.write("your line here");. Receiving and parsing data from here is very simple, as you could just read lines 01111, 10111, etc. and use any logic to manipulate the car. I hope this helps.
My Timer doesn't work as expected, why is the pictureBox moving faster after each call of the Timer interval.
I want the pictureBox to move frequent over the Form after someone pressed the D button. The functions add and remove Event works fine so that can't be the case:
Timer loop;
Int32 posX, posY;
public Form1()
{
InitializeComponent();
loop = new Timer();
}
private void Form1_Load(object sender, EventArgs e)
{
sprit.Enabled = false;
loop.Interval = 10;
posX = this.sprit.Location.X;
posY = this.sprit.Location.Y;
}
private void nextStep(object sender, EventArgs e)
{
posX++;
this.sprit.Location = new Point(posX, posY);
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode) {
case Keys.D:
addEvent(nextStep);
loop.Start();
break;
}
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.D:
removeEvent(nextStep);
loop.Stop();
break;
}
}
Form1_KeyDown will be called repeatedly as long as you hold the key, so you keep calling addEvent(nextStep).
Try calling addEvent(nextStep) only once on Form1_KeyDown
I read articles over the internet but I think I'm missing something here. I tried following the answer to this SO question, but nothing has happened.
I wanted to trigger the usePort_Click method whenever I press the Enter/Return key. Also, I don't know how to get around the EventArgs parameter of usePort_Click whenever I do try calling it from the ports_Keydown method.
Note: ports is a ListBox control.
private void usePort_Click(object sender, EventArgs e)
{
try
{
port = new SerialPort((string)ports.SelectedItem, 9600);
portUsedLabel.Text = (string)ports.SelectedItem;
String buffer = "";
String tellArduino = "food"; // test value
port.Open();
port.WriteLine(tellArduino);
for (int x = 0; x < tellArduino.Length; x++)
{
buffer += port.ReadLine();
}
ports.Items.Add(buffer);
port.Close();
}
catch { //stuff }
}
private void ports_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//code here
}
}
A good solution would be to move the code you want to execute into a separate method (I called it someStuff, replace the name with something better) and call that method from both event handlers:
private void usePort_Click(object sender, EventArgs e)
{
someStuff();
}
private void ports_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
someStuff();
}
}
private void someStuff()
{
try
{
port = new SerialPort((string)ports.SelectedItem, 9600);
portUsedLabel.Text = (string)ports.SelectedItem;
String buffer = "";
String tellArduino = "food"; // test value
port.Open();
port.WriteLine(tellArduino);
for (int x = 0; x < tellArduino.Length; x++)
{
buffer += port.ReadLine();
}
ports.Items.Add(buffer);
port.Close();
}
catch { //stuff }
}