How to activate keydown event by clicking specific button? - c#

I am developing 2D game(pacman)to improve myself in VB 2013 via c#,
and I want my key-down events activated by clicking specific button.(That is restart button shown when the game is over).Thanks for your help.
//these are my keydown codes
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
int r = pictureBox5.Location.X;
int t = pictureBox5.Location.Y;
if (pictureBox5.Top >= 33)
{
if (e.KeyCode == Keys.Up)
{
t = t - 15;
}
}
if (pictureBox5.Bottom <= 490)
{
if (e.KeyCode == Keys.Down)
{
t = t + 15;
}
}
if (pictureBox5.Right <= 520)
{
if (e.KeyCode == Keys.Right)
{
r = r + 15;
}
}
if (pictureBox5.Left >= 30)
{
if (e.KeyCode == Keys.Left)
{
r = r - 15;
}
}
if (e.KeyCode == Keys.Up && e.KeyCode == Keys.Right)
{
t = t - 15;
r = r + 15;
}
pictureBox5.Location = new Point(r, t);
}
//and that's the button I wanted to interlace with keydown event
private void button1_Click(object sender, EventArgs e)
{
}

A bit of refactoring could help here. Suppose that if you hit the button the keycode to use is Keys.Down. In this scenario you can move all the code inside the Form_KeyDown to a different method called HandleKey
private void HandleKey(Keys code)
{
int r = pictureBox5.Location.X;
int t = pictureBox5.Location.Y;
if (pictureBox5.Top >= 33)
{
if (code == Keys.Up)
t = t - 15;
}
if (pictureBox5.Bottom <= 490)
{
if (code == Keys.Down)
t = t + 15;
}
if (pictureBox5.Right <= 520)
{
if (code == Keys.Right)
r = r + 15;
}
if (pictureBox5.Left >= 30)
{
if (code == Keys.Left)
r = r - 15;
}
// This is simply impossible
if (code == Keys.Up && code == Keys.Right)
{
t = t - 15;
r = r + 15;
}
pictureBox5.Location = new Point(r, t);
}
Now you can call this method from the Form_KeyDown event
private void Form_KeyDown(object sender, KeyEventArgs e)
{
// Pass whatever the user presses...
HandleKey(e.KeyCode);
}
and from the button click
private void button1_Click(object sender, EventArgs e)
{
// Pass your defined key for the button click
HandleKey(Keys.Down);
}

Related

Selected PictureBox don't move on KeyDown

I have PictureBoxes and I just choose from them via the onClick function and then if it doesn't have a "King" tag, I can move with it ... But I can only do that if I have the MessageBox there (It was only there for the test , if it takes a tag) and if I remove it now, I can't move with it.
private void PictureBoxIsClicked(object sender, MouseEventArgs e)
{
selectedPlayer = (PictureBox)sender;
if (e.Button == MouseButtons.Left)
{
//Choosing King
if (isClicked == true && readyToPlay == false)
{
selectedPlayer.Image = Properties.Resources.CharRed;
selectedPlayer.Tag = "King";
isKing = true;
}
isClicked = false;
//Select pictureBox to move
if (readyToPlay == true)
{
label2.Text = String.Format("{0}", selectedPlayer.Tag.ToString());
label1.Show();
MessageBox.Show(selectedPlayer.Tag.ToString());
}
}
}
private void KeyIsDown(object sender, KeyEventArgs e)
{
if(selectedPlayer.Tag.ToString() != "King")
{
//Move forward
if (e.KeyCode == Keys.Up)
{
forward = true;
}
//Move backward
if (e.KeyCode == Keys.Down)
{
backward = true;
}
//Move Left
if (e.KeyCode == Keys.Left)
{
left = true;
}
//Move right
if (e.KeyCode == Keys.Right)
{
right = true;
}
}
}
private void GameTimerEvent(object sender, EventArgs e)
{
//Movement - Player
if(forward == true)
{
selectedPlayer.Top -= 120;
forward = false;
}
if (backward == true)
{
selectedPlayer.Top += 120;
backward = false;
}
if (left == true)
{
selectedPlayer.Left -= 120;
left = false;
}
if (right == true)
{
selectedPlayer.Left += 120;
right = false;
}
}
Why does it fail?

