Creating a Car Class with Acceleration and Braking - c#

EDIT: I have tried this a different way and updated my new code. I am now getting a few errors:
1. 'Car_Class_BBrantley.Car.Car()' must declare a body because it is not marked abstract, extern, or partial
2. No overload for method 'GetCarData' takes 0 arguments
3. No overload for method 'GetCarData' takes 0 arguments
These last two errors fall under the GetCarData(); lines which are under the two button sections.
Alright, so my task is to create an application that displays 3 main features: year, make, and speed of a car. The year and make are inputted with textboxes and the speed starts at 0.
There is an accelerate button which is supposed to add 5 to the speed every time it is pressed and a brake button which decreases the speed by 5 every time it is pressed.
I am having trouble using the class and form together to display the results. I need to display in a messagebox the make, year, and speed. I have been sitting here for hours and I am getting nowhere. I am getting the errors " speed does not exist in current context" and "car does not exist in current context" under my buttons. I am unsure of how I should go about fixing this.
Any and all help is much appreciated. I'm sorry if this is a mess. I have never worked with classes before.
Here is the form:
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 Car_Class_BBrantley
{
public partial class Form1 : Form
{
private Car myCar;
public Form1()
{
myCar = new Car;
InitializeComponent();
}
private void GetCarData(Car car)
{
try {
myCar.Make = txtMake.Text;
myCar.Year = int.Parse(txtModel.Text);
myCar.Speed = 0;
}
catch (Exception ex)
{
MessageBox.Show(string.Concat("Must enter a valid make and year model for the car. ", ex.Message, "\r\n", ex.StackTrace));
}
}
private void btnAcc_Click(object sender, EventArgs e)
{
GetCarData();
myCar.AccSpeed(5);
MessageBox.Show(" Your car is a " + myCar.Year + myCar.Make + " and it is traveling " + myCar.Speed + " mph. ");
}
private void btnBrake_Click(object sender, EventArgs e)
{
GetCarData();
myCar.DecSpeed(5);
MessageBox.Show(" Your car is a " + myCar.Year + myCar.Make + " and it is traveling " + myCar.Speed + " mph. ");
}
}
}
///////////////////////////////////////////////////////////////////////////////////////
If you would like to see the class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Car_Class_BBrantley
{
class Car
{
private int year;
private string make;
private int speed;
public Car()
{
this.year = 1994;
this.make = "Ford";
this.speed = 0;
}
public Car(string make, int year, int speed)
{
this.year = year;
this.make = make;
this.speed = speed;
}
public string Make
{
get { return make; }
set { make = value; }
}
public int Year
{
get { return Year; }
set { Year = value; }
}
public int Speed
{
get { return speed; }
set { speed = value; }
}
public void AccSpeed(int speedIncrement)
{
//Add check for speed limit ranges
Speed += speedIncrement;
}
public void DecSpeed(int speedDecrement)
{
//Add check for speed limit ranges
Speed -= speedDecrement;
}
}
}

This code:
public int AccSpeed
{
get { return Speed + 5; }
}
.. says "get a copy of the value in property Speed and increase that copy with five before returning the result"
What you want is: "increase the value of property Speed with five and then return the result". That is done by using:
public int AccSpeed
{
get
{
Speed = Speed + 5; //shorter code: Speed += 5;
return Speed;
}
}
However, Properties should never change state of classes in the get methods. Anyone using your code would get really confused if it did.
Instead use a method to make it crystal clear:
public int Accelerate()
{
Speed += 5;
return Speed;
}

You can declare your variables like this:
public int name { get; set; }
this automatically makes it a variable with a getter and setter.
As for the methods that increase speed etc. you could make a method like this fx:
public void AccSpeed() {
Speed += 5;
}
As for the rest you should be able to figure it out from this.
EDIT: Elaboration.
As I think your confused on how classes work let me elaborate. In your class name you have included the type of car I'm guessing because the class is supposed to represent that certain type of car.
You shouldn't think like this in programming. Instead you should create a Car class that can represent any and all types of cars.
So maybe add a string variable called type, and insert that in the constructor fx. thereby declaring what particular type of car it is. Then simply call your class Car.
If you then later want to add methods to specific types of cars, you could make subclasses of your car class that extends the main car class.
Fx. like below. Then you add the additional methods a racing car should have to this class.
RacingCar : Car {
// class content
}

Related

