How to access a variable defined in designer code from other classes? - c#

I'm trying to make a game that is round-based, and I want to make it so that the user is able to define the amount of rounds from the beginning. I've made it so that the user will input a number into a text box, and then a button will put that number into a variable called length by using "length = Convert.ToInt32(textBox1.Text)". Unfortunately, I'm not sure how to access this length variable from the Form1 class so that I can set the number of rounds. Can someone please point me in the right direction? I've tried doing SpeedDialog.length (SpeedDialog is a windows form designer class that I'm getting the info from), but it did not seem to work, saying that I cannot reference a non-static class. Could I fix this problem by making SpeedDialog static (I'm thinking not but I could be wrong)? Thank you so much! I really appreciate it!
Here's my Form1 class:
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;
using System.Runtime.InteropServices;
using System.Threading;
namespace BrickO1
{
public partial class Form1 : Form
{
private const int kNumberOfTries = 3;
public int rounds;
private Ball TheBall = new Ball();
private Paddle ThePaddle = new Paddle();
private Paddle TheOtherPaddle = new Paddle();
// private System.Windows.Forms.Timer timer1;
private Score TheScore = null;
private Score TheOtherScore = null;
private Thread oThread = null; //thread is used to run sounds independently
[DllImport("winmm.dll")]
public static extern long PlaySound(String lpszName, long hModule, long dwFlags);
//method PlaySound must be imported from the .dll file winmm
public Form1()
{
InitializeComponent();
ThePaddle.Position.X = 5;
ThePaddle.Position.Y = this.ClientRectangle.Bottom - ThePaddle.Height;
TheOtherPaddle.Position.X = 5;
TheOtherPaddle.Position.Y = 0;
// this.ClientRectangle refers to the current container (the instance of Form1)
TheBall.Position.Y = this.ClientRectangle.Bottom - 200;
TheScore = new Score(ClientRectangle.Right - 30, ClientRectangle.Bottom - 40);
TheOtherScore = new Score(ClientRectangle.Right - 30, ClientRectangle.Bottom - 370);
//positions the score - 0 at this moment
// choose Level
SpeedDialog dlg = new SpeedDialog();
/* makes sure that, if the DialogResult property of the button "OK" is on,
the SpeedDialog form appears and stays on the screen, and timer's Interval
gets an appropriate value */
if (dlg.ShowDialog() == DialogResult.OK)
{
timer1.Interval = dlg.Speed;
}
}
private string m_strCurrentSoundFile = "BallOut.wav"; //sound file is initialized
public void PlayASound() //method to play a sound; to be called by a thread
{
if (m_strCurrentSoundFile.Length > 0)
{
PlaySound(Application.StartupPath + "\\" + m_strCurrentSoundFile, 0, 0);
/* the above gives full path to the location of the sound file from the startup path
of the executable file: Application.StartupPath */
}
m_strCurrentSoundFile = "";
oThread.Abort(); //aborts the tread playing sound
}
public void PlaySoundInThread(string wavefile) //creates and starts a new thread to play a sound
{
m_strCurrentSoundFile = wavefile;
oThread = new Thread(new ThreadStart(PlayASound)); //calls the method PlayASound
oThread.Start();
}
private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e) //method to draw Form1
{
Graphics g = e.Graphics;
g.FillRectangle(Brushes.White, 0, 0, this.ClientRectangle.Width, this.ClientRectangle.Height);
TheScore.Draw(g);
TheOtherScore.Draw(g);
ThePaddle.Draw(g);
TheOtherPaddle.Draw(g);
TheBall.Draw(g);
}
private void CheckForCollision()
{
if (TheBall.Position.X < 0) // hit the left side, switch polarity
{
TheBall.XStep *= -1;
TheBall.Position.X += TheBall.XStep;
PlaySoundInThread("WallHit.wav");
}
if (TheBall.Position.Y < 0) // hit the top of the form
{
//Lost the ball for 2nd paddle
TheScore.Increment();
if(TheScore.Count == SpeedDialog.length)
{
MessageBox.Show("Congrats! Player 1 wins!");
Application.Exit();
}
Reset();
PlaySoundInThread("BallOut.wav");
}
if (TheBall.Position.X > this.ClientRectangle.Right - TheBall.Width) // hit the right side, switch polarity
{
TheBall.XStep *= -1;
TheBall.Position.X += TheBall.XStep;
PlaySoundInThread("WallHit.wav");
}
if (TheBall.Position.Y > this.ClientRectangle.Bottom - TheBall.YStep) // lost the ball!
{
TheOtherScore.Increment();
if (TheScore.Count == SpeedDialog.length)
{
MessageBox.Show("Congrats! Player 2 wins!");
Application.Exit();
}
Reset();
PlaySoundInThread("BallOut.wav");
}
int hp = HitsPaddle(TheBall.Position); //check if the ball hit the paddle
if (hp > -1)// checks if the ball is not lost
{
PlaySoundInThread("PaddleHit.wav");
switch (hp) //new direction of the ball depends on which quarter of the paddle is hit
{
case 1:
TheBall.XStep = -7;
TheBall.YStep = -3;
break;
case 2:
TheBall.XStep = -5;
TheBall.YStep = -5;
break;
case 3:
TheBall.XStep = 5;
TheBall.YStep = -5;
break;
default:
TheBall.XStep = 7;
TheBall.YStep = -3;
break;
}
}
int hp2 = HitsPaddle2(TheBall.Position); //check if the ball hit the paddle
if (hp2 > -1)// checks if the ball is not lost
{
PlaySoundInThread("PaddleHit.wav");
switch (hp2) //new direction of the ball depends on which quarter of the paddle is hit
{
case 1:
TheBall.XStep = -7;
TheBall.YStep = 3;
break;
case 2:
TheBall.XStep = -5;
TheBall.YStep = 5;
break;
case 3:
TheBall.XStep = 5;
TheBall.YStep = 5;
break;
default:
TheBall.XStep = 7;
TheBall.YStep = 3;
break;
}
}
}
private int HitsPaddle(Point p)
{
Rectangle PaddleRect = ThePaddle.GetBounds(); //current position of the paddle
if (p.Y >= this.ClientRectangle.Bottom - (PaddleRect.Height + TheBall.Height))//If the ball has hit the paddle according to its y value
{
if ((p.X > PaddleRect.Left) && (p.X < PaddleRect.Right)) //ball hits the paddle (horizontally)!
{
if ((p.X > PaddleRect.Left) && (p.X <= PaddleRect.Left + PaddleRect.Width / 4))
return 1; //hits leftmost quarter of the paddle
else if ((p.X > PaddleRect.Left + PaddleRect.Width / 4) && (p.X <= PaddleRect.Left + PaddleRect.Width / 2))
return 2; //hits the second quarter of the paddle
else if ((p.X > PaddleRect.Left + PaddleRect.Width / 2) && (p.X <= PaddleRect.Right - PaddleRect.Width / 2))
return 3; //hits the third quarter of the paddle
else
return 4; //hits the rightmost quarter of the paddle
}
}
return -1;
}
private int HitsPaddle2(Point q)
{
Rectangle Paddle2Rect = TheOtherPaddle.GetBounds(); //current position of the paddle
if (q.Y <= this.ClientRectangle.Top + Paddle2Rect.Height)
{
if ((q.X > Paddle2Rect.Left) && (q.X < Paddle2Rect.Right)) //ball hits the paddle!
{
if ((q.X > Paddle2Rect.Left) && (q.X <= Paddle2Rect.Left + Paddle2Rect.Width / 4))
return 1; //hits leftmost quarter of the paddle
else if ((q.X > Paddle2Rect.Left + Paddle2Rect.Width / 4) && (q.X <= Paddle2Rect.Left + Paddle2Rect.Width / 2))
return 2; //hits the second quarter of the paddle
else if ((q.X > Paddle2Rect.Left + Paddle2Rect.Width / 2) && (q.X <= Paddle2Rect.Right - Paddle2Rect.Width / 2))
return 3; //hits the third quarter of the paddle
else
return 4; //hits the rightmost quarter of the paddle
}
}
return -1;
}
private void Reset() //resets the ball, stops timer, and redraws the main form
{
TheBall.XStep = 5;
TheBall.YStep = 5;
TheBall.Position.Y = this.ClientRectangle.Bottom - 190;
TheBall.Position.X = 5;
timer1.Stop();
TheBall.UpdateBounds();
Invalidate(TheBall.GetBounds());
}
private void timer1_Tick(object sender, System.EventArgs e) //runs one round of the game, when started
{
TheBall.UpdateBounds(); //gets the ball position
Invalidate(TheBall.GetBounds()); //redraws the ball
TheBall.Move(); //moves the ball
TheBall.UpdateBounds(); //updates position of the ball
Invalidate(TheBall.GetBounds()); //redraws the boll
CheckForCollision(); //checks for collision
Invalidate(TheScore.GetFrame()); //redraws the score
Invalidate(TheOtherScore.GetFrame());
}
private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
string result = e.KeyData.ToString();
Invalidate(ThePaddle.GetBounds());
switch (result)
{
case "Left":
ThePaddle.MoveLeft();
Invalidate(ThePaddle.GetBounds());
if (timer1.Enabled == false) //starts the game if it does not run yet
timer1.Start();
break;
case "Right":
ThePaddle.MoveRight(ClientRectangle.Right);
Invalidate(ThePaddle.GetBounds());
if (timer1.Enabled == false) //starts the game if it does not run yet
timer1.Start();
break;
case "Z":
TheOtherPaddle.MoveLeft();
Invalidate(TheOtherPaddle.GetBounds());
if (timer1.Enabled == false) //starts the game if it does not run yet
timer1.Start();
break;
case "C":
TheOtherPaddle.MoveRight(ClientRectangle.Right);
Invalidate(TheOtherPaddle.GetBounds());
if (timer1.Enabled == false) //starts the game if it does not run yet
timer1.Start();
break;
default:
break;
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
And here's the SpeedDialog class:
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 BrickO1
{
public partial class SpeedDialog : Form
{
public int Speed = 250;
private static int length = 0;
public SpeedDialog()
{
InitializeComponent();
}
private void SlowRadio_CheckedChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, System.EventArgs e)
{
if (SlowRadio.Checked)
Speed = 100;
else if (MediumRadio.Checked)
Speed = 100;
else
Speed = 50;
length = Convert.ToInt32(textBox1.Text);
if(length == 0)
{
length = 5;
}
}
public int SelectedLength { get{ return length; }}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void SpeedDialog_Load(object sender, EventArgs e)
{
}
private void groupBox2_Enter(object sender, EventArgs e)
{
}
private void maskedTextBox1_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
Thanks again!!!

Related

How do I specifically check is a the slots all have a jackpot image for slot machine game

How do I also make it so that if all 3 slots have a jackpot image, the user wins 5x their bet
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlTypes;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace Slot_Machine
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Random rnd = new Random();
int a, b, c, move, wins,losses, bid;
int balance = 100;
If the user clicks the quit button, the program ends
private void QuitBtn_Click(object sender, EventArgs e)
{
this.Close();
}
If the user presses the reset button, the game restarts
private void ResetBtn_Click(object sender, EventArgs e)
{
Application.Restart();
}
This function subtracts the bid from the balance before the slots start running
void Before_Game_Result()
{
bid = Convert.ToInt32(BidAmountTxt.Text);
balance = balance - bid;
BalanceLbl.Text = "Balance: $" + Convert.ToString(balance);
}
This function decides whether or not the user won their bid
void Game_Result()
{
if (System.Convert.ToInt32(a) == b && System.Convert.ToInt32(b) == c)
{
wins++;
WinLbl.Text = "Wins: " + wins;
bid = Convert.ToInt32(BidAmountTxt.Text);
balance = balance + (bid * 2);
BalanceLbl.Text = "Balance: $" + Convert.ToString(balance);
BidBtn.Enabled = true;
BidAmountTxt.Enabled = true;
BidAmountTxt.BackColor = Color.White;
}
else
{
if ((System.Convert.ToInt32(a) == b && System.Convert.ToInt32(b) != c) || (System.Convert.ToInt32(a) == c && System.Convert.ToInt32(b) != c) ||
(System.Convert.ToInt32(b) == c && System.Convert.ToInt32(a) != c))
{
wins++;
WinLbl.Text = "Wins: " + wins;
bid = Convert.ToInt32(BidAmountTxt.Text);
balance = balance + bid;
BalanceLbl.Text = "Balance: $" + Convert.ToString(balance);
BidBtn.Enabled = true;
BidAmountTxt.Enabled = true;
BidAmountTxt.BackColor = Color.White;
}
else
{
losses++;
LossesLbl.Text = "Losses: " + losses;
BalanceLbl.Text = "Balance: $" + Convert.ToString(balance);
BidBtn.Enabled = true;
BidAmountTxt.Enabled = true;
BidAmountTxt.BackColor = Color.White;
}
}
if (balance <= 0)
{
MessageBox.Show("You don't have any money!! SCRAM");
this.Close();
}
}
This function validates that the user enters a valid bid before pressing the bid button
private void BidBtn_Click(object sender, EventArgs e)
{
if(BidAmountTxt.Text =="")
{
MessageBox.Show("input a bid first!!");
}
else
{
int x = Convert.ToInt32(BidAmountTxt.Text);
bool success = false;
if(x <= balance)
{
success = true;
}
if(success)
{
Before_Game_Result();
timer1.Enabled = true;
BidAmountTxt.Enabled = false;
BidBtn.Enabled = false;
BidAmountTxt.BackColor = Color.Black;
}
else
{
MessageBox.Show("INVALID - please enter a bid lower or equal to your balance");
BidAmountTxt.Clear();
}
}
}
**This function runs the slots **
private void timer1_Tick(object sender, EventArgs e)
{
move++;
if (move < 30)
{
a = rnd.Next(5);
b = rnd.Next(5);
c = rnd.Next(5);
switch(a)
{
case 1:
Slot1.Image = Properties.Resources.basketball3;
break;
case 2:
Slot1.Image = Properties.Resources.soccer_ball2;
break;
case 3:
Slot1.Image = Properties.Resources.volleyball;
break;
case 4:
Slot1.Image = Properties.Resources.hockey_puck;
break;
}
switch (b)
{
case 1:
Slot2.Image = Properties.Resources.basketball3;
break;
case 2:
Slot2.Image = Properties.Resources.soccer_ball2;
break;
case 3:
Slot2.Image = Properties.Resources.volleyball;
break;
case 4:
Slot2.Image = Properties.Resources.hockey_puck;
break;
}
switch (c)
{
case 1:
Slot3.Image = Properties.Resources.basketball3;
break;
case 2:
Slot3.Image = Properties.Resources.soccer_ball2;
break;
case 3:
Slot3.Image = Properties.Resources.volleyball;
break;
case 4:
Slot3.Image = Properties.Resources.hockey_puck;
break;
}
}
else
{
timer1.Enabled = false;
move = 0;
Game_Result();
}
}
}
}
There's lot of ways to do what you want. My take on this is that a little abstraction would go a long way. Starting with an ImageList where you can select pictures by index.
Assign it to the ImageList property of the controls (e.g. Label) you are using to display a slot "wheel".
public MainForm()
{
InitializeComponent();
labelJackpot.Visible= false;
Slot1.ImageList = imageList;
Slot2.ImageList = imageList;
Slot3.ImageList = imageList;
}
Then you could abstract those index values to an enum.
enum SlotImage
{
Jackpot,
Basketball,
SoccerBall,
VolleyBall,
HockeyPuck,
}
Which simplifies your "wheel spinner" in your timer tick handler:
Label[] Slots => new [] { Slot1, Slot2, Slot3 };
SlotImage[] SlotImages { get; } = Enum.GetValues(typeof(SlotImage)).Cast<SlotImage>().ToArray();
private void timer1_Tick(object sender, EventArgs e)
{
move++;
if (move < 30)
{
foreach (var slot in Slots)
{
slot.ImageIndex= rnd.Next(SlotImages.Length);
}
}
else
{
timer1.Enabled = false;
move = 0;
// Probably goes in GameResult but here's how.
var isJackpot = Slots.All(_ => ((SlotImage)_.ImageIndex).Equals(SlotImage.Jackpot));
labelJackpot.Visible = isJackpot;
Game_Result();
}
}
Doing it in this manner would make the wheels comparable by int. So, one solution to your question is to use this System.Linq expression to see whether you've hit the jackpot.
isJackpot = Slots.All(_ => ((SlotImage)_.ImageIndex).Equals(SlotImage.Jackpot));

Pong game use enum for direction player in C#

I am new to enum and my teacher said I should use it in my code, so I tried but it doesn't work, I am trying to make pong. This is my code. I tried using examples form other codes with enum but it doesnt work.
using System;
using System.Windows.Forms;
namespace pong_1._13
{
public partial class Form1 : Form
{
int MaxScore = 10; // the max score you can get
int ActivateBotCheat = 9; // makes the bot always win when the playerscore = the value of AcitvateBotCheat, To turn cheat off set value to 10
int speed = 6; // bot speed
int playerSpeed = 8; // the speed of the player
int topScreen = 0; // the top of the screen
int bottemScreen = 350; // the boytom of th screen
int middelScreen = 300; // respawnpoint of the ball
int leftSideScreen = 0; // the left side of the screen
// right side of screen = ClientSize.Width
int YIs0 = 10; // the value Y gets when it ends up at 0 so the bal keeps going up and down
int YcheatOffset = 30; // offset bot when cheat is enabled
enum Deraction {goUp, goDown}
Deraction UpDown;
int ballX = 5; // the x angle of the ball left/right
int ballY = 5; // the y angle of the ball up/down
int ballXspeedAdd = 1; // after round add ball speed X
int ballYspeedAdd = 5; // after round add ball speed Y
int score = 0; // the score of the player
int scoreAI = 0; // the score of the bot
public Form1()
{
InitializeComponent();
}
private void keyIsUp(object sender, KeyEventArgs e) // looks if the player wants to go up or down if not then makes the player stand still
{
if (e.KeyCode == Keys.Up)
{
}
else if (e.KeyCode == Keys.Down)
{
Deraction Down = Deraction.goDown;
}
}
private void keyIsDown(object sender, KeyEventArgs e) // looks if the player wants to go up or down if so makes the player go up and down
{
if (e.KeyCode == Keys.Down)
{
Deraction Down = Deraction.goDown;
}
else if (e.KeyCode == Keys.Up)
{
Deraction Up = Deraction.goUp;
}
}
private void timerTick(object sender, EventArgs e)
{
playerScore.Text = "" + score; // dispays player score
aiScore.Text = "" + scoreAI; // displays bot score
ball.Top += ballY; // makes the ball bouwns
ball.Left -= ballX; // makes the ball bouwns
bot.Top += speed; // makes bot faster
if (score < ActivateBotCheat)
{
if (bot.Top < topScreen || bot.Top > bottemScreen) // normal game play for the bot
{
speed = -speed; // makes bot slower
}
}
else // cheat code for bot
{
bot.Top = ball.Top - YcheatOffset; // set the x cordinats of the bot = to x cordinats of the ball mines the offset
}
if (ball.Left < leftSideScreen) // when bot scores
{
ball.Left = middelScreen; // respawnpoit ball
ballX = -ballX; // makes the ball go the other way
ballX -= ballXspeedAdd; // makes the bal go faster
ballY = -ballY; // makes the ball go the other way
ballY += ballYspeedAdd; // makes the bal go faster
scoreAI++;
}
if (ball.Left + ball.Width > ClientSize.Width) // when player scores
{
ball.Left = middelScreen; // respawnpoit ball
ballX = -ballX; // makes the ball go the other way
ballX += ballXspeedAdd; // makes the bal go faster
ballY = -ballY; // makes the ball go the other way
ballY += ballYspeedAdd; // makes the bal go faster
score++;
}
if (ball.Top < leftSideScreen || ball.Top + ball.Height > ClientSize.Height) // when ball hits border of the screen
{
ballY = -ballY; // makes the ball go the other way
}
if (ball.Bounds.IntersectsWith(player.Bounds) || ball.Bounds.IntersectsWith(bot.Bounds)) // when ball hits border of the screen
{
ballX = -ballX; // makes the ball go the other way
}
if(ballY == 0) // makes sure ball Y is not 0
{
ballY += YIs0;
}
if (UpDown == Deraction.goUp && player.Top > topScreen) // makes player go up
{
player.Top -= playerSpeed;
}
if (UpDown == Deraction.goDown && player.Top < bottemScreen) // makes player go down
{
player.Top += playerSpeed;
}
if (score == MaxScore) // show message when player wins
{
score++;
gameTimer.Stop();
MessageBox.Show("You win this game");
}
if (scoreAI == MaxScore) // show message when bot wins
{
scoreAI++;
gameTimer.Stop();
MessageBox.Show("The bot wins, you lose");
}
}
}
}
enum Deraction {goUp, goDown};
Deraction UpDown;
This is correct. Your problem is that you are not using UpDown later. Instead, you are writing Deraction Down = Deraction.goDown; which does not affect UpDown.
Change your code to assign to UpDown.
Example:
private void keyIsUp(object sender, KeyEventArgs e) // looks if the player wants to go up or down if not then makes the player stand still
{
if (e.KeyCode == Keys.Up)
{
}
else if (e.KeyCode == Keys.Down)
{
UpDown = Deraction.goDown;
}
}
private void keyIsDown(object sender, KeyEventArgs e) // looks if the player wants to go up or down if so makes the player go up and down
{
if (e.KeyCode == Keys.Down)
{
UpDown = Deraction.goDown;
}
else if (e.KeyCode == Keys.Up)
{
UpDown = Deraction.goUp;
}
}

Moving Picturebox randomly as it roams

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();
}
}

