I am writing an Android game in Kotlin where the board changes according to a specific pattern - which pattern, depends on the level the user currently plays.
I need a way to use many different patterns (20, 30 at max) in my code, deciding which one of them to use at runtime.
I thought of encoding each pattern as a string, putting all these strings in a file and at runtime loading it and parsing the desired one. However, the patterns aren't so simple, so parsing will be a complicated process. It also seems as an over-complication.
My best idea right now is writing a class for each distinct pattern (and a common parent abstract class to be used by the calling entities). Each class will have a single "apply" method that applies that specific pattern on the board.
However, it means dozens of classes (I could put them in a different folder so they don't make the main code folder too crowded), and a big switch case which maps the pattern id (received from the level manager) to the specific implementation. I'm pretty sure I don't want that.
Any better ideas? Thanks in advance.
It depends on what may happen in future. Will there be more patterns? Are they have parts which are common? Will there be other rules, say if you have used pattern 1 then you cannot go to pattern 1 again next time and so on?
Either way you will have a dozen of patterns. Storing them as a string, object, file, model or whatever is totally up to you but you will not escape from having them. What i mean here is having 1 file with 20 patterns is not very different from having 20 files each with 1 pattern. So no, having many classes is not something that is wrong in that case.
Put them in a folder and create a facade. That way all you need to do to use them is call the facade and get apply method based on some criteria(pattern id):
The facade itself can either map id to behavior or directly checks if there is file(class) named that way in the folder. If there is one it will get instance of it and call apply method on it as a result. You can store the instance so:
pros:
can be changed at any moment and behavior will change
there will be only 1 way to present pattern ( no option to get 2 patterns trying to draw them self's )
cons:
if some patterns at some point need to have one more method you need to change all of the classes and the facade
That way you don't need switch and there is no need to change the facade itself if new pattern shows up - just create new file with its own implementation and you are ready to go.
The question is not that ideal for SO, however, I found it really interesting. Hence I am putting some of my ideas if I had to design such game.
This is a level based game which incurs different board patterns in different levels. So it is really important that how you are designing your patterns to be translated into the board. Your pattern may have some generic keywords which can be translated into a program to create a board part by part. Let us look into an example, for making the idea clearer.
Suppose, you are building a line of pipes. Each part is being connected with the already constructed pipe. There can be a lot of differently shaped pipes in your hand. So while building a pattern, you just name each shape. For example, left-round-vertical-up, right-round-vertical-up, straight-horizontal, straight-vertical etc. You have a Factory class which knows the implementation of each of your shape. Now its pretty simple to store the whole pattern in your local database table. Which will be translated into your board in runtime, based on the logic your Factory class has.
A sample row in your database table may look like the following.
id level_number level_passed pattern_desc
-- ------------ ------------ ------------
1 1 1 left-round-vertical-up, straight-horizontal, straight-vertical, right-round-vertical-up
2 1 0 straight-horizontal, straight-vertical, right-round-vertical-up
So when you have the data in the structure above in your database and you know all the keywords of your pipe segments to be translated in your board, its simpler for you to maintain the code and to add new patterns via API call.
In your current structure, its difficult to update your patterns without any application update. However, in the proposed architecture, you can easily add new patterns in different levels using a simple API call from your server. The application knows how to parse the pattern and can show them accordingly. Then your job is to call an API to get the newly introduced patterns from your server and insert them into your table for storing patterns with appropriate values.
The factory implementation might require many classes, which indicates each shape of your pipe segment. However, you are not writing classes for each of your patterns which is quite a lot and difficult to manage further.
Hope that helps!
Related
I'm developing an android game, and on each level, i have the level information written on the code, like these example.
LevelOneballsNumber = 5;
LevelTwoballsNumber = 7;
Level one = new Level(1, LevelOneballsNumber , #FF462F);
Level two = new Level(2, LevelTwoBallsNumber, #FFFFFF);
This approach seems very hardcoding to me. There's some way to store this kind of information (information that never changed), and get them during the game?
you can save the information on file , and get it from there .
or to make a "manager class" or some static class that will contain all the information of all the levels .
So based on the information that you have provided, personally I see two approaches.
Approach 1:
One of things which you could do, is use the sql lite database if you are really concerned about keeping them as unchangable and it will persist and you can read out of there.
Approach 2:
The Other way is to make it a static class and then have reference of it for each user, but I am guessing you would have to implement a multiton design pattern to be able to effectively do it, you could do this but would involve a little more complexity than using the database directly.
I am sure there are more ways to do this, at the end of the day your call, but personally I would go the Database way.
DBs FTW!
Another approach is to store the information in an xml (or json, etc) file as your asset, and then parse it in runtime with your favorite xml / json parser. This allows a more flexibility in the schema than storing it in a relational database, and can be easily edited independent of the code.
I have a SQLite database which has a table (of course) named Object. In my application, I need to access that table and all of its fields. I am able to query the database and get all of the information I want from a cursor with no issues. The problem comes with deciding what to do with the cursor next. Right now I am thinking of creating a class called Object and it will have fields for every column in the table which will be set by the query. This just seems so... inefficient. I'm not sure how to do this without needing to write out every column that is in the table for the object to use, which seems to violate DRY. Are there any better ways to do this?
My end goal is to be able to access every row in the table and get whatever information I want for that row. For example I will be using this to populate a ListView. If this is too ambiguous let me know and I'll try to clarify.
Thanks!
Edit: I've found the library db40 and it seems to do what I want. The library seems to be kind of big though (40 mb) for a mobile application. Does anybody have experience with this? Everything I've read seems to indicate it is good. I'll post more if I find information.
Are there any better ways to do this?
This is very "wide" question and depends on personal requirements and what is for developer more comfortable. I'm using your idea that is for me the best one you can use.
Generally we can say you want to create ORM (object-relation mapping). It's very clean and efficient approach (my opinion). Of course sometimes is not the best solution to use ORM ( i never met with this case but heard about it). I almost always use my own defined ORM for sure it takes some time but results are significant against done frameworks.
Both have advantages and disadvantages. Own ORM has much more higher performance because it's designated and optimized for concrete solution (mainly queries etc.).
I suggest you to do what you mentioned -> create object that will represent table in database with properties equal to columns. I'm using this in work and we never had problems with performance or too much battery consumption with our applications.
It's also much more safe if you'll show user some data not directly from database but "copies" in objects. Users can do whatever want with dislayed results (they can add some dangerous symbols and hacks) but now you can easily check this before you'll want to update database(s) with changes.
Your source-code looks good, another developer won't be lost in your code, everything will be clear and easy to do updates for future.
I provided you "my opinion" on this thing so hope it'll help you with make a decision.
Background:
My CSS360 group is attempting to create an Android application that will include an auto-complete search feature. The data that we'll be searching consists of around 7000 entries, and will be stored in a SQLite database on the phone itself. The most obvious approach would be to do a linear search of the database following every character that the user types, and then return a list of suggestions which are potential alphabetic extensions of the user's query. However, this seems like it would be pretty inefficient, and we've been looking for better alternatives. In another one of my classes today, my instructor briefly discussed the trie data structure, and mentioned that it's often used to store entire dictionaries. Entries into a trie can be retrieved in logarithmic time (as opposed to linear time for a regular old array), so this seems like a great tool for us to use! Unfortunately, we're in waaaay over our heads on this project already, and none of us really have a clue how to make this happen. All any of us have ever coded to date are basic console applications to teach us programming basics. We're all attempting to learn the Android platform in a week's time by watching YouTube videos, and differing the database stuff to the one guy in our group who has any SQL experience whatsoever. We could seriously use some pointers!
Questions:
When creating a trie, is it possible to have the entire structure pre-populated? IE: generate a line of code for every node used, so that the entire structure will already be in memory when the program starts? My thinking here is that this will save us the overhead of having to regenerate the entire trie from the database every time the program starts. If so, is there an easy way to get these thousands of lines of code into our program? IE: Some sort of script which converts the database files into a giant text file of java commands which can be copied and pasted into Eclipse?
Will there be a considerable amount of overhead if we search the database directly instead of using some sort of internal list or data structure? Should we be copying the names out of the database and searching them inside the program for our auto-complete function?
If this proves too technically difficult for us, and we have to resort to a regular linear search, will the performance be noticeably affected?
Our current plans are to run the auto-complete function each time the user enters a character, and then wait for the function to return before allowing them to continue typing. The only programs any of us have written so far function synchronously like this. What would we need to know to make this function asynchronously? Considering our novice abilities, and the requirements that we're already having to meet, would this be too technically challenging for us?
sqlite should be able to serve this auto-complete functionality reasonably well. I'd recommend using their internal indexes over re-implementing the wheel. If you need to do the latter, then sqlite is probably not going to help you after you've done that work.
If you want substring searching, then full text search is probably your best bet.
If you only want to complete the beginning of the word, then just using their vanilla indexes should be more than enough. If performance is a problem, then just wait until they type three characters before doing the query. Set a limit on your results for snappy responses.
I am a php/mysql developer learning android. I am creating an android app that receives info from my php app to create list views of different products which will open a web view of that product's detail.
Currently my php cms web application outputs xml lists for an iphone app.... (also, separately outputs html). I have full control of the php app so if there is a better way to output the data for the android app please let me know.
I have created code that reads the xml from the web and creates the list view. The list can be refreshed daily, so the data does not need to be read from the online xml every time the app starts.
So I was thinking to store the data retrieved locally to improve my apps responsiveness. there may be up to 500 product descriptions to be stored at any given time in up to 30 different xml lists. I am starting development with one xml list with about 30 products.
For best performance should i store the product info in a sqlLite db or should i store the actual xml file in the cache/db or some other method like application cache.
I also was think to create the update of the data as a service, would this be a good idea?
The most efficient way to store data is RAM. But if you want to cache it, then the most efficient way is Database.
I recommend you store your data in sqlite android database.
You could also consider zipping you xml for faster network transfer and unzipping through java.util.zip package classes. You could even consider a simpler format for transmitting data, less verbose than xml, using a datainput/outputstream.
(I do that in of my apps and it works great)
Here are some details on data input / output stream method :
imagine a proprietary protocol for your data, only what you need. No tags, no attributes, just raw values in order.
on the client side, get an input stream on your data using URL.getContent() and cast it in input stream.
on the client side still, build a data input stream encapsulating your socket input stream and read data in order. Use readInt, readDouble, readUTF, and so on.
on the client side, from php, you need to find a way to save your data in a format that is compatible with the data format expected by the client. I can't tell much about PHP, I only program using java.
The advantage of this technique is that you save bandwith as there is only data and no verbose decoration due to xml. You should read about java specs to understand how double, int, strings are written in data output stream. But it can be hard using two languages to get the data right.
If php can't save format in a suitable way, use xml, it will be much simpler. First try with just plain xml, then give a try using a zip or tarball or xml file.
But all this is about speed gain during network connection.
The second part of what you have to do is to store each row of your list in a SQL table. Then you can retrieve it pretty fast using a CursorAdapter for your list view (it breaks the charming MVC model but it is quite fast !).
Sorry about this, but it became too long to write as a comment. This is not intended to be an answer to your question, because in my opinion Stéphane answered very well. The best solution is indeed to store the data in an sqlite database. Then you need to create the class to be used as a connection between the data, the database and the app. I don't want to take credit for what is said here already (I, too, voted it up).
I'm concerned with the other suggestion (use of low level raw streams for data manipulation, the list steps on that answer). I strongly recommend you to avoid creating your own proprietary protocol. It goes like this:
I need to exchange data.
I don't want to deal with the hassle of integrating external APIs into my code.
I know I can write two 5 minute routines to read and write the data back and forth.
Therefore, I just created my own proprietary format for exchanging data!
It makes me cry whenever I need to deal with unknown, obscure and arbitrary sequence of data blobs. It's always good to remember why we should not use unknown formats:
Reinventing the wheel is counter-productive. It seems not, but on the middle term it is. You can adapt your project to other mediums (server-side, other platforms) easily.
Using off-the-shelf components help you scale your code later.
Whenever you need to adapt your solution to other technologies and mediums, you'll work faster. Otherwise, you would probably end up with ad hoc code solutions that are not (easily) extensible and interoperable.
Using off the shelf components enables you to leverage advances in that particular technology. That's particularly important when you are using Android APIs, as they are frequently optimized for performance later down the road (See Android's Designing for Performance). Rolling your own standards may result in a performance penalty.
Unless you document your protocol, it's extremely easy to forget the protocol you created yourself. Just give it enough time and it will happen: you'll need to relearn/remember. If you document, then you are just wasting the computational time of your brain.
You think you don't need to scale your work, but chances are you will most of the time.
When you do, you will wish you had learned how to easily and seamlessly integrate well known formats.
The learning curve is needed anyway. In my experience, when you learn, you actually integrate well known formats faster than imagining your own way of doing things.
Finally, trust your data to geniuses that take their lives into creating cohesive and intelligent standards. They know it better!
Finally, if the purpose is to avoid the typical verbosity of XML, for whatever reasons, you have several options. Right now I can think of CSV, but I'm no expert in data storage, so if you're not confortable with it, I'm sure you can find good alternatives with plenty of ready to use APIs.
Good luck!
I want to save my Android game state so the user can pick up and play from where he/she left off.
I have been reading about the serializable interface, but have some questions.
Aside from background rendering and a few other things my game is performed from one class.
Let me explain what that means. I have a class A, and all the different elements of the game are stored in various arraylists and such, in A. SO I have dozens of instances of classes B,C,D,E... all being called and updated (when the screen updates) from class A.
My problem is I am unsure what needs to be serializable. Every class B,C,D.. (i.e. every class? or just A? I don't see why serializing A and then saving the output in SQLite DB wouldnt store all the data.
Just as a suggestion, you may also want to look at Berkeley DB Java Edition, specifically at the DPL (Data Persistence Layer) API. Like SQLite, it's a transactionally protected, recoverable, fast, small footprint database library. However, the DPL allows you to directly persist your classes, making it a much easier choice for Java application developers.
Here's a technical white paper describing the API and how to use it.
if you want to serialize some object. then look at this link use other object in place of hashmmap object that has been specified in this link.