473,882 Members | 1,546 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Logic question...

I am writing a game and I am having a challenge with my combat
function. All I want to do is find out how to group pieces that are in
the same space. There are two sides and all the units that are in the
same space fight. I want to add up the attack factors and defending
factors in the same space then figure out the odds so I can roll
against an odds table. Basically each piece holds its own x and y loc.
Here is what I have right now:

void fight(vector<un it>& at, vector<unit>& dt,
board * b , terrain * trn ){

vector<fightcla ssfighting;

/* adds attacking units to the fightclass vector if units are in the
same space they are to grouped in the same fight class elemet of
the
vector. */

for(int atu = 0; atu != at.size(); atu++){
if(fighting.siz e() == 0){
fightclass ft;
ft.addAu(at[atu]);
fighting.push_b ack(ft);
} else {
for(int lp = 0; lp != fighting.size() ; lp++){
if(at[atu].getXloc() != fighting[lp].getX() &&
at[atu].getYloc() != fighting[lp].getY()){
fightclass ft;
ft.addAu(at[atu]);
fighting.push_b ack(ft);
} else {
fighting[lp].addAu(at[atu]);
}
}
}
}
/* Adds defending units to the fightclass array. If x and y locs are
the same as attacking locations (are in the same space) they are
added to array for combat */

for(int dtu = 0; dtu != dt.size(); dtu++){
for(int lp = 0; lp != fighting.size() ; lp++){
if(dt[dtu].getXloc() == fighting[lp].getX() &&
dt[dtu].getYloc() == fighting[lp].getY()){
fighting[lp].addDu(dt[dtu]);
}
}
}

// Combat routine

for(int lp = 0; lp != fighting.size() ; lp++){ //handles combat
if(fighting[lp].canfight()){
int df = b->GetSpace(fight ing[lp].getX(), fighting[lp].getY());
float odds =
fighting[lp].getAtk()/fighting[lp].getDef();
//gets the defense bonus for the terrain in the space where
//combat takes place
int roll = rand() - trn[df].defend();
//get the die roll modified for terrain
odds = fighting[lp].getAtk() / fighting[lp].getDef();
//gets the attack to defence ratio.
if(odds < .5){
MessageBox(NULL , "Fighting! 1:3", "Info!", MB_OK);
return;
}
if(odds < 1){
MessageBox(NULL , "Fighting! 1:2", "Info!", MB_OK);
return;
}
if(odds < 2){
MessageBox(NULL , "Fighting! 1:1", "Info!", MB_OK);
return;
}
if(odds < 3){
MessageBox(NULL , "Fighting! 2:1", "Info!", MB_OK);
return;
}
if(odds < 4){
MessageBox(NULL , "Fighting! 3:1", "Info!", MB_OK);
return;
}
if(odds < 5){
MessageBox(NULL , "Fighting! 4:1", "Info!", MB_OK);
return;
}
if(odds < 6){
MessageBox(NULL , "Fighting! 5:1", "Info!", MB_OK);
return;
}

}
}
for(int lp = 0; lp != fighting.size() ; lp++){
fighting[lp].done();
}
fighting.clear( );
}

class fightclass{
/* Fightclass holds two arrays of units. The two arrays represent
units
in the same space elgible for combat. Array at represents the
attacking
forces and dt represents the defending units */
int xl;
int yl;

bool sides2; /* indicates if there are units in both attack and
defend
if there are units in both attack and defend then
combat
is to take place between the opposing sides. */

vector<unit>at; //attack units
vector<unit>dt; //defending units

public:
fightclass();
void addAu(unit au); //adds an addacking unit
void addDu(unit du); //adds a defending unit
int getX(){return xl;} //return the x coord
int getY(){return yl;} //returns the y coord
float getAtk(); //returns the total attack factors for one space
float getDef(); //returns the total defending factors for one space
bool canfight(); //if there are both attacking and defending units
void done(); //clears vectores after the turn

};

fightclass::fig htclass(){
xl = 0;
yl = 0;
}

void fightclass::add Au(unit u){
at.push_back(u) ;
xl = u.getXloc();
yl = u.getYloc();

}

void fightclass::add Du(unit u){

dt.push_back(u) ;

}

bool fightclass::can fight(){
if(at.size() && dt.size()){
return true;
}else {return false;}
}

float fightclass::get Atk(){
float total;
for(int lp = 0; lp != at.size(); lp++){
total +=at[lp].getAttack();
}
return total;
}