I'm getting error Ambiguity between '¨Form1.score' and ¨Form1.score'

i have int score = 0; under public partial class Form1 : Form and Im getting error in txtscore.Text = "Score: " + score; and score = 0; in private void RestartHry() does someone know why is that? Or know how to fix that bsc i have no idea. ......................................................................................................................................................................................
namespace Projekt_Havlík
{
public partial class Form1 : Form
{
bool vpravo, vlevo;
int rychlost = 8;
int score = 0;
int minul = 0;
Random rndX = new Random();
Random rndY = new Random();
PictureBox minulcoin = new PictureBox();
public Form1()
{
InitializeComponent();
RestartHry();
}
private void MainGameTimerEvent(object sender, EventArgs e)
{
//naprogramovaní textboxů
txtscore.Text = "Score: " + score;
txtminul.Text = "Minul: " + minul;
//změnění postavy při jízdě do leva/prava
if (vlevo == true && player.Left > 0)
{
player.Left -= 12;
player.Image = Properties.Resources.main_left;
}
if (vpravo == true && player.Left + player.Width <this.ClientSize.Width)
{
player.Left += 12;
player.Image = Properties.Resources.main_right;
}
}
private void KeyIsUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
vlevo = false;
}
if (e.KeyCode == Keys.Right)
{
vpravo = false;
}
}
private void KeyIsDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
vlevo = true;
}
if (e.KeyCode == Keys.Right)
{
vpravo = true;
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void RestartHry()
{
foreach(Control x in this.Controls)
{
if (x is PictureBox &&(string)x.Tag == "coins")
{
x.Top = rndY.Next(80, 300) * -1;
x.Left = rndX.Next(5, this.ClientSize.Width - x.Width);
}
}
player.Left = this.ClientSize.Width / 2;
player.Image = Properties.Resources.main_right;
score = 0;
minul = 0;
rychlost = 8;
vpravo = false;
vlevo = false;
CasovacHry.Start();
}
}
}
Try changing the name of your "score" variable, try calling it like, "myScore", typically if something is ambiguous it is because there are two fields or properties with the same name in assembly references that are not directly specified in the code.

How do I move an object using a timer and the key press event (Like snake)

I want to move a button automatically using a timer and want it to change direction when another key is pressed, kinda like what happens in snake
I have used a string to set what the direction should be, but this doesn't work.
string x = "right";
public Form1()
{
InitializeComponent();
timer1.Interval = 1000;
timer1.Start();
}
private void Player_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.W)
{
string x = "up";
}
else if (e.KeyCode == Keys.S)
{
string x = "down";
}
else if (e.KeyCode == Keys.D)
{
string x = "right";
}
else if (e.KeyCode == Keys.A)
{
string x = "left";
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void Timer1_Tick(object sender, EventArgs e)
{
while (x == "up")
{
Player.Top -= 10;
}
while (x == "down")
{
Player.Top += 10;
}
while (x == "right")
{
Player.Left += 10;
}
while (x == "left")
{
Player.Left -= 10;
}
}
}
The button just disappears, but I want it to move by ten until it gets a key press like "D" then it changes direction
1: You are creating variable 'x' every time means locally in player_keyDown event so create it globally.
2: you are using while loop it, not needed as you are already using timer_tick.
3: Instead of Top, Left use Location property of button it gives you X, Y co-ordinate
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
timer1.Interval = 1000;
timer1.Start();
}
string x = "right";
private void Player_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.W)
{
x = "up";
}
else if (e.KeyCode == Keys.S)
{
x = "down";
}
else if (e.KeyCode == Keys.D)
{
x = "right";
}
else if (e.KeyCode == Keys.A)
{
x = "left";
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (x == "up")
{
Player.Location = new System.Drawing.Point(Player.Location.X, Player.Location.Y - 10);
}
if (x == "down")
{
Player.Location = new System.Drawing.Point(Player.Location.X, Player.Location.Y + 10);
}
if (x == "right")
{
Player.Location = new System.Drawing.Point(Player.Location.X + 10, Player.Location.Y);
}
if (x == "left")
{
Player.Location = new System.Drawing.Point(Player.Location.X - 10, Player.Location.Y);
}
}
}

