Categories
Object

Object Relationships

While file structures and the like are incredibly entertaining, at some point in the development of a text based game were probably going to have to parse some text. But before I dive into developing a natural language parser (next week hopefully?) why don’t we work on some behind the scenes stuff that enables the user to change the game world in a meaningful way?

I’m going to be breaking down how I build up relationships between objects. It doesn’t sound like much but its essential to making a game environment that persists. Our goal will be to build two rooms, a player, and move between them. Pretty basic movement but to run you must walk, and to walk you must stand!

Class Room

You’ve probably seen a class like this, its mostly string attributes for its name and a couple descriptions. Then we have the .exits dictionary where we will spend most of our attention.

Class Player

We need something to “move” between rooms right? so lets make a quick player.

There nice and short, we gave him a name, an inventory that we will ignore for now, and most importantly a location.

The location that we passed here is noted as being an object. This is important because we want that object to reference later. If we need to ever tell the player where they care we can just call location.name and it will give us the name string we stored on the Room object when we created it. I like to think of this as one way association. The player knows that they are in the room but the room doesn’t know that the player is there.

The last part we need to cover before building a room relationship is making instances of room objects. Lets make a Den and a Library. Oh and an instance of our player.

Initialize Rooms/Player

For the Rooms we just pass each a name string, a blank dictionary and a couple of variables that represent longer strings (keeps the code clean)

Then we make a guy, lets call him Ted. Ted starts in the den so we will pass him that object as his location. Ted has nothing in his inventory. Poor Ted.

Building Relationships

Ok we have two rooms, and even a player who knows he is in a room. Now we need a hallway between the Den and the Library. Lets put it on the west side of the Den and the south side of the Library because the hall curves for some reason.

We do this by accessing the .exits library in each room and going to our desired direction key. Then we set that direction to the other room. That gives us a reference within each room object to the other room. I like to think of this as a two way relationship as opposed to our one way earlier. The rooms both know that they are connected! Don’t think about it too much!

First steps

Now is the moment of truth our player got tired of the Den and he wants to go Read a book so he inputs a command that calls room_mov() one of his methods with the string “west” because he remembers the library is over there.

His method room_mov() looks a little dense but its really just checking to see if west if each direction has a brick wall or a hallway.

First we set a bool and rename self.locaation too just this_room because its a little easier

the for loop on line 58 iterates through keys for all the possible exits from the den (north south east and west)

We check two things for validity on line 59, wither the key matches the key string the user gave us, and wither that key has an association attached to it.

If both of those are true then its a valid destination! Yay! we set our bool to true to indicated this on line 61

For convenience sake we also grab the validated object that matches the key string on line 63.

THAT WAS A LOT OF VALIDATION

but it was worth it because we get to update our players location on line 67 and he finally gets to Read the latest copy Of Fantasy and Science Fiction magazine that he has been waiting all month for.

At the end we can check for non existing associations (brick walls) by printing out a string that lets the player know they are still in the same room. Wrong way Ted.

Categories
JSON

Json and objects

One of my goals in my current project, making a text based adventure game, is to create a method of saving the state of the game and loading it later. Last week I went in depth on a method of saving dictionaries but that falls a little short when it comes to a larger project. What would be really useful is the ability to store the attributes of a given object and retrieve them later. Then ideally if I created a new instance of an object when the game opens, say representing a room, I could simply write the saved attributes over the ones it is initiated with. That way if a player “dropped” and item in the room it would be preserved in one of the attributes. This could also be used to save states of features in the room, or other changes that the player makes. Additionally it allows the room class that the object is created from to inherit all of the methods that might be tied to it, eg. get exits, get description, that kind of thing. Here’s what I came up with.

same as last time remember to import json before following along.

Basic Setup

We will need an example class to work with, so we will initialize a basic car class and give it a few attributes as well as a method. Honk probably would have been a better method but I’ve ben watching too much Knight Rider lately so our car can talk.

Its always good to throw in a couple test prints just to make sure the basic stuff is working. Your current output should look something like this

Boom we have a talking Honda city. Its no Pontiac Firebird but lets try to save it anyway.

Save the attributes

While JSON is an incredible tool it seems that it mostly likes saving dictionaries. There are more complicated ways to store a whole object but I found this method to suit my purposes the best. We are going to save our attributes as a dictionary so we can restore them to a new instance of the object at a later point. We can to this with a method very similar to the dictionary saving I covered in my last post.

The first think we need to do is convert to JSON format so we use json.dumps() to dump a dictionary of our objects attributes. Very handy. Throw in a test print to makes sure the string looks right and then make a new to a JSON file using the same with open() command I introduced in my last post. Finally we can use json.dump() to send the formatted string to the file that we just created. As with last week your output shoudnlt change much but you will notice a new JSON file named attributes_save in the same folder as your main python folder.

Now that we have a dictionary of our object attributes saved pretend we are starting a new instance of our game. We ultimately want to make a new car with the same attributes as our first so lets start by grabbing them from the saved JSON dictionary.

We can use with open() and the ‘r’ attribute to read the JSON file. Then we save the new data by running json.load() with the file alias and assigning it to the varible “data” on line 39. We then use json.loads() to make it a python dictionary. This pretty much the same process we used to get JSON data in the last post. This time however, after we confirm that the data is good with a couple test prints we are going to do something different.