I know the logic is not the best but it is the best I can do. This is
tricky and I am pretty confused. I would like to find some way of
making the logic steps easier. There may be some simple error that I
overlooked or it can be totally screwed up.

Sep 4 '06
73 4326

Miss Elaine Eos wrote:
In article <11************ *********@d34g2 000cwd.googlegr oups.com>,
"JoeC" <en*****@yahoo. comwrote:
If I read the previous poster correctly (and I concur with this
sentiment), it appears from your questions that you are missing some
training in fundamental concepts that are difficult to learn in C++
without a strong C background.
[...]
My history of learning computers consited [...]

Btw, I didn't mean my previous to be in the slightest bit insulting.
I'm sure you're a fine programmer and a very smart person. All I was
trying to say is that your questions seem to indicate that you're
missing some fundamentals that are easier to grasp in C, which may be
why folks suggested you back up & try going fwd from there.
I do read the basics of programming and I have devloped my techiques.
I am always trying to improve those techniques. I am self taught and
have little contact with other programmers. I ask what ever question
is on my mine and I can't get a good answer in a book.
>
It's a little like if I started asking all sorts of compiler questions,
pretty soon it'd be obvious that I'd never learned whatever it is they
teach folks in compiler courses. Hence, my "I'm 2/3 of the way through
writing my compiler, but running into foo-related problems" might be met
with "you need to back up and start way back near the beginning with
your (oh, I don't know...) tokenizer (let's say.)
I couldn't immagine wiriting a compiler although I would like to do
some basic assembly programming some day just as I have done some
research into Latin. I am starting to write larger programs and I have
choices on how I can design the parts of that program and often wonder
which ways are the best. I just got my map game to run correctly. In
the proscess of writing that game as I go back there are better ways I
could have written some parts of that program. Going back to make
changes would result in far more effort trying to make the rest of the
program accept those changes.
>
This doesn't mean that I'm stupid or a bad programmer, only that my
questions would indicate to the experts that I was a bit lost in
compiler-land.
I have doubts about my abilities despite what I create. I know I have
it in my to do better and write even better programs even at my current
skill. I also look for ways to write small programs to learn new ways
of doing things and new skills. I often avoid some directions because
of some lack of knowlege. I always try to know what I want to do then
how to do it.

I am planning a complete re-write of my game I just don't think I have
learned enough lessons to make it worh wile. Some of the ideas I have
is to have units dynamic and have several kinds. Load the unit data
from a file, conquer cities and have a production value and create new
units in play. A better combat system and have ranged attacks. Still
my thoughts are too disorginized to continue. I am taking a break and
re-writing some of the libraries with the ideas and knolwege I have. I
so far have created a coor struct and a new color object. Still Many
of the questions I have are should a unit be a graphic or have a
graphic should the color be part of the unit or the graphic. What if I
want to create one unit or army from several units. Kind of a tree.

Yes, I am dangerous and I am facinated by programming especially by
C++.
>
See what I mean?

Now, maybe we've read you correctly, maybe not -- but that's what it
looks like, from the kinds of things you're asking, and that's why we're
recommending the things we do.

"No offense", and all that :)
Don't worry. I am currenly at a loss for direction. I can study but I
am not sure what to study next. What topic or better knowege is the
best use of my time. Of course you don't know that, it is up to me. I
gain so much from open ended discussions. A question I often ask
myself is not what to think but how to think as a programmer.

A big fustration is that I have the C++ programming language. I often
study AC++ a priceless resource. Still there is only so much
informations there. C++ PL is often dificult to learn anything from.
I often get confuced because there is just as much what not to do as
what is correct.

Right now I am writing little pointer programs. When I get lost in the
big things, I go to small programs and focus on improving my skills
with specific syntax.

Sep 26 '06 #71
LR wrote:
Perhaps you should look into std::map, or maybe std::multimap.

Just as a thought experiment, not the way to write your code, think
about something like std::map<Locati on, std::set<UnitIn dicies.
Let's consider that simple things are more expressive and easier to
understand than complex things.

struct Entity
{
int x, y;
};
typedef std::list<Entit y*EntityList;

EntityList g_theEntities;

EntityList GetObjectsAt(in t x, int y)
{
EntityList list;
for (EntityList::co nst_iterator it = g_theEntities.b egin();
it != g_theEntities.e nd(); ++it)
{
Entity* e = *it;
if ((e->x == x) && (e->y == y))
{
list.append(e);
}
}

return list;
}

Then no 'manager' or other "god object" needs to maintain any info; the
entities can take care of knowing where they are themselves.

-tom!

