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.
Related
I want to make an AI using PictureBox that can roam randomly without messing its movements like for example:
PictureBox must execute the movement to go Right, if the Timer runs out it the next movement is going Down, like just how random it would roam.
I'd thought I might figured it out to Hard code it. However might took long, also once the Timer Stops, it won't Restart again. idk why.
Here's a Picture of my Game so you would have some ideas about it.
Here's the code also
private void Game_Load(object sender, EventArgs e)
{
E_Right.Start();
if(Upcount == 0)
{
E_Right.Start();
}
}
private void E_Right_Tick(object sender, EventArgs e)
{
if(Rightcount > 0)
{
EnemyTank.Left += 5;
EnemyTank.BackgroundImage = Properties.Resources.EnemyTank_RIGHT_v_2;
Rightcount = Rightcount - 1;
}
if (Rightcount == 0)
{
E_Right.Stop();
E_Down.Start();
}
}
private void E_Up_Tick(object sender, EventArgs e)
{
if (Upcount > 0)
{
EnemyTank.Top -= 5;
EnemyTank.BackgroundImage = Properties.Resources.EnemyTank_TOP_v_1;
Upcount = Upcount - 1;
}
if (Upcount == 0)
{
E_Up.Stop();
E_Right.Start();
}
}
private void E_Down_Tick(object sender, EventArgs e)
{
if (Downcount > 0)
{
EnemyTank.Top += 5;
EnemyTank.BackgroundImage = Properties.Resources.EnemyTank_DOWN_v_1;
Downcount = Downcount - 1;
}
if (Downcount == 0)
{
E_Down.Stop();
E_Left.Start();
}
}
private void E_Left_Tick(object sender, EventArgs e)
{
if (Leftcount > 0)
{
EnemyTank.Left -= 5;
EnemyTank.BackgroundImage = Properties.Resources.EnemyTank_LEFT_v_1;
Leftcount = Leftcount - 1;
}
if (Leftcount == 0)
{
E_Left.Stop();
E_Up.Start();
}
}
Well just assume that the PictureBox is in Location(0,0). If you see a PictureBox an image of a Tank nevermind that. That goes for the MainTank of the user will be using.
You could do it with just one timer:
int moveTo = 0; // Move while this is not 0
int speed = 3;
Random rand = new Random();
// Keep track of whether the tank is moving up/down or left/right
enum MoveOrientation { Vertical, Horizontal };
MoveOrientation orientation = MoveOrientation.Vertical;
void ChooseNextPosition()
{
// Negative numbers move left or down
// Positive move right or up
do {
moveTo = rand.Next(-5, 5);
} while (moveTo == 0); // Avoid 0
}
private void Game_Load(object sender, EventArgs e) {
ChooseNextPosition();
timer1.Start();
}
private void timer1Tick(object sender, EventArgs e) {
if (orientation == MoveOrientation.Horizontal)
{
EnemyTank.Left += moveTo * speed;
}
else
{
EnemyTank.Top += moveTo * speed;
}
moveTo -= moveTo < 0 ? -1 : 1;
if (moveTo == 0)
{
// Switch orientation.
// If currently moving horizontal, next move is vertical
// And vice versa
orientation = orientation == MoveOrientation.Horizontal ? MoveOrientation.Vertical : MoveOrientation.Horizontal;
// Get new target
ChooseNextPosition();
}
}
I'm trying to re-create flappybird in Visual studio 2015 c# for a little school project. But for some reason i get this error that i really can't fix. I'm following an tutorial on how to create flappybird, but the one making the tutorial is writing in VB.net Heres the YT Link and under that my code I'm trying to make.
https://www.youtube.com/watch?v=tnjdMbdEzMo
public partial class Form10 : Form
{
int gravity = 1;
int yspeed = 0;
PictureBox[,] Pipe;
public Form10()
{
InitializeComponent();
}
private void gameTimer_Tick(object sender, EventArgs e)
{
int i;
this.yspeed += this.gravity;
bird.Top += this.yspeed;
}
private void inGameKeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Space)
{
this.yspeed = -15;
}
}
private void pausePlayToolStripMenuItem_Click(object sender, EventArgs e)
{
if (gameTimer.Enabled == true)
{
gameTimer.Enabled = false;
}
else
{
if (gameTimer.Enabled == false)
{
gameTimer.Enabled = true;
}
}
}
private void restartToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void startGame_Click(object sender, EventArgs e)
{
if (gameTimer.Enabled == false)
{
gameTimer.Enabled = true;
startGame.Enabled = false;
}
}
private void CreatePipes(int number)
{
int i = 0;
for (i = 0; (i <= number); i++)
{
var temp = new PictureBox();
this.Controls.Add(temp);
temp.Width = 50;
temp.Height = 370;
temp.BorderStyle = BorderStyle.FixedSingle;
temp.BackColor = Color.Red;
temp.Top = 50;
temp.Left = (2 * 200) + 300;
Pipe(i) = temp;
Pipe(i).Visable = true;
}
}
private void Form10_Load(object sender, EventArgs e)
{
gameTimer.Enabled = true;
CreatePipes(1);
}
}
}
The problem you are seeing is in the lines
Pipe(i) = temp;
Pipe(i).Visable = true;
If you are trying to access Pipe as an array, the syntax is Pipe[i], although pipe is a 2d array so it should be Pipe[i,j] Where j is something else.
Also you have misspelled Visible.
I am currently working on a platformer in C#,VS 2015
The problem i have encountered is:when i press the left/right arrow,the background moves behind the player in the opposite direction,and this happens using a timer(which cannot be set to a value lower than 1 milisecond).
Because the timer is limited to 1 milisecond,the background moves laggy,and i would like to solve this :D
Here is the code
public Form1()
{
InitializeComponent();
}
Bitmap back;
Bitmap bobright;
Bitmap bobleft;
Bitmap bobimage;
Bitmap exit;
Point boblocation = Point.Empty;
Point exitlocation = Point.Empty;
float offSet = 0, vit;
int acc_secunde, acc_secunde_max = 30;
bool left = false, right = false;
private void button1_Click(object sender, EventArgs e)
{
Application.Exit();
}
public void Game()
{
int imageNumber = panel1.Width / back.Width + 3;
using (Bitmap frame = new Bitmap(panel1.Width, panel1.Height))
{
using (Graphics graph = Graphics.FromImage(frame))
{
for (int i = 0; i < imageNumber; i++)
{
graph.DrawImage(back, offSet/2 % back.Width + i * back.Width - back.Width, 0);
}
graph.DrawImage(bobimage, boblocation);
graph.DrawImage(exit,exitlocation);
}
using (Graphics graph = panel1.CreateGraphics())
{
graph.DrawImage(frame, Point.Empty);
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Maximized;
back = Properties.Resources.back;
bobleft = Properties.Resources.bobleft;
bobright = Properties.Resources.bobright;
bobimage = bobright;
exit = Properties.Resources.Exit;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
boblocation.X = panel1.Width / 2 - bobimage.Width / 2;
boblocation.Y = 210;
exitlocation.X = panel1.Width - exit.Width - 10;
exitlocation.Y = 5;
if (left)
{
offSet = offSet + acc_secunde;
bobimage = bobleft;
}
if(right)
{
bobimage = bobright;
offSet = offSet - acc_secunde;
}
Game();
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Left)
{
acceleratie.Start();
left = true;
}
if(e.KeyCode == Keys.Right)
{
acceleratie.Start();
right = true;
}
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if(e.KeyCode == Keys.Left)
{
acceleratie.Stop();
deacceleratie.Start();
}
if(e.KeyCode == Keys.Right)
{
acceleratie.Stop();
deacceleratie.Start();
}
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
}
private void deacceleratie_Tick(object sender, EventArgs e)
{
if(acc_secunde > 0)
acc_secunde = acc_secunde - acc_secunde_max / 3;
if (acc_secunde <= 0)
{
deacceleratie.Stop();
if (right == true)
right = false;
if (left == true)
left = false;
acc_secunde = 0;
}
}
private void acceleratie_Tick(object sender, EventArgs e)
{
if(acc_secunde< acc_secunde_max)
acc_secunde+=2;
}
private void Form1_MouseClick(object sender, MouseEventArgs e)
{
}
private void panel1_MouseUp(object sender, MouseEventArgs e)
{
Point mousePt = new Point(e.X, e.Y);
if (mousePt.X > panel1.Width - exit.Width - 10 && mousePt.X < panel1.Width - 10 && mousePt.Y > panel1.Top + 10 && mousePt.Y < panel1.Top + 10 + exit.Height)
Application.Exit();
}
}
}
i'm new to C# (and programming at all) and i'm trying to write an 'XO' game along with ASP.NET
i'm getting a problem after the first player clicks a button.
turns doesn't switch and any click after the 1st does nothing. what is wrong with my code ?
public partial class GamePage : System.Web.UI.Page
{
Player player1 = new Player();
Player player2 = new Player();
int turn;
protected void Page_Load(object sender, EventArgs e)
{
this.turn = 0;
if (!IsPostBack)
{
Label1.Visible = true;
}
if (turn == 0)
{
Label1.Text = (Session["player1"] as Player).getname();
}
else
{
Label1.Text = (Session["player2"] as Player).getname();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Session["p1"] = player1;
Session["p2"] = player2;
player1.setsymbol("X");
player2.setsymbol("O");
if (Button1.Text == "")
{
if (turn == 0)
{
Button1.Text = player1.getsymbol();
Label1.Text = (Session["player2"] as Player).getname();
turn = 1;
}
else
{
Button1.Text = player2.getsymbol();
Label1.Text = (Session["player1"] as Player).getname();
turn = 0;
}
}
}
protected void Button2_Click(object sender, EventArgs e)
{
if (Button2.Text == "")
{
if (turn == 0)
{
Button2.Text = player1.getsymbol();
Label1.Text = (Session["player2"] as Player).getname();
turn = 1;
}
else
{
Button2.Text = player2.getsymbol();
Label1.Text = (Session["player1"] as Player).getname();
turn = 0;
}
}
}
protected void Button3_Click(object sender, EventArgs e)
{
if (Button3.Text == "")
{
if (turn == 0)
{
Button3.Text = player1.getsymbol();
Label1.Text = (Session["player2"] as Player).getname();
turn = 1;
}
else
{
Button3.Text = player2.getsymbol();
Label1.Text = (Session["player1"] as Player).getname();
turn = 0;
}
}
}
// this is an example - i have the same lines from button1 to 9
Everytime page renders, you set turn to 0 in Page_Load. Because Page_Load is executed upon every page load, you won't get any other value and this is probably the major issue here.
To properly support the lifetime of such variables that should keep value upon consecutive requests, wrap them in simple property:
public int turn
{
get
{
if ( Session["turn"] != null )
return (int)Session["turn"];
return 0; // default value if not set before
}
set
{
Session["turn"] = value;
}
}
This way everytime you refer to turn in your code, setting it to 0 or 1 or comparing the value to 0 or 1, you will refer to the same value, possibly stored during previous request(s).
this.turn=0; should be executed only when IsPostBack is false. Move this line inside if in your Page_Load.
So i working on a breakout game and so far everything has been going well, but when i make the the ball picturebox go off screen i seem to getting an unlimited amount of message boxes.
here is the code snippet
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
List<Brick> bricks = new List<Brick>();
Ball _ball;
Paddle _paddle;
DateTime startTime = DateTime.Now;
DateTime startTime2 = DateTime.Now;
float ballVelocityX = 0;
float ballVelocityY = -1;
float ballSpeed = 20;
public Form1()
{
InitializeComponent();
timer1.Enabled = true;
timer2.Enabled = true;
startTime = DateTime.Now;
System.Media.SoundPlayer sndPlayer;
sndPlayer = new System.Media.SoundPlayer(Properties.Resources._01_Calm_1);
foreach (PictureBox brick in panel1.Controls)
{
if (brick.Name != "ball" && brick.Name != "paddle")
bricks.Add(new Brick(brick));
else if (brick.Name == "ball")
_ball = new Ball(brick);
else if (brick.Name == "paddle")
_paddle = new Paddle(brick);
//sndPlayer.Play();
}
}
private void gameTimer_Tick(object sender, EventArgs e)
{
checkBrickCollision();
checkPaddleCollision();
checkBallScreenBounds();
ball.SetBounds(ball.Location.X + (int)(ballVelocityX * ballSpeed),
ball.Location.Y + (int)(ballVelocityY * ballSpeed),
ball.Size.Width, ball.Size.Height);
paddle.SetBounds(Cursor.Position.X - panel1.Location.X, paddle.Location.Y,
paddle.Size.Width, paddle.Size.Height);
}
private void checkBallScreenBounds()
{
if (_ball.BallRectangle.Location.X + 25 > panel1.Size.Width)
ballVelocityX *= -1;
else if (_ball.BallRectangle.Location.X < 0)
ballVelocityX *= -1;
else if (_ball.BallRectangle.Location.Y < 0)
ballVelocityY *= -1;
else if (_ball.BallRectangle.Location.Y > panel1.Size.Height)
ballOffScreen();
}
private void ballOffScreen()
{
new_start();
Startnew startnew = new Startnew();
startnew.Show();
this.Close();
}
private void new_start()
{
TimeSpan elapsedTime = DateTime.Now - startTime2;
DialogResult result;
result = MessageBox.Show("Your total time is " + ":" + elapsedTime.Minutes + elapsedTime.Seconds
+ " would you like to play aigan?", "Application1", MessageBoxButtons.YesNo);
if (result == DialogResult.No)
{
Form1 form1 = new Form1();
form1.Show();
}
else if (result == DialogResult.Yes)
{
this.Close();
}
//MessageBox.Show("Total time is " + elapsedTime.Minutes + ":" + elapsedTime.Seconds);
}
private void checkPaddleCollision()
{
int tmpBallVelocityX = _paddle.CheckPaddleMovement();
if (_ball.BallRectangle.IntersectsWith(_paddle.PaddleRectangle))
{
ballVelocityX = tmpBallVelocityX;
ballVelocityY *= -1;
}
}
private void checkBrickCollision()
{
Rectangle ballRectangle = _ball.BallRectangle;
foreach (Brick brick in bricks)
if (brick.IntersectWith(ballRectangle))
{
bricks.Remove(brick);
ballVelocityX *= -1;
ballVelocityY *= -1;
break;
}
}
private void panel1_MouseEnter(object sender, EventArgs e)
{
Cursor.Hide();
}
private void panel1_MouseLeave(object sender, EventArgs e)
{
Cursor.Show();
}
public void Form_closse(object sender, FormClosedEventArgs e)
{
//ProgramInfo.ProgramState = State.Splash_Screen;
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
private void timer1_tick(object sender, EventArgs e)
{
LabelTime.Text = "It is " + DateTime.Now;
}
private void timer2_tick(object sender, EventArgs e)
{
TimeSpan elapsedTime = DateTime.Now - startTime;
labelElapsedTime.Text = "Time Elapsed " + elapsedTime.Minutes + ":" + elapsedTime.Seconds;
}
}
}
` #**EDIT**#`
`**because things were getting a bit confusing i posted all my code.**`
ive done this with a button and it works fine and all, but i need to pop up only once. is there any way to only have it called once?
if new_start() is part of Form1,
Following line looks like culprit, but more code is required for closer look.
if (result == DialogResult.No)
{
Form1 form1 = new Form1();
form1.Show(); //This line is creating endless messagebox on selecting NO
}
UPDATE Based on information in comments,
you can control the new_start function with flag
private bool checkNewGame = false;
private void new_start()
{
if(checkNewGame) return;
checkNewGame = true;
TimeSpan elapsedTime = DateTime.Now - startTime2;
DialogResult result;
result = MessageBox.Show("Your total time is " + ":" + elapsedTime.Minutes + elapsedTime.Seconds
+ " would you like to play aigan?", "Application1", MessageBoxButtons.YesNo);
if (result == DialogResult.No)
{
Form1 form1 = new Form1();
form1.Show();
}
else if (result == DialogResult.Yes)
{
checkNewGame = true;
this.Close();
}
UPDATE 2
Instead of
if (result == DialogResult.No)
{
Form1 form1 = new Form1();
form1.Show(); //This line is creating endless messagebox on selecting NO
}
do something like
if (result == DialogResult.No)
{
this.Clear(); // Create new function Clear, and clear all the Form state.
}
void clear()
{
... //RESET all form state
}
Most likely the code that supposed to restart the game does not clear "ball-Off-Screen" condition and your game immediately goes to end of game.
Note: Debugging should immediately show the reason of the behavior...