How to prevent two events about the same thing happening

Basically,I am a beginner in C# and I just started working on a simple platformer game following a basic Visual Studio 2015 tutorial.This is the code:
public partial class Form1 : Form
{
bool goleft = false;
bool goright = false;
bool jumping = false;
int JumpSpeed = 10;
int force = 8;
int score = 0;
public Form1()
{
InitializeComponent();
}
private void keyisdown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
goleft = true;
}
if (e.KeyCode == Keys.Right)
{
goright = true;
}
if (e.KeyCode == Keys.Space && !jumping)
{
jumping = true;
}
}
private void keyisup(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
goleft = false;
}
if (e.KeyCode == Keys.Right)
{
goright = false;
}
if (jumping)
{
jumping = false;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
player.Top += JumpSpeed;
if (jumping && force < 0)
{
jumping = false;
}
if (goleft)
{
player.Left -= 5;
}
if (goright)
{
player.Left += 5;
}
if (jumping)
{
JumpSpeed = -12;
force -= 1;
}
else
{
JumpSpeed = 12;
}
foreach (Control x in this.Controls)
{
if (x is PictureBox && x.Tag == "p")
{
if (player.Bounds.IntersectsWith(x.Bounds) && !jumping)
{
force = 8;
player.Top = x.Top - player.Height;
}
}
if (player.Bounds.IntersectsWith(Door.Bounds))
{
timer1.Stop();
MessageBox.Show("You Won!");
this.Close();
}
}
}
}
The gravity force and everything works great EXCEPT for one big problem with the player that I definitely can't solve without some help.
The problem is: the player is completely glitched and it keeps going up and down. I realised that this is because of two lines in private void timer1_Tick(object sender, EventArgs e):
player.Top += JumpSpeed;
and
player.Top = x.Top - player.Height;
Both of these try to change player.Top and interfere with each other. The trouble is that I can't just cut one of the two without destroying the gravity force code. What I think might work is applying player.Top += JumpSpeed; ONLY if(player.Bounds.IntersectsWith(x.Bounds) && !jumping) = false but I don't know how to write the code this way at all (previous tries always ended up with errors).
Thanks in advance for any help and please forgive any grammar errors that I made because I am not a native english speaker.
I don't know how your Form looks like, but with what you provided I would change the code like that:
public partial class Form1 : Form
{
bool goleft = false;
bool goright = false;
int JumpSpeed = 0; //current vertical speed
int force = 8; //initial jump speed
int score = 0;
public Form1()
{
InitializeComponent();
}
private void keyisdown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
goleft = true;
}
if (e.KeyCode == Keys.Right)
{
goright = true;
}
if (e.KeyCode == Keys.Space && JumpSpeed==0) //JumpSpeed==0 to prevent "double jump"
{
JumpSpeed = force; //start jumping with full power
}
}
private void keyisup(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Left)
{
goleft = false;
}
if (e.KeyCode == Keys.Right)
{
goright = false;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (goleft)
{
player.Left -= 5;
}
if (goright)
{
player.Left += 5;
}
JumpSpeed -= 1; //decrement the vertical speed = gravity -> choose higher value to bring him back on the ground quicker
player.Top -= JumpSpeed;
if (player.Bounds.IntersectsWith(Door.Bounds))
{
timer1.Stop();
MessageBox.Show("You Won!");
this.Close();
}
foreach (PictureBox x in this.Controls.OfType<PictureBox>())
{
if (x.Tag == "p")
{
if (player.Bounds.IntersectsWith(x.Bounds)) //if the player should be able to jump/walk on something the code is
{
player.Top = x.Top - player.Height;
JumpSpeed = 0; //the player stops falling
}
}
}
}
}
To make sure to player does not fall out of the window place PictureBoxes with tag == p on the floor!
PS:
Feel free to leave a comment!

