Libgdx json file initial game values - java

Quick question.
In my code I have the storing of my game values to Json. How would I do something where the first time they enter the game it sets the players values to the default base values. I have a method that has these values set that I can call and then use my save method? But I need a method that checks if its the first time the game has been run.. And if its the first time somehow create the json file to save to later.

Something like this should do it:
public class Game
{
final int COINS_DEFAULT = 0;
final String PLAYER_NAME_DEFAULT = "PlayerName";
...
File userInfoJSON = new File("/filepath");
if (userInfoJSON == null)
{
resetToDefaultsThenSaveToJSON();
}
}

For Libgdx you should use FileHandle:
FileHandle valuesFile = Gdx.files.internal("values.json");
if (!valuesFile.exists()) {
createJsonValuesFile();
}
I would suggest you to check(and create) it prior the actual game starts, for example, during the loading screen setup.

Related

How do I store information in a method so I can use it in a different method later?

I am very new to Java, so sorry if this is stupid and obvious or worded poorly. I don't really know enough yet to know what I don't know.
So I decided that since I have to learn Java, I'd just jump in head first and try to figure it out as I go. So far, it's worked decently. I'm trying to reinforce some basic concepts I already know by writing small programs that do trivial stuff.
I decided I'd write a little text based adventure game and it's working well so far. I'm using Scanners and Switches to call methods that use Scanners and Switches to call other methods. That's all working fine.
So far it's a very linear straight line, like an old choose your own adventure book. But, I wanted to add a player inventory. I have a very vague idea of how to do it, but I have a pretty solid idea of what I want it to do.
So, basically I want to store a piece of information that says the player has a specific item. I want to be able to test for the presence of more than one item at once. And I want to be able to tell the player what items he has at any point in the game.
I don't really know how to ask the question better.
My best guess is doing something like
int key, potion;
key = 0
potion = 2
and then testing the values of each one
if (key = 0) {
System.out.println("you don't have the key ");
}
if (key > 0) {
System.out.prinln("You unlock the door");
}
I'm doing each new room as a separate method, so the whole game is just a big chain of methods. So my hope is that the information about items can be stored in a separate method that I can access through switches or if/else in the current room method the player is in. So, the player is unlocking a door in room2, which is its own method, and he picked up the key in room1, which is its own method, and the key is stored as an integer in the inventory method. But the key was one use, so the key integer is set to 0 and the method room3 starts. If that makes any sense.
Again, sorry if this is really stupid basic stuff. I'm very new to programming.
No problem and I applaud you for choosing to learn programming. This is basic data structures. If you want to hold a value, in most programming languages, you'll have an array. I think breaking your logic down is a good idea i.e., (store an item, test for > 1, list items). The first step is making this as simple as possible and than maybe adding getters/setters later through refactors. Ultimately, your goal is to make the most basic code work first (like this) and than refactoring towards an object oriented class with getters/setters and/or a HashMap.
1:
public class PlayerInventory
{
private String[] inventoryStr = new String[20]; // basic implementation
inventoryStr[0] = "Phone";
inventoryStr[0] = "Book";
}
2:
int arrayLength = inventoryStr.length;
3:
for(int i=0; i < inventoryStr.length; i++) {
System.out.println( inventoryStr[i] );
}
Refactor (after you write unit tests for this)
1*: (with a list)
import java.util.*;
import java.util.*;
public class CollectionGetterSetter {
private List<String> playerInventory;
public void setPlayerInventory(List<String> inv) {
this.playerInventory = inv;
}
public List<String> getPlayerInventory() {
return this.playerInventory;
}
public static void main(String[] args) {
CollectionGetterSetter app = new CollectionGetterSetter();
List<String> PlayerInventory = new ArrayList();
PlayerInventory.add("phone");
PlayerInventory.add("book");
PlayerInventory.add("glasses");
PlayerInventory.add("nav");
app.setPlayerInventory(PlayerInventory);
System.out.println("Player 1: " + PlayerInventory);
List<String> PlayerInventory2 = new ArrayList();
PlayerInventory2.add("cap");
PlayerInventory2.add("gown");
PlayerInventory2.add("foo");
PlayerInventory2.add("bar");
}
}

Searching Array list of objects