Basic C# object vs object interaction

I'm currently going through various resources and trying to learn C# OOP. I haven't gone through anything on it yet but I had a go at object vs object interaction. Unfortunately it didn't go to plan and I got slightly confused on what objects I should have been referencing. I wanted to create a simple attack method that reduced the health of another object just to get the basics of object vs object interaction down. Here's the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
Dog milo = new Dog("Sparky");
Dog ruffles = new Dog("Ruffles");
milo.Attack(ruffles);
Console.ReadLine();
}
}
class Dog
{
public string name { get; set; }
public int health = 100;
public Dog(string theName)
{
name = theName;
public void Attack(Dog theDog)
{
Console.WriteLine("{0} attacks {1}.", this.name, theDog);
LoseHealth(theDog);
}
public void LoseHealth()
{
Console.WriteLine("{0} loses health!", theDog);
theDog -= 5;
}
}
}
}
The code doesn't work at all. Any idea on what I did wrong? Thanks for any help.
The code of the dog class is a bit messed up.
The Attack and LoseHealth methods are in the constructor.
Instead of referring to the health and name you only refer to theDog.
Have a look at this
class Dog
{
public string name { get; set; }
public int health = 100;
public Dog(string theName)
{
name = theName;
}
public void Attack(Dog theDog)
{
Console.WriteLine("{0} attacks {1}.", this.name, theDog.name);
LoseHealth(theDog);
}
public void LoseHealth(Dog theDog)
{
Console.WriteLine("{0} loses health!", theDog.name);
theDog.health -= 5;
}
}
Extra OO tip:
It would make more sense to change the attack and LoseHealth methods like this:
public void Attack(Dog theDog)
{
Console.WriteLine("{0} attacks {1}.", this.name, theDog.name);
theDog.LoseHealth(5);
}
public void LoseHealth(int damage)
{
Console.WriteLine("{0} loses health!", name);
this.health -= damage;
}
You did theDog -= -5. But theDog isn't a number. You need to reference the health of the dog. You also need to pass theDog into the LoseHealth() function. Change it to this:
theDog.health -= 5;
This uses dot notation to access the health of theDog.
But also, your functions are nested in the constructor. Move Attack() and LoseHealth() so they're in the class, not in the constructor body. You should end up with something like this:
class Dog
{
public string name { get; set; }
public int health = 100;
public Dog(string theName)
{
name = theName;
}
public void Attack(Dog theDog)
{
Console.WriteLine("{0} attacks {1}.", this.name, theDog);
LoseHealth(theDog);
}
public void LoseHealth(Dog theDog)
{
Console.WriteLine("{0} loses health!", theDog);
theDog.health -= 5;
}
}
By the way, never just say "my code doesn't work". Explain how it doesn't work. Include relevant exception messages if there are any.

Using a Class with a Form

I am getting an error on lines 44 and 50.
It says:
No overload for method 'GetCarData' takes 1 arguments
Alright, so my task is to create an application that displays 3 main features: year, make, and speed of a car. The year and make are inputted with textboxes and the speed starts at 0.
There is an accelerate button which is supposed to add 5 to the speed every time it is pressed and a brake button which decreases the speed by 5 every time it is pressed.
I am having trouble using the class and form together to display the results. I need to display in a messagebox the make, year, and speed. I have been sitting here for hours and I am getting nowhere.
Any and all help is much appreciated. I have never worked with classes before.
Here is the form:
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 Car_Class_BBrantley
{
public partial class Form1 : Form
{
private Car myCar;
public Form1()
{
myCar = new Car();
InitializeComponent();
}
private void GetCarData()
{
try {
myCar.Make = txtMake.Text;
myCar.Year = int.Parse(txtModel.Text);
myCar.Speed = 0;
}
catch (Exception ex)
{
MessageBox.Show(string.Concat("Must enter a valid make and year model for the car. ", ex.Message, "\r\n", ex.StackTrace));
}
}
private void btnAcc_Click(object sender, EventArgs e)
{
GetCarData();
myCar.AccSpeed(5);
MessageBox.Show(" Your car is a " + myCar.Year + myCar.Make + " and it is traveling " + myCar.Speed + " mph. ");
}
private void btnBrake_Click(object sender, EventArgs e)
{
GetCarData();
myCar.DecSpeed(5);
MessageBox.Show(" Your car is a " + myCar.Year + myCar.Make + " and it is traveling " + myCar.Speed + " mph. ");
}
}
}
If you would like to see the class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Car_Class_BBrantley
{
class Car
{
private int year;
private string make;
private int speed;
public Car()
{
this.year = 1994;
this.make = "Ford";
this.speed = 0;
}
public Car(string make, int year, int speed)
{
this.year = year;
this.make = make;
this.speed = speed;
}
public string Make
{
get { return make; }
set { make = value; }
}
public int Year
{
get { return Year; }
set { Year = value; }
}
public int Speed
{
get { return speed; }
set { speed = value; }
}
public void AccSpeed(int speedIncrement)
{
//Add check for speed limit ranges
Speed += speedIncrement;
}
public void DecSpeed(int speedDecrement)
{
//Add check for speed limit ranges
Speed -= speedDecrement;
}
}
}
If the error says
No overload for method 'GetCarData' takes 1 arguments
then look at the calls you make to GetCarData and check that they don't try to pass a parameter (argument) to it. It's declared as
private void GetCarData()
which is good, and the two calls (lines 44 and 50) are consistent with that:
GetCarData();
so make sure that the code on your computer matches what's here, save it, and re-compile.