Reset button in a c# game [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
So, I'm making a game which is kind of similar to pac-man and I want to add a reset-button (resetting the game, NOT restarting the application). I've tried a lot of things but I still can't get it working. Any solutions?
Thanks in advance,
Henk
public partial class Game : Form
{
public int GameHeigth = 45;
public int GameWidth = 45;
private Hokje[,] matrix = new Hokje[15, 15]; //creates the "game board"
private List<VObject> XObjects = new List<VObject>(); //list of the objects that
the game has(unmoveable boxes and moveable by the player boxes)
private Hero Maxim; // the hero of the game
private Random rnd = new Random();
public Reaper Linde { get; private set; } // the enemy
public Game()
{
InitializeComponent();
GenerateField();
NeighbourBase();
StartGame();
}
private void GenerateField()
{
int newpointY = 0;
int newpointX = 0;
for (int y = 0; y < 15; y++)
{
for (int x = 0; x < 15; x++)
{
int choise = rnd.Next(0, 99);
Hokje green = new Hokje();
matrix[y, x] = green;
green.Location = new Point(newpointX, newpointY);
Controls.Add(green);
if (choise < 20)
{
Doos box = new Doos(green);
}
if (choise >= 20 && choise <= 25)
{
Muur wall = new Muur(green);
}
newpointX = newpointX + GameWidth;
}
newpointX = 0;
newpointY = newpointY + GameHeigth;
}
}
private void NeighbourBase()
{
for (int y = 0; y < 15; y++)
{
for (int x = 0; x < 15; x++)
{
try
{
matrix[y, x].Buren[Direction.Up] = matrix[y - 1, x];
}
catch (IndexOutOfRangeException)
{
matrix[y, x].Buren[Direction.Up] = null;
}
try
{
matrix[y, x].Buren[Direction.Down] = matrix[y + 1, x];
}
catch (IndexOutOfRangeException)
{
matrix[y, x].Buren[Direction.Down] = null;
}
try
{
matrix[y, x].Buren[Direction.Left] = matrix[y, x - 1];
}
catch (IndexOutOfRangeException)
{
matrix[y, x].Buren[Direction.Left] = null;
}
try
{
matrix[y, x].Buren[Direction.Right] = matrix[y, x + 1];
}
catch (IndexOutOfRangeException)
{
matrix[y, x].Buren[Direction.Right] = null;
}
}
}
}
private void StartGame()
{
Maxim = new Hero(matrix[0, 0]);
Linde = new Reaper(matrix[14, 14]);
private void Game_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Up)
{
Maxim.direction = Direction.Up;
}
if (e.KeyCode == Keys.Down)
{
Maxim.direction = Direction.Down;
}
if (e.KeyCode == Keys.Left)
{
Maxim.direction = Direction.Left;
}
if (e.KeyCode == Keys.Right)
{
Maxim.direction = Direction.Right;
}
Maxim.Move();
}
private void Game_Load(object sender, EventArgs e)
{
foreach (Control control in Controls)
{
control.PreviewKeyDown += new PreviewKeyDownEventHandler(control_PreviewKeyDown);
}
}
private void control_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) //overrides browsing buttons focus while pressing on arrows keys
{
if (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down || e.KeyCode == Keys.Left || e.KeyCode == Keys.Right)
{
e.IsInputKey = true;
}
}
.......//code missing here
private void ResetButton_Click(object sender, EventArgs e)
{
//what do I set here?
}
Just create a new instance of Game. This will give you a whole new set of variables and therefore a new game state.
You need to keep a reference to the game to keep it from being GC'd, so you also need a static variable.
static private Game _currentGame;
private void ResetButton_Click(object sender, EventArgs e)
{
this.Hide();
_currentGame = new Game();
_currentGame.Show();
this.Close();
}

Categories

Resources