I have an array list in a class the array is called realtorList. From my main class I store objects with realtor data to the realtorList.
My data that is stored to a text file and is read in the first line.
This is the first element in the realtorList after I store the first line of data.
[Realtor{licenseNumber=AA1111111, firstName=Anna, lastName=Astrid, phoneNumber=111-111-1111,
commission=0.011}]
When I read the next line of data from the input file I need to see if the licenseNumber in bold already exists in the realtorList. I am having trouble figuring out how to go about doing this.
For example if the next realtor data license number is AA1111111 how do I check the realtorList for AA1111111 which does exist for this example.
A really simple way to do this would be to have a String ArrayList running alongside (for example, one called licenses) and use an if statement with indexOf to return if that license value is already in the List. Since the licenses ArrayList only has one value it can be easily searched with indexOf.
An example would be
private boolean checkLicense (String licenseNumber) {
int i = licenses.indexOf(licenseNumber);
if(i == -1) {
return false;
} else {
return true;
}
}
Similar code works in one of my projects where a dynamic List of motors for a robot checks to see if there's already a motor with the listed port before adding a new one.
Another method could use a for loop for a linear search such as
private boolean checkLicense (String licenseNumber) {
for(int i = 0; i < (realtorList.size() - 1); i++) {
if (licenseNumber.equals(realtorList[i].getLicenseNumber())) {
return true;
}
}
return false;
}
This would perform a linear search of each and every object until it finds it (it would need to be in a method like the one for the example above to work this way)

Best practise for counting data in java