Make a new object with the old attributes

This bit is quick but essential, don’t blink or you’ll miss it.

Ok so what happend there.

Lets start with the first bit, we created a new car object. When we do that it should have the initial attributes all cars start with, but those are effectively junk values when we want our cool Honda City back. When we make the call to make a Car object we pass in **and the dictionary of data that we retrieved as the attribute values for our new car. Thus we have created an object that is essentially exactly the same as the one we saved. Since new_car was created as a Car object it also has access to all of the same methods as the original. The only draw back to this approach is that you have to know ahead of time what the attribute fields of your object are but it works for the purposes of saving.

you should at this point be able to get the old values from the new_car object! Well done!

Here’s a link to my get hub with the complete code for reference.

https://github.com/samuelh223/Json_objects_dictionary/blob/main/main

Categories
JSON

Saving a dictionary with JSON

In my current project I am at some point going to need to save data to a file and load the data back in the next time they are going to use the program. With Python there are a few ways to do this but the most common seems to be using JSON. The problem I found in much of the existing material available after a quick google is that an individual tutorial might tell you a piece of the information you need but many of them gloss over crucial steps in order to tell you five different ways to turn your data into a json dictionary. Great information but less that practical. I’m going to show you a way that works start to finish. Is it the best? Well it works so lets start there.

Remember to import json before you start coding.

Moving a dictionary into a JSON file

In order to save anything into a JSON file you need to covert it into the proper format. This is where json.dumps() function comes in. You can see below that I declared and example dictionary and then converted the dictionary by passing it to json.dumps()

If you print it out at this point you will see that the file has been changed into the JSON format.

The next step is to take this formatted information and save it to a JSON file. To do this we can use with open(). When we pass the function these parameters with open will either make or open a file called dictionary_save.json note that this can be whatever file name as long as it ends in .json. We will also pass the “w” argument because we are writing to the file. Note that when we refer to the file in this section of the code have designated it thisdict_file. Very handy we want to do anything with that file we just went through all the trouble of creating. The very last thing here is to use json.dump() and pass it the formatted data we saved to dict_1 above and the file we want to send it to. Good thing we have that reference to our file.

If you run the program right now you aren’t going to see much difference. but if you open where ever your folder for the program it or you can see it in your IDE you might notice an addition.

Its the file we just created! If you open it you can see that your data is stored in there.

This is how it looks in the python editor.

Moving a dictionary out of a JSON file

Cool now you information is saved now you need to know how to access it when you need it. This section has two parts, you have to retrieve the json data and then turn it back into something you can use.

You can use with open() and pass it the file name you are trying to access and the ‘r’ argument and it will let you read the file. We also tell it we are going to be referring to the file as thisdict_save for this section of code.

We also have a chance to use another JSON function here, json.load(). This will grab the data from our file and save it to our cleverly named variable.

If you print the data variable the output should look something like this

In other words exactly the same thing we sent in.

I have to say that I am a little put out that some guides decided to stop here in their explanations. After all you got the formatted information back but you can’t do anything with it. Useless.

That’s where this little one liner comes in.

json.loads() turns JSON formatted data back into a dictionary that you can reference normally. There is a subtle difference in the prints but if you have double quotes around you dictionary when you print, it is likely still in JSON format as in the first line below.

Single quotes on your dictionary mean that you have it back to a workable Python format.

CONGRADULATONS!!

You just stored a dictionary in a JSON file and got it back to a working Python dictionary. Small victories add up to something larger.

Check out my GitHub for the full code I used for this explanation.

https://github.com/samuelh223/json_dictionary_convert

Categories
Kotlin

Kotlin and Android Studio

Sometimes as programmers it is hard to show the results of even the smallest of our efforts unless we open up and IDE and show someone what we have been working on or how programming can solve their problem. I found a little more recognition after learning some of the Kotlin programming language and how to use android studio.

Recently a collogue of mine who is also attending OSU complained that he was unable to put in what if scores in the grades section of his class. After several minutes of watching him manually add up scores and attempt averages/weight ect. I was all but begging him to just let me write a program that would do it for him. He had his doubts at first but I insisted that it would be easier to figure out all the different values he wanted to test if I just wrote something for him.

It took less than a minute before I had a simple program with hard coded values that let him test different possibilities and potential what if scores. It was a quick problem-solving scenario aided by programming and he was grateful for the help.

But that interaction got me thinking, I’ve written several small useful programs for myself over the course of my study’s at OSU but I don’t really have anything that I can share with people. Sure, I can load up PyCharm or some other IDE or run an executable but that seems a little heavy handed when people are more comfortable with downloading an app within seconds and skipping all the hassle.

After some searching into android app development, I found that one of the preferred languages for android development was Kotlin. They have a light browser-based environment to try out the language on their website so you can see if you like it before downloading a compatible IDE.

Kotlin Playground

And I found and introductory course on the android website for using the Kotlin IDE for Mobil app programming. Some of the material is a bit basic but it does a really good job of breaking everything down step by step. Even though I hadn’t used the language before I found the transition much easier than my attempts at using Java.

Android Studio and Kotlin language course

I highly recommend looking into this course if you want to branch into app development or even just to make a more user-friendly version of a program that you have already written. I took a few days out of my spring break and came out of it with some Mobil programming experience and a custom app for a collogue. I’ll mark that down as a win in my book any day