--
Sep 26 '06 #72
LR
Tom Plunket wrote:
LR wrote:

>>Perhaps you should look into std::map, or maybe std::multimap.

Just as a thought experiment, not the way to write your code, think
about something like std::map<Locati on, std::set<UnitIn dicies.


Let's consider that simple things are more expressive and easier to
understand than complex things.
I'm not entirely sure that I agree with that. For example, "expressive "
is a fairly complex word. What would it take to express your thought if
you didn't have that word available.

By the same token, we might be better served by adding some operations
that work on an Entity. Or maybe, if an Entity has a Location, then we
might be better off with something like this.

(None of this code was compiled or tested, so caveats apply.)

class Location {
int x_, y_;
public:
Location(const int x, const int y) : x_(x), y_(y) {}
// and other members as appropriate
};

and I'm not showing the implementation of these, pretty obvious.

bool operator<(const Location &l1, const Location &l2) { ... }
bool operator==(cons t Location &l1, const Location &l2) { ... }
So, if I understand your intent correctly, then
struct Entity
{
Location location_;
SomeOtherDataTh atAnEntityHas d_;
};


I do worry about making containers of pointers. Who owns the pointer?
typedef std::list<Entit y*EntityList;
EntityList g_theEntities;

If we make the argument a Location then we're not in any doubt about
what x and y are for, and since we'll probably be using a Location from
another object anyway, it might be easier to call
EntityList x = GetObjectsAt(en itity.location_ );
than
EntityList x = GetObjectsAt(en tity.x,enitity. y);
just my opinion,
EntityList GetObjectsAt(co nst Location &loc)
{
EntityList list;
for (EntityList::co nst_iterator it = g_theEntities.b egin();
it != g_theEntities.e nd(); ++it)
{
Entity *e = *it;
// this seems better to me than comparing the
// x and y things explicitly, because we might
// want to change what a location is and this
// will be a little easier.
// I think that it has the advantages of being
// more _expressive_ and tucking the complexity
// of the code away somewhere else. Plus, we'll
// probably find that we can use it elsewhere.
if(loc == e->location_)
{
list.append(e);
}
}

return list;
}

Then no 'manager' or other "god object" needs to maintain any info; the
entities can take care of knowing where they are themselves.
I guess it depends on how you want to manage the entities and where
they're going to exist during the lifetime of the program.

BTW, one of my concerns about the list of pointers to Entities involves
making a copy of the entire game. Who knows why we'd want to do that.
Maybe to allow the code to try some strategy to beat its opponent. With
something like:
(In this example, an Entity has no Location.)
typedef std::map<Locati on, std::vector<Ent ity Board;
Board a;
doSomething(a);
Board b(a);
if(somethingDes tructiveWorksOu t(b)) {
// we still have our old a.
// although this might be expensive.
}

LR
Sep 26 '06 #73
LR wrote:
By the same token, we might be better served by adding some operations
that work on an Entity. Or maybe, if an Entity has a Location, then we
might be better off with something like this.
Sure, simple doesn't mean operation-free. Indeed, adding to an object's
API may indeed simplify the use of that object.
class Location {
int x_, y_;
public:
Location(const int x, const int y) : x_(x), y_(y) {}
// and other members as appropriate
};

and I'm not showing the implementation of these, pretty obvious.

bool operator<(const Location &l1, const Location &l2) { ... }
bool operator==(cons t Location &l1, const Location &l2) { ... }
So, if I understand your intent correctly, then

struct Entity
{
Location location_;
SomeOtherDataTh atAnEntityHas d_;

};
Yep.
I do worry about making containers of pointers. Who owns the pointer?
typedef std::list<Entit y*EntityList;
It was easy for me to type it in. ;)

I'd say the thing that creates the pointers owns them, which is to say
that the thing that initially populates the "g_theEntit ies" list (which
is the likely place the objects would be created in the first place)
would be responsible for depopulating it.
If we make the argument a Location then we're not in any doubt about
what x and y are for, and since we'll probably be using a Location from
another object anyway, it might be easier to call
EntityList x = GetObjectsAt(en itity.location_ );
than
EntityList x = GetObjectsAt(en tity.x,enitity. y);
just my opinion,
I agree 100%, and would suggest that while this adds lines-of-code, this
makes the code more expressive and easier to understand. "What is this
argument here for? Oh, it's a Location. Done."
// this seems better to me than comparing the
// x and y things explicitly, because we might
// want to change what a location is and this
// will be a little easier.
// I think that it has the advantages of being
// more _expressive_ and tucking the complexity
// of the code away somewhere else. Plus, we'll
// probably find that we can use it elsewhere.
if(loc == e->location_)
I agree.
Then no 'manager' or other "god object" needs to maintain any info; the
entities can take care of knowing where they are themselves.