Lets say there is a pool of data taken a CSV file where we have a key value pairs, but keys are not unique. The requirement is to sift through each and every line and convert the CSV data into something useful. I'll make an example using a game log with format:
player, pointChange, timestamp
What I would like to do (which seems like a common operation) is to create a summary - how many points has over time. My idea was to create an inner class that represents a single entry:
private class GameFrame{
private String player;
private int points;
private ArrayList<String> timeline = new ArrayList<String>();
private ArrayList<int> pointHistory = new ArrayList<int>();
GameFrame(String player, int points, String time){
this.player = player;
this.points = points;
this.time.add(time);
}
public String getName(){return this.player;}
public void increment(int change){
this.pointHistory.add(this.points);
this.points += change;} //will work with negatives to decrement points as well
public void timeProgress(String time){this.time.add(time);}
}
The actual challenge:
The original data is of unknown size and is read line by line. Is there a good practice/recommended method to process such data. I was thinking about making a list of all GameFrame objects and nesting a second loop, something like this:
pseudocode:
for(everything in the input list){
load up line data;
for(everything in gameFrame list){
compare names;
if names match - update with data
return;}
got out of inner loop so it's a new player.
create entry for new player and add it to gameFrame list
}
Is it a good approach or there is a better way of doing it (perhaps to sort the data first or by using a library I don't know about)?
UPDATE:
I will try to do this using a hashmap instead of ListArray as suggested by Luke
Heavy solution: Database
More appropriate if you're going to have lots of records, you want to do the parsing/inserting in one session once, and then do processing later/multiple times, and if you're going to be appending data constantly. Databases make it really easy to work with sets of data.
Create a table named frames, with fields player (varchar), point_change (int) and timestamp (datetime), or similar. In the parsing step, simply insert the rows. Then you can select distinct player from frames; to get all players. Or select player, sum(pointChange) from frames group by player; to get points for a particular player. Or include the timestamp in a where clause to get points over a particular window of time.
Light solution: HashMap
More appropriate if you're going to do this one time. Or if there are so few records that it can be run many times trivially. It avoids the whole 'setting up a database' step.
HashMap<String, Integer> map = new HashMap<String, Integer>();
public void insert(String player, int scoreChange) {
Integer value = map.get(player);
if (value == null)
value = 0;
map.put(player, value + scoreChange)
}
public void getScore(String player) {
Integer value = map.get(player);
if (value == null)
value = 0;
return value;
}

Bukkit plugin - check if specific data from a file exists, and declare it

I'm having an issue with a bukkit plugin I'm updating. In what I'm doing, when a player uses a bed, it saves the following data to a file named beds.yml:
ThePlayersUsername:
X: (double)
Y: (double)
Z: (double)
world: worldName
When the plugin is initialized, I need to declare a few variables, because they are used later on in the code.
Player p = (Player)sender;
String dn = p.getDisplayName();
dn = ChatColor.stripColor(dn);
double x = (Double) yml.get(dn + ".x");
double y = (Double) yml.get(dn + ".y");
double z = (Double) yml.get(dn + ".z");
World bw = Bukkit.getWorld((yml.get(dn + ".world").toString()));
Location l = new Location(bw, x, y, z);
I can't do this if they don't exist, but, I can't reset to any defaults because new items get added to the config each time someone enters a bed, and all data is user-specific.
How would I go about checking if the player has some data in the config, if not, telling them to sleep in a bed, and when they do have data in the config, how to declare it so they can use a command to teleport using data from the config. Thanks.
Create 2 list or array:
-The online players
-The players in the config
A simple string list is do the magic just store the names. Then compare them. Something like that:
List<String> online_players = new List<String>();
//fill list code here
List<String players_in_config = new List<String>();
//fill list code here
List<String> output = new List<String>();
for(String s : online_players){
for(String a : players_in_config){
if(s.equals(a)){
output.add(s);
break;
}
}
}
//and now output contains the names of the players that online and have a bed in the config
You are going to want to use a Map here. Maps are a data structure that creates key-value pairs for your data. You can ask a Map for the data associated with a given key and you will get the value you put into it, or null if they key was not found.
Your map would look something like this:
private Map<Player, Location> bedLocations = new HashMap<Player, Location>();
We are going to store this data inside your JavaPlugin class since it needs access inside your listener and command handler. You will also need a way to get this Map from within your listener. An accessor method will do the job here. See the below method for how to do this. You will need to do it later as well.
public Map<Player, Location> getBedLocations() {
return bedLocations;
}
In case you were wondering, a HashMap is a type of map that used the int hashCode() method to quicken key value access, but that's a more high level topic that's irrelevant to the issue at hand.
That map should store a key-value pair of all Players currently online that have a bed location associated with them. Since you don't need someone's info until they come online, you shouldn't load out of the configuration yet, but you should still open the configuration like so to prevent reading the file every time. This should be done in the onEnable method.
//Near your map and other class variables
private FileConfiguration bedConfiguration;
//Inside your onEnable
bedConfiguration = YamlConfiguration.loadConfiguration(new File(PLUGIN_VARIABLE.getDataFolder(), "beds.yml"));
Don't forget to store that bedConfiguration in a class variable. Also create an accessor method for it. I would name it getBedConfiguration().
Now you have a loaded configuration and a place to store your data, what next? You need to populate your Map with player data when they join.
Inside your listener, you should write a method to listen for the PlayerJoinEvent. Inside here you will load your player data.
Firstly, we need to get the YML file from our JavaPlugin class.
FileConfiguration bedConfig = plugin.getBedConfiguration();
That will get you the FileConfiguration that you opened up earlier. Now we check to see if the player's data is in the config.
if (bedConfig.isSet(event.getPlayer().getName()) {
//Next section here
}
If the isSet method returns true, then something exists there. Now we load the data.
String playerName = event.getPlayer.getName(); //You can do this above the if statement if you wish.
double x = (Double) bedConfig.get(playerName + ".x");
double y = (Double) bedConfig.get(playerName + ".y");
double z = (Double) bedConfig.get(playerName + ".z");
World bw = Bukkit.getWorld((bedConfig.get(dn + ".world").toString()));
Location loc = new Location(bw, x, y, z);
Your data is loaded! Excellent. Now we store it in the map for later access. First, get the Map from the JavaPlugin class. Then we put our data into the Map.
Map<Player, Location> map = plugin.getBedLocations();
map.put(event.getPlayer(), loc);
The data is in the map! To access it, make sure you get the map first and then call map.get(PLAYER);
Other things that need to be done are... saving the data when a player leaves / the server shuts down and removing the player from the map when they leave (Keeping players in a map is a very bad practice, you can use their name or UUID as a key if you wish to prevent that issue).
To save your Map to the config, you can either change the config whenever a bed location changes, or you can wait and loop over all the Map entries and save them all at the end. To loop over these you can use an advanced for loop.
for(Player player : map.keySet()) {
Location loc = map.get(player);
//save here
}
This will loop over all players in the map and let you access their location with the map.get(player) method.
To remove a player from the map, listen for the PlayerQuitEvent and use map.remove(player); to unload their data. Don't forget to save it first if you don't save it every update.
If you have any questions, please leave a comment. I tried to be very thorough.

how to pass object by reference in android to make changes in orignal object?

friends,
i have code
DalCategories selected_object= new DalCategories();
for (DalCategories cat : DalCategories.EditPostCategory)
{
if(cat.getCategory_Id().equals(root_id))
{
selected_object = cat;
// add to list
if(selected_object.getSub_Category() != null)
{
for (DalCategories t : selected_object.getSub_Category())
{
if(t.getSub_Category() != null)
{
// MakeChangesInThisObject(t.getSub_Category());
adapter.addSection(t.getTitle(), new EfficientAdapter(this,t.getSub_Category(),selected_object.getSub_Category().get(0).getSub_Category()));
}
}
}
// add to list
break;
}
}
DalCategories.EditPostCategory has three levels i want to change third level object values and want this change should be done to DalCategories.EditPostCategory by reference and using MakeChangesInThisObject
any one guide me how to achieve this?
Before you try and learn Android learn a bit of java. All objects are passed around by reference. It would be crazy if each time you passed a reference the entire thing was cloned/copied especially when it is not necessary because the class is immutable.
Think what would happen if you created a byte array with 500000 bytes. If it got copied each time a method was called with it as a parameter, your cpu would be wasted copying this array lots of times without actually doing anything.

Categories

Resources