Could you provide an example of how one would represent a “player” class with mutable properties such as HP and position (3d vector), functions such as init, setters and getters?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I agree with mikera, that you should try to do it immutably, but you ask specifically for mutable properties, so the way I might suggest is very similar to mikera’s answer, but to use atoms inside the map where you will have mutable properties you may want to change.
Notice that only the things you may want to change are wrapped in atoms. In order to access the mutable data you would have to dereference it, like so:
In order to set the value you could use
swap!orreset!, like so:This would be an example for you making one player, although you asked for something like an init, a getter, and a setter. I should say at this point that I have almost no programming experience outside of Clojure, so I may not have a complete grasp of what those would be, but here’s how I would set it up.
Then when I wanted to make a new player, I would do:
I think it would unnecessary to make explicit “getters” and/or “setters”, because you could simply get any mutable data by dereferencing it, and set any mutable data with
swap!orreset!in exactly the same way I showed above. Having said that, if you wanted to, you could do something like this:Now with these you could do:
Since this answer isn’t already long enough, I think it might be nice to include default values when making new players. I can think of an easy, but not necessarily elegant way to do this:
Now by default, new players will have 20 hp and be at location [0 0 0]. If passed either an integer or a vector, it will assume that should be the value for hp or location (respectively), or else it will throw an exception.
Again, I think that mutable data would probably be unnecessary in most cases, and the simplest solution may be to conceive of the problem not as “how can a make this mutable data structure” but rather “how can I create new, updated versions of immutable data, then pass these data back to the beginning of a loop, wherein afterwards I may update and recur again”.
Hopefully some of this is helpful.