I guess it depends on how you want to manage the entities and where
they're going to exist during the lifetime of the program.
Either objects can manage themselves (often the simplest solution IMO),
the thing that naturally contains them can manage them, or some third
party (aka "the manager") can manage them.
BTW, one of my concerns about the list of pointers to Entities involves
making a copy of the entire game. Who knows why we'd want to do that.
Maybe to allow the code to try some strategy to beat its opponent. With
something like:
Sure. When you find yourself trying or needing to do that, make the
code do it. Engineering a solution to that before you have a need is
quite possibly a waste of time, and if you keep all of your parts simple
it won't be hard to make the code do different things under the hood to
facilitate such work.

-tom!

--
Sep 27 '06 #74

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

60
7334
by: Fotios | last post by:
Hi guys, I have put together a flexible client-side user agent detector (written in js). I thought that some of you may find it useful. Code is here: http://fotios.cc/software/ua_detect.htm The detector requires javascript 1.0 to work. This translates to netscape 2.0 and IE 3.0 (although maybe IE 2.0 also works with it)
6
1574
by: Ted Singh | last post by:
(I apologize in advance if this is an obvious question, my experience is more with console or client-only apps) I am trying to build an web-based HTML UI, which will work with a web-server on the same machine (i.e., http://localhost/...). However, I do not want the logic source to be visible to the user to prevent customer support problems, intellectual property issues, etc. The requirements strictly call for a web-based UI running...
0
1909
by: Tony Johansson | last post by:
Hello Experts! I reading a book called programming with design pattern revealed by Tomasz Muldner and here I read something that sound strange. "Exception are divided into logic errors and runtime errors. Logic errors represent static errors that can be prevented and detected at compile time. Runtime errors represent dynamic errors that can be detected only at runtime."
2
1511
by: Simon Harvey | last post by:
Hi all, I was wondering how most developers handle the initial startup of their Windows Forms applications? When you make an application in Visual Studio, the IDE places Main in the form that VS makes for you. When I make my applications I sometimes feel uneasy about leaving the startup logic in the Form - it sort of seems the wrong place for it. I'm by no means an expert on such things (which is why I'm writing this post), but it...
3
1530
by: mca | last post by:
Hi everyone, I'm new to asp.net and i have a question about separating the html code from the programming code. i have an unknown numbers of entries in my table. I want to make a hyperlink for every entry in my table. So i query the database and get for example 3 entries back. So in a while loop i can make 3 hyperlinks with response.write(.......) etc.
24
14427
by: cassetti | last post by:
Here's the issue: I have roughly 20 MS excel spreadsheets, each row contains a record. These records were hand entered by people in call centers. The problem is, there can and are duplicate phone numbers, and emails and addresses even person names. I need to sift through all this data (roughly 300,000+ records and use fuzzy logic to break it down, so that i have only unique records.
6
2013
by: Simon Harvey | last post by:
Hi everyone, We have a need to make a Windows Forms (2.0) client application that will be installed on our clients site. The data that the application uses needs to be centrally available to a potentially large number of other sites, which would seem to leave us with our traditional approach, or having a central database server on a dedicated server someplace.
14
3582
by: rabbitrun | last post by:
Hi Everyone, I work for a financial company. I am planning to give a presentation to rest of the development team (15 people) here on moving server side logic to client-side javascript for an internal intranet application rewrite. This approach will definitely stir up hot debate from hardcore server-side Java folks who wants to do UI stuff even on the server!. Since I am pretty much known as the JS or UI Guy of the group, my Boss...
29
2243
by: Brad Pears | last post by:
Here is a simple OO design question... I have a Contract class. The user can either save an existing contract or they start off fresh with a blank contract, fill in the data and then save a "new" contract. I have a method in my contract class called "Save" which is called like this... dim oContract as new Contract
15
2451
by: bruno.desthuilliers | last post by:
On 27 juin, 18:09, "John Salerno" <johnj...@NOSPAMgmail.comwrote: For which definitions of "content" and "logic" ??? The point of mvc is to keep domain logic separated from presentation logic, not to remove logic from presentation (which just couldn't work). Templating systems are for presentation logic. Whether they work by embedding an existing complete programmation language or by providing they're own specialised mini-language (or...
0
9931
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9777
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11108
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10830
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10403
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7956
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
4601
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4198
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3226
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.