I need to group multiple functions into one function - c++

I need to group multiple if functions into one big function with a custom name.
if (NPC == NPC1)
{
Attack = NPCAttack1;
}
if (NPC == NPC2)
{
Attack = NPCAttack2;
}
if (NPC == NPC3)
{
Attack = NPCAttack3;
}
if (NPC == NPC4)
{
Attack = NPCAttack4;
}
if (NPC == NPC5)
{
Attack = NPCAttack5;
}
if (NPC == NPC6)
{
Attack = NPCAttack6;
}
if (NPC == NPC7)
{
Attack = NPCAttack7;
}
if (NPC == NPC8)
{
Attack = NPCAttack8;
}
if (NPC == NPC9)
{
Attack = NPCAttack9;
}
if (NPC == NPC10)
{
Attack = NPCAttack10;
}
I want all of that to be inside a function called AttackFunction. How do I do that?

First of all, let's replace all of those if statements with a single switch statement:
switch (NPC) {
case NPC1:
Attack = NPCAttack1;
break;
case NPC2:
Attack = NPCAttack2;
break;
case NPC3:
Attack = NPCAttack3;
break;
case NPC4:
Attack = NPCAttack4;
break;
case NPC5:
Attack = NPCAttack5;
break;
case NPC6:
Attack = NPCAttack6;
break;
case NPC7:
Attack = NPCAttack7;
break;
case NPC8:
Attack = NPCAttack8;
break;
case NPC9:
Attack = NPCAttack9;
break;
case NPC10:
Attack = NPCAttack10;
break;
}
Now we can inject this code into a function, which receive the NPC, and return the desired type of attack.
<attack_type> get_attack_type_from_npc(<npc_type> NPC) {
switch (NPC) {
case NPC1:
return NPCAttack1;
case NPC2:
return NPCAttack2;
case NPC3:
return NPCAttack3;
case NPC4:
return NPCAttack4;
case NPC5:
return NPCAttack5;
case NPC6:
return NPCAttack6;
case NPC7:
return NPCAttack7;
case NPC8:
return NPCAttack8;
case NPC9:
return NPCAttack9;
case NPC10:
return NPCAttack10;
}
throw std::runtime_error("No attack type found");
}
in your main:
int main() {
// ... Declare Attack & NPC ... Set NPC ...
Attack = get_attack_type_from_npc(NPC);
}

Related

How to build the simple change maker for a vending machine?

On the menu deposits n,d, q, o,f are indicated which are indication for nickel dime quarter , one dollar and five dollar. I should also indicate "C" as in cancel option when the user hits c. But i couldn't make it work. My program still runs even the user hit c. I am confused on this point?
switch(DepositIndication) {
case 'n': {
PurchasedPrice=PurchasedPrice-0.05;
NumOfNickels=NumOfNickels+1;
}
break;
case 'd': {
PurchasedPrice=PurchasedPrice-0.10;
NumOfdimes=NumOfdimes+1;
}
break;
case 'q': {
PurchasedPrice=PurchasedPrice-0.25;
NumOfquarters=NumOfquarters+1;
}
break;
case 'o': {
PurchasedPrice=PurchasedPrice-1.00;
NumOfOnes=NumOfOnes+1;
}
break;
case 'f': {
PurchasedPrice=PurchasedPrice-5.00;
NumOfFives=NumOfFives+1;
}
break;
}
the condition c is missing and I Put the break into to brackets;
switch (DepositIndication) {
case 'n':
{
PurchasedPrice = PurchasedPrice - 0.05;
NumOfNickels = NumOfNickels + 1;
break;
}
case 'd':
{
PurchasedPrice = PurchasedPrice - 0.10;
NumOfdimes = NumOfdimes + 1;
break;
}
case 'q':
{
PurchasedPrice = PurchasedPrice - 0.25;
NumOfquarters = NumOfquarters + 1;
break;
}
case 'o':
{
PurchasedPrice = PurchasedPrice - 1.00;
NumOfOnes = NumOfOnes + 1;
break;
}
case 'f':
{
PurchasedPrice = PurchasedPrice - 5.00;
NumOfFives = NumOfFives + 1;
break;
}
case 'c':
}
//you can print cancellation messages in here
break;
}
default:
break;
}
I should also indicate "C" as in cancel option when the user hits c
Your current code works fine the only thing you are missing to make that work right now is a default case or a case where you specifically check if the user inputed C.
Example:
switch(DepositIndication) {
// All other cases ...
case 'c': {
// The user canceled the interaction
std::cout << "Interaction was canceled." << std::endl;
break;
}
// Default case to ensure that even,
// if the user hits any other key we still handle his interaction
default {
std::cout << "No fitting interactional behaviour found." << std::endl;
break;
}
}
If you want to ensure that the user can even input big lettered chars and the switch case will still work you can use std::tolower and cast it back to a char.
Make the User-Input lowercase:
// Make DepositIndication lowercase
DepositIndication = std::tolower(DepositIndication, std::locale());