A Car Class with Speed [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
EDIT: I am getting a new error after having added the () to the Car instantiation.
It says:
'Car_Class_BBrantley.Form1.myCar()' must declare a body because it is not marked abstract, extern, or partial
Alright, so my task is to create an application that displays 3 main features: year, make, and speed of a car. The year and make are inputted with textboxes and the speed starts at 0.
There is an accelerate button which is supposed to add 5 to the speed every time it is pressed and a brake button which decreases the speed by 5 every time it is pressed.
I am having trouble using the class and form together to display the results. I need to display in a messagebox the make, year, and speed. I have been sitting here for hours and I am getting nowhere. I am getting the errors
speed does not exist in current context
and
car does not exist in current context
under my buttons. I am unsure of how I should go about fixing this.
Any and all help is much appreciated. I'm sorry if this is a mess. I have never worked with classes before.
Here is the form:
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 Car_Class_BBrantley
{
public partial class Form1 : Form
{
private Car myCar;
public Form1()
{
myCar = new Car;
InitializeComponent();
}
private void GetCarData(Car car)
{
try {
myCar.Make = txtMake.Text;
myCar.Year = int.Parse(txtModel.Text);
myCar.Speed = 0;
}
catch (Exception ex)
{
MessageBox.Show(string.Concat("Must enter a valid make and year model for the car. ", ex.Message, "\r\n", ex.StackTrace));
}
}
private void btnAcc_Click(object sender, EventArgs e)
{
GetCarData();
myCar.AccSpeed(5);
MessageBox.Show(" Your car is a " + myCar.Year + myCar.Make + " and it is traveling " + myCar.Speed + " mph. ");
}
private void btnBrake_Click(object sender, EventArgs e)
{
GetCarData();
myCar.DecSpeed(5);
MessageBox.Show(" Your car is a " + myCar.Year + myCar.Make + " and it is traveling " + myCar.Speed + " mph. ");
}
}
}
If you would like to see the class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Car_Class_BBrantley
{
class Car
{
private int year;
private string make;
private int speed;
public Car()
{
this.year = 1994;
this.make = "Ford";
this.speed = 0;
}
public Car(string make, int year, int speed)
{
this.year = year;
this.make = make;
this.speed = speed;
}
public string Make
{
get { return make; }
set { make = value; }
}
public int Year
{
get { return Year; }
set { Year = value; }
}
public int Speed
{
get { return speed; }
set { speed = value; }
}
public void AccSpeed(int speedIncrement)
{
//Add check for speed limit ranges
Speed += speedIncrement;
}
public void DecSpeed(int speedDecrement)
{
//Add check for speed limit ranges
Speed -= speedDecrement;
}
}
}
You're instantiating your Car class incorrectly:
myCar = new Car; // wrong
myCar = new Car();
You're not passing your Car instance to the GetCarData() method even though it expects it:
GetCarData(); // wrong
GetCarData(myCar);
(You're not actually using the instance of Car that you're passing to the method... either remove the parameter from the method, or reference it in your code.)
1-You are not using parentheses in the Car constructor:
myCar = new Car;
should be
myCar = new Car();
2-You declared GetCarData to expect a parameter but it's not using it and when you call it you are not passing it.
Change
private void GetCarData(Car car)
To
private void GetCarData()
Use parentheses within your class name to create an instance of the class:
myCar = new Car();
And change your method definition to:
private void GetCarData()
The method expecting a parameter of type Car, but you are calling it without providing any parameter.As far as I can see you are not using the parameter in the method so you can just remove it.Otherwise you have to pass a Car instance to your method.

Creating a Car Class that Incorporates Speed, Model, and Make

I am getting a new error after having added the () to the Car instantiation.
It says:
'Car_Class_BBrantley.Form1.myCar()' must declare a body because it is not marked abstract, extern, or partial
The error is thrown on line 14.
Alright, so my task is to create an application that displays 3 main features: year, make, and speed of a car. The year and make are inputted with textboxes and the speed starts at 0.
There is an accelerate button which is supposed to add 5 to the speed every time it is pressed and a brake button which decreases the speed by 5 every time it is pressed.
I am having trouble using the class and form together to display the results. I need to display in a messagebox the make, year, and speed. I have been sitting here for hours and I am getting nowhere.
Any and all help is much appreciated. I'm sorry if this is a mess. I have never worked with classes before.
Here is the form:
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 Car_Class_BBrantley
{
public partial class Form1 : Form
{
private Car myCar();
public Form1()
{
myCar = new Car();
InitializeComponent();
}
private void GetCarData(Car car)
{
try {
myCar.Make = txtMake.Text;
myCar.Year = int.Parse(txtModel.Text);
myCar.Speed = 0;
}
catch (Exception ex)
{
MessageBox.Show(string.Concat("Must enter a valid make and year model for the car. ", ex.Message, "\r\n", ex.StackTrace));
}
}
private void btnAcc_Click(object sender, EventArgs e)
{
GetCarData();
myCar.AccSpeed(5);
MessageBox.Show(" Your car is a " + myCar.Year + myCar.Make + " and it is traveling " + myCar.Speed + " mph. ");
}
private void btnBrake_Click(object sender, EventArgs e)
{
GetCarData();
myCar.DecSpeed(5);
MessageBox.Show(" Your car is a " + myCar.Year + myCar.Make + " and it is traveling " + myCar.Speed + " mph. ");
}
}
}
If you would like to see the class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Car_Class_BBrantley
{
class Car
{
private int year;
private string make;
private int speed;
public Car()
{
this.year = 1994;
this.make = "Ford";
this.speed = 0;
}
public Car(string make, int year, int speed)
{
this.year = year;
this.make = make;
this.speed = speed;
}
public string Make
{
get { return make; }
set { make = value; }
}
public int Year
{
get { return Year; }
set { Year = value; }
}
public int Speed
{
get { return speed; }
set { speed = value; }
}
public void AccSpeed(int speedIncrement)
{
//Add check for speed limit ranges
Speed += speedIncrement;
}
public void DecSpeed(int speedDecrement)
{
//Add check for speed limit ranges
Speed -= speedDecrement;
}
}
}
Change
private Car myCar();
to
private Car myCar;
and
private void GetCarData(Car car)
to
private void GetCarData()
change
myCar = new Car;
to myCar = new Car();

OOP C# - Design pattern for MMO mechanics simulator

I've been working on a simulator for FFXIV;
I keep getting really close to finishing, then I get walled into an object access issue that doesn't let me access the stats of the main player. My project can be found at: https://github.com/eein/chocobro
There's plenty of things i can optimize, I know. :P
Basically i'm kind of brute-force winging it to have objects gain access to the objects they need, but i'm looking for the right way to do things.
I'm going to start rewriting it so don't clutch too hard to the example code but its there to see the issue i'm having. :(
Ideally in the next attempt, this is what i'd like to do:
Start with a player class that contains all of the informatin about the player object (in the future, i'd like to create multiples for full group simulation).
Something like:
int main(){
Player p = new Player();
public void setJob()
{
if (job == "bard"){ Player p = new Bard(); }
if (job == "warrior"){ Player p = new Warrior(); }
}
public class Player
{
private string name {get;set;}
private string job {get;set;}
private string STR;
private string DEX;
private string VIT;
//etc..
public virtual void rotation()
{
}
}
//I want to make the program a bit modular for jobs (roles/classes)
//So..
public class Bard : Player
{
public override void rotation()
{
heavyshot.execute();
//etc.
}
Ability heavyshot = new Heavyshot();
public class Heavyshot : Ability
{
public Heavyshot()
{
name = "Heavy Shot";
potency = 150;
dotPotency = 0;
recastTime = 2.5;
TPcost = 60;
animationDelay = 0.8;
abilityType = "Weaponskill";
castTime = 0.0;
duration = 0.0;
}
public override void impact()
{
//add heavier shot buff activation here
base.impact();
}
}
}
public class Ability{
public int cooldown;
public int cost;
public virtual void impact()
{
public virtual void impact()
{
//Deal some damage.
// !! - the key problem is here, i want to initiate a roll to compare to the players CRIT rating versus the roll to determine the bonus damage. But I can't access the initiated players crit from here. The rating may change depending on abilities used so I can't create a new object. I know i need an object reference but I can't figure it out...
log(time.ToString("F2") + " - " + name +
" Deals " + potency +
" Potency Damage. Next ability at: " + nextability);
}
}
I'm probably not being too clear, but basically I want to be able to access the player's crit from ability, and i'm assuming ability can't be set up this way in order for it to work. Does anyone have a good idea what kind of design pattern I should be using so that the virtual functions in ability can access the parent classes players stats?
Ideally, I want the bard class to contain all of the abilities and stat updates pertaining to the bard job, once bard inherits player and the object is changed to reference the Bard object, how do I make it so abilities created by the Ability class dont need an object reference to the parent at the time of creation when accessing that function.
I'm confusing myself, but many thanks to whoever understands my gibberish and can help!
One option is to pass the crit to the Abillity's constructor.
Another option, if an Ability is always connected to the player.
Have the crit property public with private set:
public class Player
{
private double crit { get; private set;}
...
}
Then pass the Player to the Ability's constructor and hold it there.
Note however that this will increase the coupling.
This could be done like this:
public class Ability
{
protected Player _player;
public Ability(Player player)
{
_player = player;
}
}
you would want to change the Headshot class deriving from Ability as well
public class Headshot : Ability
{
public Headshot(Player player) : base(player)
{
...
}
}
Instead of executing abilities rotation directly, save the abilities in a list. This way, you can have setup method in Player, that injects the player into all abilities in rotation. Adding conditions and some kind of "abilityused", that negates next ability is actually one more reason to express the rotation in some kind of list. So you don't have to duplicate the "abilityused" check everywhere, but have it in one place. Something like this:
public class Player
{
private string name {get;set;}
private string job {get;set;}
private string STR;
private string DEX;
private string VIT;
//etc..
public struct RotationAbility
{
public RotationAbility(Func<bool> cond, Ability ability)
{
this.cond = cond;
this.ability = ability;
}
public Func<bool> cond;
public Ability ability;
}
private List<RotationAbility> rotation = new List<RotationAbility>();
public void execute()
{
foreach (var ab in rotation)
{
if (ab.cond())
ab.ability.execute();
}
}
public void setUpRotation()
{
setUpRotation(rotation);
foreach (var ab in rotation)
{
ab.ability.Player = this;
}
}
protected virtual void setUpRotation(List<RotationAbility> rotation) { }
}
//I want to make the program a bit modular for jobs (roles/classes)
//So..
public class Bard : Player
{
protected override void setUpRotation(List<RotationAbility> rotation)
{
rotation.Add(new RotationAbility(()=>buff>0, new Heavyshot());
//etc.
}
public class Heavyshot : Ability
{
public Heavyshot()
{
name = "Heavy Shot";
potency = 150;
dotPotency = 0;
recastTime = 2.5;
TPcost = 60;
animationDelay = 0.8;
abilityType = "Weaponskill";
castTime = 0.0;
duration = 0.0;
}
public override void impact()
{
//add heavier shot buff activation here
base.impact();
}
}
}
public class Ability{
public Player Player { get; set; }
public int cooldown;
public int cost;
public virtual void impact()
{
//Deal some damage.
// !! - the key problem is here, i want to initiate a roll to compare to the players CRIT rating versus the roll to determine the bonus damage. But I can't access the initiated players crit from here. The rating may change depending on abilities used so I can't create a new object. I know i need an object reference but I can't figure it out...
log(time.ToString("F2") + " - " + name +
" Deals " + potency +
" Potency Damage. Next ability at: " + nextability);
}
}
}

Categories

Resources