c# Platform game optimization issue + player studdering

This is my first question on stackoverflow, sorry if I made stupid mistakes,
I hope you can help me out!
So my game looks kinda laggy when i Run it, my player studders and if I add gifs instead of image's then everything is very slow :/
I used pictureboxes as Image's
Here is my code (I just used one class):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ProjectBlok1Remake
{
public partial class myGame : Form
{
bool jump = false;
bool right = false;
bool left = false;
int score = 0;
int jumpspeed = 10;
int force = 8;
System.Media.SoundPlayer sp = new System.Media.SoundPlayer("muziek.wav");
public myGame()
{
InitializeComponent();
sp.Play(); // play music :)
}
private void myGame_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Right)
{
right = true;
}
if (e.KeyCode == Keys.Left)
{
left = true;
}
if (e.KeyCode == Keys.Escape)
{
this.Close(); //exist the game
}
if (jump != true)
{
if (e.KeyCode == Keys.Space)
{
jump = true;
}
}
}
private void myGame_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Right)
{
right = false;
}
if (e.KeyCode == Keys.Left)
{
left = false;
}
if (jump)
{
jump = false;
}
}
private void AddPoints(int valueCoin)
{
score = valueCoin + score;
}
private void GameTimer(object sender, EventArgs e)
{
player.Top += jumpspeed;
if (jump && force < 0)
{
jump = false;
}
if (left)
{
player.Left -= 5;
}
if (right)
{
player.Left += 5;
}
if (jump)
{
jumpspeed = -12;
force -= 1;
}
else
{
jumpspeed = 12;
}
foreach (Control x in this.Controls)
{
if (x is PictureBox && x.Tag == "platform")
{
if (player.Bounds.IntersectsWith(x.Bounds) && !jump)
{
force = 8;
player.Top = x.Top - player.Height;
}
}
if (x is PictureBox && x.Tag == "coin")
{
if (player.Bounds.IntersectsWith(x.Bounds) && !jump)
{
this.Controls.Remove(x); //will remove current touched coin :)
AddPoints(5); // each coin taken, will increase the score with 5 points!
}
}
if (x is PictureBox && x.Tag == "bigCoin")
{
if (player.Bounds.IntersectsWith(x.Bounds) && !jump)
{
this.Controls.Remove(x); //will remove current touched coin :)
AddPoints(15); ; // each coin taken, will increase the score with 15 points!
}
}
this.scoreLabel.Text = "score: " + score;
}
if (player.Bounds.IntersectsWith(door.Bounds))
{
timer1.Stop();
sp.Stop();
MessageBox.Show("Congratulations! YOU WON THE GAME! + \n With a total score of: " + score + "\n Exit the game with escape (2x)");
}
if (player.Bounds.IntersectsWith(panel1.Bounds))
{
timer1.Stop();
sp.Stop();
MessageBox.Show("YOU DIED, GAME OVER! :c");
}
}
}
}
Here is an Image of how the game looks like, All the Image's you see are uploaded from a file.
https://i.stack.imgur.com/8QiIc.png
...but if i delete that, there is no gravity and he can't jump.... I didn't say to delete it. I just pointed the problem of changing the position of the player prior the intersect checking. The way you do it is to chech if the new position is ok then change it:
CODE:
private void GameTimer(object sender, EventArgs e)
{
//Don't change the position of the player but a copy one, playerClone!
Rectangle playerClone = player.Bounds;
playerClone.Y += jumpspeed;
if (jump && force < 0)
{
jump = false;
}
if (left)
{
playerClone.X -= 5;
}
if (right)
{
playerClone.X += 5;
}
if (jump)
{
jumpspeed = -12;
force -= 1;
}
else
{
jumpspeed = 12;
}
foreach (Control x in this.Controls)
{
if (x is PictureBox && x.Tag == "platform")
{
if (playerClone.IntersectsWith(x.Bounds) && !jump)
{
force = 8;
playerClone.Y = x.Top - playerClone.Height;
}
}
if (x is PictureBox && x.Tag == "coin")
{
if (playerClone.IntersectsWith(x.Bounds) && !jump)
{
this.Controls.Remove(x); //will remove current touched coin :)
AddPoints(5); // each coin taken, will increase the score with 5 points!
}
}
if (x is PictureBox && x.Tag == "bigCoin")
{
if (playerClone.IntersectsWith(x.Bounds) && !jump)
{
this.Controls.Remove(x); //will remove current touched coin :)
AddPoints(15); ; // each coin taken, will increase the score with 15 points!
}
}
this.scoreLabel.Text = "score: " + score;
}
if (playerClone.IntersectsWith(door.Bounds))
{
timer1.Stop();
sp.Stop();
MessageBox.Show("Congratulations! YOU WON THE GAME! + \n With a total score of: " + score + "\n Exit the game with escape (2x)");
return;
}
if (playerClone.IntersectsWith(panel1.Bounds))
{
timer1.Stop();
sp.Stop();
MessageBox.Show("YOU DIED, GAME OVER! :c");
return;
}
//And now set the player position
player.Bounds = playerClone;
}