Arduino : A case of switch block the case that are after

I've a switch and a functions 'block the case that are after it' at the 4th case of the switch.
I tried to move the case and apparently it's the 'P_JEU' case that block but I don't understand why.
switch (partie) {
case P_CHOIX_ANIM:
allPlayers.chenillard(250,100);
partie = P_CHOIX;
case P_CHOIX:
temp = allPlayers.checkInterro();
if (temp == 0) break;
if (temp == 1) { //Only 1 press
partie = P_JEU;
DEBUG_PRINTLN("P_CHOIX 1 press");
break;
}
partie = P_CHOIX_ERREUR;
break;
case P_JEU:
// Bug
if (bConfig.isPressed()) {
if (bConfig.getPressDuration()) {
if (bConfig.getPressDuration() <= 2000) {
partie = P_CHOIX_RESET;
} else {
bConfig.reset();
}
}
}
allPlayers.filteredCall(A_CHECK, J_PLAYER);
bool passResponse = allPlayers.Pass();
if (passResponse) { partie = P_JEU_REPONSE; }
break;
case P_CHOIX_RESET:
allPlayers.reset();
bConfig.reset();
partie = P_CHOIX_ANIM;
break;
default:
DEBUG_PRINTLN("Default");
partie = P_CHOIX_RESET;
break;
Thanks
You cant declare variables inside a case:
https://complete-concrete-concise.com/programming/c/keyword-switch-case-default/
Can I declare variables inside an Objective-C switch statement?
bool passResponse = allPlayers.Pass();
is wrong - you have to enclose it:
case P_JEU:
// Bug
if (bConfig.isPressed()) {
if (bConfig.getPressDuration()) {
if (bConfig.getPressDuration() <= 2000) {
partie = P_CHOIX_RESET;
} else {
bConfig.reset();
}
}
}
allPlayers.filteredCall(A_CHECK, J_PLAYER);
{
bool passResponse = allPlayers.Pass();
if (passResponse) { partie = P_JEU_REPONSE; }
}
break;

Declared enum and IF on its elements

I'm working on Snake game. Although I have a little problem. I created enum with possible directions:
enum Direction{
n = 0, // north
e = 1, // east
s = 2, // south
w = 3 // west
};
And then I created a ChangeDirection() function, which basing on previous direction will change it. (For example, if you go to the right/east, you can't switch to left/west):
void ChangeDirection(char key){
switch (key){
case 'w':
if (Direction != 2)
Direction = 0;
break;
case 'd':
if (Direction != 3)
Direction = 1;
break;
case 's':
if (Direction != 0)
Direction = 2;
break;
case 'a':
if (Direction != 1)
Direction = 3;
break;
}
But my ifs clearly don't work; following error occurs:
Expected primary-expression before '!=' token
Anyone could help? How can I rearrange it to work? Why doesn't it work? Thanks!
Direction CurrentDir = e; // somewhere in the code
// ....
//another place in the code, so on..
CurrentDir = s;
//....
void ChangeDirection(char key){
switch (key){
case 'w':
if (CurrentDir != s)
CurrentDir = n;
break;
case 'd':
if (CurrentDir != w)
CurrentDir = e;
break;
// so on ..
}

String was not recognized as a valid DateTime in Android

I am developing an Android client for Microsoft Dynamics NAV. I am using ksoap2 for making communication with NAV webservices. I used MarshalDate class to serialize date. When I pass Date to webservice I am getting an error like "String was not recognized as a valid DateTime."
MarshalDate.java
public class MarshalDate implements Marshal {
public static Class DATE_CLASS = new Date().getClass();
public Object readInstance(XmlPullParser parser, String namespace, String name, PropertyInfo expected) throws IOException, XmlPullParserException {
return IsoDate.stringToDate(parser.nextText(), IsoDate.DATE_TIME);
}
public void register(SoapSerializationEnvelope cm) {
cm.addMapping(cm.xsd, "dateTime", Date.class, this); }
public void writeInstance(XmlSerializer writer, Object obj) throws IOException {
writer.text(IsoDate.dateToString((Date) obj, IsoDate.DATE_TIME)); } }
My object for salesordercard,
SalesOrderCard.java
public class SalesOrderCard implements KvmSerializable
{
String Key;
String No;
String Sell_to_Customer_No;
Sales_Order_Line_List Salesorderlinelist;
String ShopNo;
Date OrderDate;
double Received_Amount;
boolean Cheque;
public SalesOrderCard(){}
public SalesOrderCard(String key,String no,String selltocustno,Sales_Order_Line_List salesorderline,String shopno,Date orderdate ,double received_Amount,boolean cheque) {
Key = key;
No = no;
Sell_to_Customer_No = selltocustno;
Salesorderlinelist=salesorderline;
ShopNo=shopno;
OrderDate=orderdate;
received_Amount=Received_Amount;
Cheque=cheque;
}
public Object getProperty(int arg0) {
switch(arg0)
{
case 0:
return Key;
case 1:
return No;
case 2:
return Sell_to_Customer_No;
case 3:
return Salesorderlinelist;
case 4:
return ShopNo;
case 5:
return Received_Amount;
case 6:
return Cheque;
case 7:
return OrderDate;
}
return null;
}
public int getPropertyCount() {
return 8;
}
public void getPropertyInfo(int index, Hashtable arg1, PropertyInfo info) {
switch(index)
{
case 0:
info.type = PropertyInfo.INTEGER_CLASS;
info.name = "Key";
break;
case 1:
info.type = PropertyInfo.INTEGER_CLASS;
info.name = "No";
break;
case 2:
info.type = PropertyInfo.INTEGER_CLASS;
info.name = "Sell_to_Customer_No";
break;
case 3:
info.type = Sales_Order_Line_List.class;
info.name = "SalesLines";
break;
case 4:
info.type = PropertyInfo.INTEGER_CLASS;
info.name = "Shop_No";
break;
case 5:
info.type = PropertyInfo.INTEGER_CLASS;
info.name = "Received_Amount";
break;
case 6:
info.type = PropertyInfo.INTEGER_CLASS;
info.name = "Cheque";
break;
case 7:
info.type = MarshalDate2.DATE_CLASS;
info.name = "Order_Date";
break;
default:break;
}
}
public void setProperty(int index, Object value) {
switch(index)
{
case 0:
Key = value.toString();
break;
case 1:
No = value.toString();
break;
case 2:
Sell_to_Customer_No = value.toString();
break;
case 3:
Salesorderlinelist = (Sales_Order_Line_List)value;
break;
case 4:
ShopNo = value.toString();
break;
case 5:
Received_Amount = Double.parseDouble(value.toString());
break;
case 6:
Cheque = Boolean.parseBoolean(value.toString());
break;
case 7:
OrderDate=(Date)value;
break;
default:
break;
}
}
}
And I am passing date like,
String DateString="22-05-2014 19:32:52";
SimpleDateFormat format=new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
d=(Date)format.parse(DateString);
SalesOrderCard cr=new SalesOrderCard();
cr.OrderDate=d;
PropertyInfo custProp = new PropertyInfo();
custProp.setName("SalesOrderCard");
custProp.setValue(cr);
custProp.setType(SalesOrderCard.class);
request.addProperty(custProp);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
MarshalDouble md = new MarshalDouble();
md.register(envelope);
MarshalDate mdate=new MarshalDate();
mdate.register(envelope);
Assuming d is a Date this code looks correct
String DateString="22-05-2014 19:32:52";
SimpleDateFormat format=new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
d=(Date)format.parse(DateString);
I suspect this line may be the problem
writer.text(IsoDate.dateToString((Date) obj, IsoDate.DATE_TIME));
If you know the format writer.text expects then I would try using SimpleDateFormat to create the string for you instead:
String dateString = format.format((Date)obj);

c++ Recursive Tree building with pointers and a state machine

I have a simple state machine (entered below). My major problem is that I am trying to make a recursive call to the function that is my state machine. What I do upon entry of the function is create a new node for my tree and then push that through. When I do a recursive call, I create a new node over and over. This can work, but when adding children to a parent I'm a little confused. Can someone help look over this and help me take my tree node (parent I'm assuming) and attach a child to it?
TreeNodeClass* ProcessTree(TokenT token, vector <list <stateAssoc> >& vecTree, int depth)
{
int state = 1; //Assume this is a new record.
bool noState = false;
bool update = true;
int dex = 0;
string root, value, data, tag;
TreeNodeClass* treeNode;
treeNode = new TreeNodeClass; //Assume a new node per state machine visit.
//Need 11 to break out of loop as well.
while(state != 10)
{
switch(state)
{
case 1: dex = 1;
break;
case 2: dex = 6;
root = yylval;
break;
case 3: dex = 7;
break;
case 4: dex = 3;
value = yylval;
treeNode->CreateAttrib(root, value);
break;
case 5: dex = 2;
break;
case 6: dex = 4;
data = yylval;
break;
case 7: //Really Don't do anything. Set the tag creation at 8...
dex = 8;
tag = yylval;
if(data != "" and data != "authors")
treeNode->CreateTag(data, tag);
break;
case 8: {
//New TreeNode already grabbed.
//TreeNodeClass* childNode = new TreeNodeClass;
childNode = ProcessTree(token, vecTree, depth+1);
childNode->SetHeight(depth);
treeNode->AddChildren(childNode);
}
token = TokenT(yylex()); //Get a new token to process.
dex = 5;
break;
case 9: dex = 9;
update = false;
if(yylval != treeNode->ReturnTag())
{
state = 11;
}
break;
case 10: update = false;
treeNode->SetHeight(1);
break;
default: cout << "Error " << endl;
cout << state << endl;
cin.get();
break;
}
if(!noState)
state = FindMatch(vecTree[dex], token);
if(update)
token = TokenT(yylex());
else
update = true;
}
return treeNode;
}
You may assume that the dex is simply an index to an array of lists that will return a correct state or 11 (error). Also you may assume that this funciton has atleast been called once on an input file and has started parsing. Thank you for your help.
Looking at your code, you have
int state = 1;
//Code
while(state != 10) {
switch(state) {
case:1 dex = 1; break; //Only case you run
//more cases
case 8: { //never enter here
//New TreeNode already grabbed.
//TreeNodeClass* childNode = new TreeNodeClass;
childNode = ProcessTree(token, vecTree, depth+1);
childNode->SetHeight(depth);
treeNode->AddChildren(childNode); //should work if assuming function is correct
}
//stuff
break;
default: break;//blah
}
}
//blah
return treeNode;
I see no other reason than the fact state is always equal to 1 that your code at case 8 would fail. This is assuming treeNodeClass::AddChildren(TreeNodeClass*) has been properly implemented. WIthout that code, I can assume it's not your problem. Is there some method in which state wouldn't be 1 in the switch?