I am creating a game similar to Pokemon and right now I'm trying to figure out the best way to handle my battle.
I have created a monster class which when instanced contains a particular monster's name, health, stats, etc. I will have two monsters fighting each other with the player able to select a move (will likely be a class as well with damage, info, and type stats) to attack the opponent with.
Would I be best served to make the Moves class an activity so that I can use methods to attack and calculate damage? Or should I create a battle activity which I send the monsters pertinent stats and have it deal with changing the health and printing out the text explaining what happened? This way, my monster and moves class only holds the information and doesn't use any methods.
From a design perspective, your second thought is more on cue.
The basic idea that you have is that each object (Monster, in this case) will have public functions available to get what moves are available, current stats, etc.
Thus the Battle Activity will expect to have one or more Monster objects per team, rules defined as to what makes the battle win, handle which monster goes first, etc.
Thus if a monster takes damage and we need to save that, you can make a function in the Monster class such as:
public void takeDamage(double damage) {
this.hp -= damage;
//Handle status updates if hp <= 0
//Automatically save the monster's state, to prevent cheating by quitting before battle is over!
this.saveMonsterState();
}
And this would be called from the Battle activity whenever one monster hits another. Hope that helps!
Related
I have a pretty basic knowledge of AS3, so I'm not sure if this is actually possible, or if it is, how to do it. I am in the very starts of coding this project, so I don't actually have much code to show, but would like to figure this issue out before I start writing everything around it.
I am making a game similar to Monopoly, so I will speak in terms of that. Basically, I want 4 Players all with variable integers that reflect how much money they have. In my game, I want to be able to click on a player, click "Buy Property", and then click the property they're buying, which would be a button (btnProperty1).
Let's say Property 1 also has a purchase value, which could be "valueProperty1", and let's say the value is 100. My players will start with 1000, so I want the buying of this property to deduct 100 from the active player money. The player money int could be "moneyPlayer1, moneyPlayer2, etc.". So, I would be able to click btnPlayer1, btnBuyProperty, btnProperty1, and then moneyPlayer1 would go from 1000 to 900. To determine the active player, I had the idea of making an "activePlayer" int, and just setting it to 1, 2, 3 or 4 based on which btnPlayer I click.
In a shotty way of putting it, I could put in the btnProperty1 if (activePlayer == 1){moneyPlayer1 -= valueProperty1} and write four statements, one for each player. HOWEVER, I would like to subvert doing that by writing a function that looks like this:
moneyPlayer[activePlayer] -= valueProperty1 (if the activePlayer int is equal to 1, then it would fill in 1 to the end of moneyPlayer, therefor targeting moneyPlayer1)
In theory, it would then deduct money from whichever player is active. IF THIS IS POSSIBLE, I have no idea how to write it.
Additionally, I would like to do something similar if a subsequent player lands on an owned property. So in the same vein, I would want something that looks like this:
moneyPlayer[activePlayer] -= rentProperty1 (the rent value is deducted from the active player)
moneyPlayer[paidPlayer] += rentProperty1 (the rent value is added to the paid player)
I can figure out ways to make the active player and paid player functions work, I just need to know if I can put these variables INSIDE of other variables, so I don't have to write 18,748 if statements.
Lastly, I would love to be able to enter a player name into an input text field, then have it appear in a dynamic text field. I tried looking around and couldn't find an answer... So bonus points for this one :)
Any help would be GREATLY appreciated!! Thank you!
To answer your question, YES you can put variables "inside" another variable, this is called "classes" in AS3, and is a required thing to use whenever you plan something big. Say you want a Player class, then you can do like this:
public class Player {
private var _money:int;
... // whatever else a player has
public function get money:int { return _money;} // a property
// such functions are the way to make someone not directly steal the player's money,
// but are a way to view the money of a player
// rest of property functions goes here
public function Player() // a constructor, required
{
_money=1000; // starting money
... //etc, place default values everywhere
}
public function earnMoney(amount:int) // makes the player able to earn money
{
_money += amount; // negative money may be accepted, learn to check parameters!
}
// everything else goes here
}
Then you add there more functions that can change a player's state, say a function buy(aProperty):Boolean that would return true if the player did buy that property, and will also change the variables "inside" both the property involved and the player (this, or just call variables as if they are local).
You can do way more with classes, please read about object-oriented programming, there's a lot of basics that can help you draw your game's architecture. Learn about "encapsulation" first, to not accidentally break your objects. An example was shown above.
I am trying to implement a series of notifications based on radio button options the user selects. The notifications date and time will set depending on both radio button options and the user selected date.
for example the user selects Option 1, 2 and 3 along with Jan 1st 2017 and 12 notifications are set every couple of days/weeks depending on said options.
Before I get too far into this, am I just looking at a complex if then statement to set these notifications or am i missing another solution?
When your if-else statements get too long you might be needing a switch statement instead. You said there are twelve notification options so a switch could do this just fine.
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
Remember to separate each option in a modular fashion using different classes, or methods so that you just have to call each block of code.
A lot of switcing or if/else can also be a symptom of you trying to express intrinsically polymorphic code. You are essentially replicating the vtable the compiler would do for you. Following separating business logic from view (rendering) logic -- ie some form of MVC -- you could associate a subclass with each radio button to which the button delegates the logic when it is pressed (btw you might not necessarily need separate subclasses). The controller of each radio button may have a reference to some other object which stores the final frequency of days/hours/minutes, etc for each to call the alarm. So as each radio button is pressed, it delegates to its controller which in turn interprets the value of the radio button and in turn calls into the alarm controller, incrementing / decrementing some value using some appropriate API.
I know it might sound like over-engineering but it is quite simple to set up and it is likely that you will minimally need that alarm controller for other details (which also makes it a lot easier to test; you definitely do not want to shove business logic in your views (activities) as it makes testing a nightmare). So if you wish to simplify this, you could forego each button's individual controller and instead have each button directly invoke the alarm controller API if you prefer to update it.
I will start this by saying that on iOS this algorithm takes, on average, <2 seconds to complete and given a simpler, more specific input that is the same between how I test it on iOS vs. Android it takes 0.09 seconds and 2.5 seconds respectively, and the Android version simply quits on me, no idea if that would be significantly longer. (The test data gives the sorting algorithm a relatively simple task)
More specifically, I have a HashMap (Using an NSMutableDictionary on iOS) that maps a unique key(Its a string of only integers called its course. For example: "12345") used to get specific sections under a course title. The hash map knows what course a specific section falls under because each section has a value "Course". Once they are retrieved these section objects are compared, to see if they can fit into a schedule together based on user input and their "timeBegin", "timeEnd", and "days" values.
For Example: If I asked for schedules with only the Course ABC1234(There are 50 different time slots or "sections" under that course title) and DEF5678(50 sections) it will iterate through the Hashmap to find every section that falls under those two courses. Then it will sort them into schedules of two classes each(one ABC1234 and one DEF5678) If no two courses have a conflict then a total of 2500(50*50) schedules are possible.
These "schedules" (Stored in ArrayLists since the number of user inputs varies from 1-8 and possible number of results varies from 1-100,000. The group of all schedules is a double ArrayList that looks like this ArrayList>. On iOS I use NSMutableArray) are then fed into the intent that is the next Activity. This Activity (Fragment techincally?) will be a pager that allows the user to scroll through the different combinations.
I copied the method of search and sort exactly as it is in iOS(This may not be the right thing to do since the languages and data structures may be fundamentally different) and it works correctly with small output but when it gets too large it can't handle it.
So is multithreading the answer? Should I use something other than a HashMap? Something other than ArrayLists? I only assume multithreading because the errors indicate that too much is being done on the main thread. I've also read that there is a limit to the size of data passed using Intents but I have no idea.
If I was unclear on anything feel free to ask for clarification. Also, I've been doing Android for ~2 weeks so I may completely off track but hopefully not, this is a fully functional and complete app in the iTunes Store already so I don't think I'm that far off. Thanks!
1) I think you should go with AsynTask of Android .The way it handle the View into `UI
threadandBackground threadfor operations (Like Sorting` ) is sufficient enough to help
you to get the Data Processed into Background thread And on Processing you can get the
Content on UI Thread.
Follow This ShorHand Example for This:
Example to Use Asyntask
2) Example(How to Proceed):
a) define your view into onPreExecute()
b) Do your Background Operation into doInBackground()
c) Get the Result into onPostExceute() and call the content for New Activty
Hope this could help...
I think it's better for you to use TreeMap instead of HashMap, which sorts data automatically everytime you mutate it. Therefore you won't have to sort your data before start another activity, you just pass it and that's all.
Also for using it you have to implement Comparable interface in your class which represents value of Map.
You can also read about TreeMap class there:
http://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html
So I am currently designing a game where the main idea is that you choose your attack and then an animation plays out based on the attack that you picked (think pokemon). The game is turn-based as well.
My question is whether scene2d would be easier to use than implementing a custom solution for handling the animation part of the game. From what I've read (and I've found it difficult to find good information on scene2d), it sounds like scene2d would make designing the UI for the buttons/menu extremely easy, but I'm not sure how I can roll that into making the actors move. Is it as simple as handling the touch event on the button and calling the corresponding actor's action method based on the player's choice?
In what I have in mind, the actors never actually move (except during their animation and they don't move across the screen, they merely go through their animations in place). During the animation, there will also be particle effects (the attack) which, if using scene2d, would need to be their own actors. Would the synchronization of the actors and the attack be difficult to produce?
Actors do movee..
actor.addAction(Actions.moveTo(posX, posY, 5)));
by this your actor moves to posX, posY and 5 is the time duration ..
using scene2d would be a good idea in my opinion..
Scene2D would be better since you would have to manually implement the listener for actions such as Click when you use Sprite whereas Scene2D provides the functions to set Listeners.
you may already know this, but let me try to answer your question:
Scene2d has a very handy action system, which basically allows the following:
do any of the provided actions
fine tune them with the many provided interpolations
make new actions with Actions.run()
chain existing actions forming sequences
Like this:
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.Action;
Action a1 = Actions.sequence(Actions.fadeOut(0), Actions.fadeIn(3, Interpolation.bounce));
Action a2 = Actions.moveTo(100, 200, 3, Interpolation.pow2Out);
Runnable r = new Runnable() {
#Override
public void run() {
setColor(1, 0, 0, 1);
System.out.println("now I'm a red actor");
}
};
And then combine then, for example like this:
addAction(Actions.sequence(Actions.parallel(a1, a2), Actions.run(r)));
This allows you to profit from scene2d's built-in sequencer saving you the half of the work, at least. So, answering your question, I think it is very possible indeed to easily implement fixed as well as reactive/randomized animations using this system. It also allows you to easily encapsulate simpler actions into complexer ones, and has the following advantages:
Very readable and maintainable code
Tradeoff CPU/Mem: much more memory-efficient than storing plain sequences or even videos
Reactivity: this way you can program your animations to be slightly different each time
On the other hand, this developing system can become very time consuming if you constantly want "uncovered" things, like the following:
Implement time-based actions yourself that aren't built-in (like camera travelling)
Make your own interpolations if the built-in ones don't fit your goals
Work with many little granular elements (for that sake I would use the ParticleEditor).
Which I don't think is your case. As a last remark, you should take a look at the spine animation engine. I don't use it myself but may be useful for what you have in mind.
I'm trying to build a complex form where almost all of the elements are optional. It starts with just a single field and an "add element" button. When you click add, the form shows a Spinner of the types of elements you can add to the form (location, photo, detailed note, timestamp other than "now", etc). When you select an item, it will launch an Activity, and each item has a different associated Activity.
In addition, each choice will have several bits of data, which it would be nice to store "with" the Activity somehow:
An icon and the displayed name in the Spinner
A key for storing the data in the db (as well as passing to a webservice)
A layout for how to display the result on the original form (i.e. a thumbnail for the photo, the lat/lon for the location, etc)
I was considering a set of classes that all extend an abstract FormElement class, and would have static elements for each of the above extra pieces of data. (An additional bump for this solution is how much of a pain Resources are in a static context.)
How can I make this as clean and maintainable as possible? I'd really not enjoy editing five different files to add a new type of element to this form. (Mostly because I can guarantee I'll miss one and spend hours chasing down unbugs.)
A few tips...
Unit tests will prevent "unbugs" :)
When each Activity has obtained the information it needs from the user, call Activity#setResult() with an Intent that contains your per-type data. Intent supports all the Bundle methods, so you can set different types of data as needed.
To support #2, make sure you're using Activity#startActivityForResult(Intent,int) to launch it, and listen for the result in Activity#onActivityResult(int,Intent)
I would probably maintain the list of available "element" types for use with the SpinnerAdapter (e.g., ArrayList<Class<? extends AbstractFormElement>>, and invoke static methods like .getDisplayName(), .getActivityClass(), etc, in the Adapter's getView() method, in order to determine what to display and what Activity to launch.
In this way, your list would actually contain things like { MyPhotoElement.class, MyTextElement.class, MyDateElement.class, ...}).
As each element is added to the form, add it to an ArrayList<AbstractFormElement>, which will be used to back another Adapter for a ListView. That adapter will dispatch the inflation of a custom view layout, as well as the creation of a ViewHolder, based on what type of object it is -- that will require that each distinct AbstractFormElement will have its own "view type", according to the Adapter. See BaseAdapter#getItemViewType(int) and related getViewTypeCount().
It's worth noting that these will need distinct view types only if one cannot be converted to the other... For example, if you have two "Elements" that only need to display a string of text in the list, those can both share a "text-only" view type. Likewise, two elements that only display a photo, or can easily convert one to the other (e.g., an icon with a caption, vs a photo thumbnail with no caption), can share a single "image-plus-caption" view type.
With the above in mind, you actually would end up having to modify different files to add a new type (well, I guess technically you could have them all in one file, as inner classes, but there's really no good argument for doing that), but if you've done your interface API correctly, and follow good OO practices, and implement good unit tests, you'll considerably reduce the amount of effort required to find bugs -- simply because most of the things involved in adding a new type would actually force a compiler error if you do it incorrectly. Add to that the fact that a proper unit test suite will be able to programmatically add all possible types, and ensure that everything displays properly, and you should have a pretty streamlined process for easy extensibility :)
It sounds like a lot of work, and it might seem tedious and verbose at first... But the end result is actually much more maintainable, especially if your list of element types is going to be fairly extensive.