Detect picture box Edges C#

I'm creating a simple bouncing ball application that uses a timer to bounce the ball of the sides of a picture box, the trouble i'm having with this is that it bounces fine off the bottom and right side of the picture box but doesn't bounce off the top or left side and i'm not sure why, the ball size is 30 if you wanted to know
The code for it is:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace Ball
{
public partial class Form1 : Form
{
int x = 200, y = 50; // start position of ball
int xmove = 10, ymove = 10; // amount of movement for each tick
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void pbxDisplay_Paint(object sender, PaintEventArgs e)
{
Graphics g = e.Graphics; // get a graphics object
// draw a red ball, size 30, at x, y position
g.FillEllipse(Brushes.Red, x, y, 30, 30);
}
private void timer1_Tick(object sender, EventArgs e)
{
x += xmove; // add 10 to x and y positions
y += ymove;
if(y + 30 >= pbxDisplay.Height)
{
ymove = -ymove;
}
if (x + 30 >= pbxDisplay.Width)
{
xmove = -xmove;
}
if (x - 30 >= pbxDisplay.Width)
{
xmove = -xmove;
}
if (y - 30 >= pbxDisplay.Height)
{
ymove = -ymove;
}
Refresh(); // refresh the`screen .. calling Paint() again
}
private void btnQuit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void btnStart_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
}
private void btnStop_Click(object sender, EventArgs e)
{
timer1.Enabled= false;
}
}
}
If anyone can see what my problem is then please let me know, thanks alot!
Well your method for edge recognition is wrong. Top left corner point got coordinates [0,0]. So you should check left and top against zero. Not Width and Height.
So your code should look like:
private void timer1_Tick(object sender, EventArgs e)
{
x += xmove; // add 10 to x and y positions
y += ymove;
if(y + 30 >= pbxDisplay.Height)
{
ymove = -ymove;
}
if (x + 30 >= pbxDisplay.Width)
{
xmove = -xmove;
}
if (x - 30 <= 0)
{
xmove = -xmove;
}
if (y - 30 <= 0)
{
ymove = -ymove;
}
Refresh(); // refresh the`screen .. calling Paint() again
}

Categories