im trying to clear the picturebox that are created from a list in my game once it has ended, i have cleared the list but the picturebox still display i have tried using the below code in a timer that is enable upon the game ending
foreach (Invader ship in invaders)
{
ship.isDisposed = true;
ship.ship.Dispose();
}
this doesnt do anyhting tho so does anyone have any ideas how i could do this?
public partial class Form1 : Form
{
private List<Invader> invaders = new List<Invader>();
private List<Laser> lasers = new List<Laser>();
int invaderNumber = 0;
int score = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
// moves the spacefighter up when clicked
if (e.KeyCode.Equals(Keys.W))
{
if (SpaceFighter.Top > 0)
{
SpaceFighter.Top = SpaceFighter.Top - 30;
}
}
// moves the spacefighter left when clicked
if (e.KeyCode.Equals(Keys.A))
{
if (SpaceFighter.Left > 0)
{
SpaceFighter.Left = SpaceFighter.Left - 10;
}
}
// moves the spacefighter right when clicked
if (e.KeyCode.Equals(Keys.D))
{
if (SpaceFighter.Right < this.Width)
{
SpaceFighter.Left = SpaceFighter.Left + 10;
}
}
// moves the spacefighter down when clicked
if (e.KeyCode.Equals(Keys.S))
{
if (SpaceFighter.Bottom < this.Height - 10)
{
SpaceFighter.Top = SpaceFighter.Top + 10;
}
}
// fires lasers when clicked
if (e.KeyCode.Equals(Keys.Space))
{
System.Media.SoundPlayer LaserSound = new System.Media.SoundPlayer(Properties.Resources.LaserSound);
LaserSound.Play();
this.lasers.Add(new Laser(this, SpaceFighter));
}
}
private void timer1_Tick(object sender, EventArgs e)
{
// introduces 10 enemies once the game starts
if (invaderNumber > 9 )
{
timer1.Enabled = false;
timer2.Enabled = true;
}
else
{
invaders.Add(new Invader(this));
invaderNumber++;
}
}
private void timer2_Tick(object sender, EventArgs e)
{
// detects if the enemy ship interacts with the spacefighter and ends the game if this happens
invaders.RemoveAll(ship => ship.isDisposed);
foreach(Invader ship in invaders)
{
ship.MoveInvader(this);
if (SpaceFighter.Bounds.IntersectsWith(ship.ship.Bounds))
{
// plays sound for exploding ship
System.Media.SoundPlayer SpaceshipSound = new System.Media.SoundPlayer(Properties.Resources.SpaceshipSound);
SpaceshipSound.Play();
timer2.Enabled = false;
timer3.Enabled = false;
timer4.Enabled = true;
invaders.Clear();
listBox1.Items.Add(lblScore.Text); // adds score to listbox
MessageBox.Show("You Lose!");
return;
}
}
// detects if an enemy ship his hit by a laser
lasers.RemoveAll(laser => laser.isDisposed);
foreach (Laser laser in lasers)
{
laser.MoveLaser(this);
foreach (Invader ship in invaders)
{
if (laser.laser.Bounds.IntersectsWith(ship.ship.Bounds))
{
laser.isDisposed = true;
laser.laser.Dispose();
ship.isDisposed = true;
ship.ship.Dispose(); // makes the ship dissappear once its shot
System.Media.SoundPlayer ShipSound = new System.Media.SoundPlayer(Properties.Resources.EnemySound); // sound for the enemy ship being destroyed
ShipSound.Play();
score = score + 2; //adds 2 points to players score if enemy is hit
lblScore.Text = score.ToString(); //updates the score label
invaderNumber = invaderNumber - 1;
}
}
}
foreach (Invader ship in invaders)
{
if (ship.ship.Top > 485)
{
ship.isDisposed = true;
ship.ship.Dispose();
invaderNumber = invaderNumber - 1;
}
}
}
private void btnStart_Click(object sender, EventArgs e)
{
timer1.Enabled = true; // activates timer 1
timer3.Enabled = true; // activates timer 3
btnStart.Visible = false; // hidesthe start button
lblScore.Text = "0"; // updates score label to 0 for start of game
lblName.Text = txtName.Text; // updates the name label to user nput
txtName.Visible = false; // hides the textbox
lblEnterName.Visible = false; // hides the enter name label
SpaceFighter.Visible = true; // makes the spacefighter visible
}
// code for the countdown clock
int m = 2;
int s = 60;
private void timer3_Tick(object sender, EventArgs e)
{
if(s > 0)
{
s = s - 1;
lblTimer.Text = "0" + m.ToString() + ":" + s.ToString();
}
if(s == 0)
{
s = 59;
m = m - 1;
lblTimer.Text = "0" + m.ToString() + ":" + s.ToString();
}
if(s < 10)
{
s = s - 1;
lblTimer.Text = "0" + m.ToString() + ":" + "0" + s.ToString();
}
if (m < 0)
{
listBox1.Items.Add(lblScore.Text + " " + lblName.Text); // adds score to list box
timer4.Enabled = true;
invaders.Clear();
}
if (m >= 0)
{
timer1.Enabled = true;
}
}
private void Form1_Load(object sender, EventArgs e)
{
SpaceFighter.Visible = false; // hides the space fighter until the player starts the game
listBox1.Visible = false; // keepsscore table hidden
lblScoreTable.Visible = false; // score table lables kept hidden
lblNameTable.Visible = false;
btnMenu.Visible = false;
}
private void Timer4_Tick(object sender, EventArgs e)
{
lblTimer.Text = "00:00"; // sets game timer to 00:00
timer3.Enabled = false; // disbales timer 3
listBox1.Visible = true; // makes score card visible
listBox1.Sorted = true;
lblNameTable.Visible = true; // displays score table labels
lblScoreTable.Visible = true;
btnMenu.Visible = true;
foreach (Invader ship in invaders)
{
ship.isDisposed = true;
ship.ship.Dispose();
}
}
private void BtnMenu_Click(object sender, EventArgs e)
{
// resets game to its original state in order to play another game
m = 2;
s = 60;
lblTimer.Text = "03:00";
timer1.Enabled = false;
timer2.Enabled = false;
timer3.Enabled = false;
timer4.Enabled = false;
listBox1.Visible = false;
lblNameTable.Visible = false;
lblScoreTable.Visible = false;
lblEnterName.Visible = true;
txtName.Visible = true;
SpaceFighter.Visible = false;
btnMenu.Visible = false;
btnStart.Visible = true;
score = 0;
lblScore.Text = "Score";
lblName.Text = "Name";
txtName.Clear();
invaderNumber = 0;
SpaceFighter.Top = 380;
SpaceFighter.Left = 400;
}
}
this would do:
foreach (var control in this.Controls)
{
var pb = control as PictureBox;
if (pb != null)
{
if (pb.Name != "SpaceFighter")
{
pb.Dispose();
this.Controls.Remove(pb);
}
}
}
for the listbox sorting:
using System.Collections;
ArrayList Sorting = new ArrayList();
foreach (var o in listBox1.Items)
{
Sorting.Add(o);
}
Sorting.Sort();
Sorting.Reverse();
listBox1.Items.Clear();
foreach (var o in Sorting)
{
listBox1.Items.Add(o);
}
Related
I have this simple snake game, my problem is that the tails wont add when it reaches three tails.
namespace Snake
{
public partial class Form1 : Form
{
bool left = false, right = false;
bool top = false, down = false;
PictureBox pic = new PictureBox();
List<PictureBox> tails = new List<PictureBox>();
int score = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if (((e.KeyChar.ToString() == "a") || (e.KeyChar.ToString() == "A"))&&(right == false))
{
right = false;
top = false;
down = false;
left = true;
}
else if (((e.KeyChar.ToString() == "d") || (e.KeyChar.ToString() == "D"))&& (left == false))
{
top = false;
down = false;
left = false;
right = true;
}
else if (((e.KeyChar.ToString() == "w") || (e.KeyChar.ToString() == "W"))&& (down == false))
{
down = false;
left = false;
right = false;
top = true;
}
else if (((e.KeyChar.ToString() == "s") || (e.KeyChar.ToString() == "S"))&& (top == false))
{
top = false;
left = false;
right = false;
down = true;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
//ticks every 1 sec
if (pic.Location == head.Location)
{
score++;
spawnFood();
tails.Add(addTails());
}
sortLocation();
if (right == true)
{
int r = head.Location.X + head.Height;
head.Location = new Point(r, head.Location.Y);
}
else if(left == true)
{
int l = head.Location.X - head.Height;
head.Location = new Point(l, head.Location.Y);
}
else if (top == true)
{
int t = head.Location.Y - head.Height;
head.Location = new Point(head.Location.X, t);
}
else if (down == true)
{
int d = head.Location.Y + head.Height;
head.Location = new Point(head.Location.X,d);
}
txtScore.Text = score.ToString();
}
private void sortLocation()
{
if (tails.Count == 0)
{
}
else
{
for (int i = 1; i < tails.Count; i++)
{
tails[i].Location = tails[i-1].Location;
}
tails[0].Location = head.Location;
}
}
private PictureBox addTails()
{
PictureBox tail = new PictureBox();
tail.Name = "tail" + score.ToString();
tail.BackColor = Color.Black;
tail.Width = 10;
tail.Height = 10;
this.Controls.Add(tail);
return tail;
}
private void spawnFood()
{
Random rnd = new Random();
int rndLocationX = rnd.Next(10, 50);
int rndLocationY = rnd.Next(10, 50);
pic.BackColor = Color.Red;
pic.Height = 10;
pic.Width = 10;
this.Controls.Add(pic);
if (rndLocationX >= 500)
{
rndLocationX -= 10;
}
if (rndLocationY >= 500)
{
rndLocationY -= 10;
}
pic.Location = new Point(rndLocationX*10,rndLocationY*10);
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Start();
spawnFood();
}
}
}
for (int i = 1; i < tails.Count; i++)
{
tails[i].Location = tails[i+1].Location;
}
tails[0].Location = head.Location;
Are your tails there just stacked so to speak? That's another thought I might be thinking. I changed the tails[i-1] to tails [i+1]. Check if that does the trick.
As you can see I've created an array of images, but I'm not sure how to load each image into successive indexes.
Someone told me to do this for my game but I'm not sure how or if it will fix my problem
I've made a game where the character walks left then up then down then right and a few timers that load the animation and handle the movement but when I draw using this code
*e.Graphics.DrawImage(Properties.Resources.Corn_Cobs, 70, 70, 40, 40);*
My character gets really laggy/slow but when I don't draw the image it works smoothly and the character speeds up like normal.
Here is the code:
namespace Rice_Boy_Tester_2
{
public partial class Form1 : Form
{
bool iggy = false;
bool left2 = false;
bool right2 = false;
bool Up2 = false;
bool Down2 = false;
bool Check2 = false;
bool left = false;
bool right = false;
bool Up = false;
bool Down = false;
bool Check = false;
Image[] Animations;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Animations = new Image[6];
Animations[0] = Image.FromFile("Rice-Boy-Walking-Left-Bouncing.gif");
Animations[1] = Image.FromFile("Rice-Boy-Walking-Up-Bouncing.gif");
Animations[2] = Image.FromFile("Rice-Boy-Walking-Right-Bouncing.gif");
Animations[3] = Image.FromFile("Rice-Boy-Walking-Down.gif");
Animations[4] = Properties.Resources.Rice_Boy_Standing_Left;
Animations[5] = Properties.Resources.Corn_Cobs;
}
private void Refresh_Tick(object sender, EventArgs e)
{
this.Refresh();
}
private void PriceBoyWalk_Tick(object sender, EventArgs e)
{
if (left)//Goes Left
{
Player.Left -= 1;
}
if (Player.Left < 170 & Check == false)//checks how far away player is from form
{
left = false;
Up = true;
}
if (Up & Player.Left < 170) //Goes Up
{
Player.Top -= 1;
Check = true;
}
if (Player.Top < 100 & Check)
{
Up = false;
Down = true;
}
if (right)//Goes Right
{
Player.Left += 1;
}
if (Down)//Goes Down
{
Player.Top += 1;
}
if (Player.Top + 150 > this.ClientSize.Height)// When RiceBoy goes down and hits bottom right = true
{
Check = false;
Down = false;
right = true;
}
if (Player.Left + 150 > this.ClientSize.Width)//Stops At Starting Point
{
right = false;
}
}
private void B1_Click(object sender, EventArgs e)
{
this.Paint += new PaintEventHandler(form1_Pad1_Corn);
RiceBoyWalkGif.Enabled = true;
left = true;
left2 = true;
RiceBoyWalk.Enabled = true;}
}
private void form1_Pad1_Corn(object sender, System.Windows.Forms.PaintEventArgs e)
{
e.Graphics.DrawImage(Properties.Resources.Corn_Cobs, 70, 70, 400, 400);
}
private void timer1_Tick(object sender, EventArgs e)
{
if (left2)
{
Player.Image = Animations[0];
left2 = false;
}
if (Player.Left < 170 & Check2 == false)//checks how far away player is from form
{
left2 = false;
Up2 = true;
}
if (Up2 & Player.Left < 170) //Goes Up
{
this.Player.Size = new System.Drawing.Size(36, 76); // Changes size of the picture box to maintain quaility
Player.Image = Animations[1];//Animates RiceBoyWalkingUp
Check2 = true;
Up2 = false;
}
if (Player.Top < 105 & Check2)//Player.Top < 101 must be +1 greater than the RiceBoyWalkTimer
{
Up2 = false;
Down2 = true;
}
if (right2)
{
this.Player.Size = new System.Drawing.Size(53, 77); // Changes size of the picture box to maintain quaility
Player.Image = Animations[2];//Animates RiceBoyWalkingRight
right2 = false;
}
if (Down2)//Goes Down
{
Player.Image = Animations[3];//Animates RiceBoyWalkingDown
Down2 = false;
}
if (Player.Top + 150 > this.ClientSize.Height)// When RiceBoy goes down and hits bottom riceboy walks right
{
iggy = true;// shows that riceboy is approching the starting point
Check2 = false;
Down2 = false;
right2 = true;
}
if (Player.Left + 150 > this.ClientSize.Width & iggy)//Stops At Starting Point
{
right2 = false;
Player.Image = Animations[4];// Rice boy standing left
}
I've made an countdown and i want to add an time check for it now. If the minutes are < 01 and the seconds are != 60 so 00:59 the Time should be orange and if the seconds are then smaller then 10 the time should be red.
But it does not work.
They're always just getting orange if the time is 00:00:58, but why?
private int hours, minutes, seconds;
private bool paused;
private void button_Start_Click(object sender, EventArgs e)
{
button_Pause.Enabled = true;
button_Stop.Enabled = true;
if(paused != true)
{
hours = int.Parse(textBox_Hours.Text);
minutes = int.Parse(textBox_Minutes.Text);
seconds = int.Parse(textBox_Seconds.Text) + 1;
textBox_Hours.Enabled = false;
textBox_Minutes.Enabled = false;
textBox_Seconds.Enabled = false;
button_Start.Enabled = false;
timer_CountDown.Start();
}
}
private void timer_CountDown_Tick(object sender, EventArgs e)
{
if(hours == 0 && minutes < 1)
{
label_Hours.ForeColor = Color.Red;
label_Minutes.ForeColor = Color.Red;
label_Seconds.ForeColor = Color.Red;
label8.ForeColor = Color.Red;
label10.ForeColor = Color.Red;
}
if(hours == 0 && minutes == 0 && seconds == 0)
{
timer_CountDown.Stop();
textBox_Seconds.Enabled = true;
textBox_Minutes.Enabled = true;
textBox_Hours.Enabled = true;
button_Start.Enabled = true;
}
else
{
if (seconds < 1)
{
seconds = 59;
if (minutes < 1)
{
minutes = 59;
if (hours != 0)
{
hours -= 1;
}
}
else
{
minutes -= 1;
}
}
else
{
seconds -= 1;
}
if(hours > 9)
{
label_Hours.Text = hours.ToString();
}
else { label_Hours.Text = "0" + hours.ToString(); }
if(minutes > 9)
{
label_Minutes.Text = minutes.ToString();
}
else { label_Minutes.Text = "0" + minutes.ToString(); }
if(seconds > 9)
{
label_Seconds.Text = seconds.ToString();
}
else { label_Seconds.Text = "0" + seconds.ToString(); }
}
}
The Timer Intervall is 1000.
You're over complicating things. Why not just use the TimeSpan type and get rid of those hours, minutes, seconds?
private TimeSpan countDownTime = TimeSpan.Zero;
private void timer_CountDown_Tick(object sender, EventArgs e)
{
if(countDownTime == TimeSpan.Zero)
{
timer_CountDown.Stop();
textBox_Seconds.Enabled = true;
textBox_Minutes.Enabled = true;
textBox_Hours.Enabled = true;
button_Start.Enabled = true;
return;
}
countDownTime = countDownTime.Add(TimeSpan.FromSeconds(1).Negate());
label_Hours.Text = countDownTime.ToString("hh");
label_Minutes.Text = countDownTime.ToString("mm");
label_Seconds.Text = countDownTime.ToString("ss");
if(countDownTime.TotalSeconds < 10)
{
label_Hours.ForeColor = Color.Red;
label_Minutes.ForeColor = Color.Red;
label_Seconds.ForeColor = Color.Red;
label8.ForeColor = Color.Red;
label10.ForeColor = Color.Red;
}
else if (countDownTime.TotalMinutes < 1)
{
label_Hours.ForeColor = Color.Orange;
label_Minutes.ForeColor = Color.Orange;
label_Seconds.ForeColor = Color.Orange;
label8.ForeColor = Color.Orange;
label10.ForeColor = Color.Orange;
}
}
private void button_Start_Click(object sender, EventArgs e)
{
button_Pause.Enabled = true;
button_Stop.Enabled = true;
if(paused != true)
{
int hours = int.Parse(textBox_Hours.Text);
int minutes = int.Parse(textBox_Minutes.Text);
int seconds = int.Parse(textBox_Seconds.Text) + 1;
this.countDownTime = new TimeSpan(hours,minutes,seconds);
textBox_Hours.Enabled = false;
textBox_Minutes.Enabled = false;
textBox_Seconds.Enabled = false;
button_Start.Enabled = false;
timer_CountDown.Start();
}
}
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.
I created a program what will type a text for me automatically by using SendKeys command. When I press start button the text will be typed as it should, and when I press start button the text will stop from typing. The typing is done by using an interval timer which will decide when to start typing and have a brief space between typing 2 lines.
The problem is that when I start typing and type part of the message then press stop before program can type the entire message then start typing again, the message will continue to type from where it stopped. For example I want to type the message "123456789". I start typing then program types "1234" then press stop so program wont type no more. Then when I press start again program should start typing from 1, but instead my program types "56789".
How to reset the line when I stop, then start again? I tried to make the message as a "message" variable which is reset when I press stop button but it doesn't work.
This is how I set to type every interval tick:
private void Space(object sender, EventArgs e)
{
if (cbRandomLine.Checked || tickCount < lbMessage.Items.Count)
{
var index = cbRandomLine.Checked ? randomLine : tickCount;
var item = lbMessage.Items[index].ToString();
SendKeys.Send(item.Substring(currentChar++, 1));
if (currentChar == item.Length)
{
SendKeys.Send("{enter}");
tmrSpace.Enabled = false;
currentChar = 0;
}
}
tmrSpace.Interval = random.Next(10, 100);
}
private void Delay(object sender, EventArgs e)
{
if (delayCount == 0)
{
tmrDelay.Stop();
tmrInterval.Start();
lblDelay.Text = "Typing...";
}
else lblDelay.Text = "Typing in: " + delayCount;
delayCount--;
}
// METHODS
private void WhenStarted()
{
tickCount = 0;
delayCount = 2;
lbMessage.Enabled = false;
txtMessage.Enabled = false;
if (cbDelay.Checked)
{
lblDelay.Text = "Typing...";
tmrInterval.Enabled = true;
}
else
{
lblDelay.Text = "Typing in: 3";
tmrDelay.Enabled = true;
}
cbPause.Enabled = false;
cbDelay.Enabled = false;
cbRandomLine.Enabled = false;
btnStart.Enabled = false;
btnStop.Enabled = true;
btnStop.Focus();
}
private void WhenStopped()
{
lblDelay.Text = string.Empty;
whenStart = false;
tickCount = 0;
txtMessage.Text = string.Empty;
lbMessage.Enabled = true;
txtMessage.Enabled = true;
cbPause.Enabled = true;
cbDelay.Enabled = true;
cbRandomLine.Enabled = true;
btnStart.Enabled = true;
btnStop.Enabled = false;
btnStart.Focus();
tmrDelay.Enabled = false;
tmrInterval.Enabled = false;
tmrSpace.Enabled = false;
}
private void SetInterval()
{
if (nudPlusMinus.Value == 0)
{
tmrInterval.Interval = int.Parse(nudInterval.Value.ToString());
}
else
{
tmrInterval.Interval = random.Next(int.Parse(nudInterval.Value.ToString()) - int.Parse(nudPlusMinus.Value.ToString()), int.Parse(nudInterval.Value.ToString()) + int.Parse(nudPlusMinus.Value.ToString()));
}
}
private void ListBoxContentCheck()
{
if (lbMessage.Items.Count > 0)
{
btnStart.Enabled = true;
}
else
{
btnStart.Enabled = false;
}
}
You need to reset the currentChar variable.