How to load multiple languages for gameplay3d? - game-engine

How to load multiple languages for gameplay3d? I want to join other countries to support the text.

Without knowing much about this engine, it seems that you can create your own ASCII fonts, and thus render those easily.
What you could do is create a simple multi-language system yourself with each language having a gameplay::Font object of its own.
See here for some more information on how to use this object: https://github.com/blackberry/GamePlay/wiki/Text-and-Fonts
of the gameplay3d forum if you haven't already tried it: http://www.gameplay3d.org/forums/
A basic multi-language system could be something like the following pseudo-code:
class LanguageManager
{
private Language _currentLanguage = Language.enUS;
private gameplay::Font[] _fonts;
private gameplay::Font _currentFont;
public void SetCurrentLanguage(Language l)
{
this._currentLanguage = l;
this._currentFont = this.GetFontFromCurrentLanguage();
}
public void RenderString(string key, int x, int y, etc....)
{
string s = this.GetTextFromKey(key);
this._currentFont.drawText(.....);
}
private GetFontFromCurrentLanguage()
{
etc...
}
private GetTextFromKey(string key)
{
// get the text from a the resource file
}
}
You can store all of the language translations in a simple file with the following format and get the value from the above LanguageManager.GetTextFromKey method:
GameText.txt
[language]
key value
for instance
[enUS]
options Options
exit Exit
[zhCN]
options 选择
exit 离开

Related

How to write an APEX #test for a picklist method?

I was searching for answears but I couldn't find it. It might be a beginner question, anyhow I am stuck.
What I am trying to write is a test in Apex. Basically the Apex code gets field names from one specific object. Each fieldname will be shown in a picklist, one after the other (that part is a LWC JS and HTML file).
So, only want to test the Apex for the moment.
I don't know how to check that a list contains 2 parameters, and those parameters are object and field. Then the values are correctly returned, and I don't know how to continue.
Here's the Apex class with the method, which I want to test.
public without sharing class LeadController {
public static List <String> getMultiPicklistValues(String objectType, String selectedField) {
List<String> plValues = new List<String>();
Schema.SObjectType convertToObj = Schema.getGlobalDescribe().get(objectType);
Schema.DescribeSObjectResult objDescribe = convertToObj.getDescribe();
Schema.DescribeFieldResult objFieldInfo = objDescribe.fields.getMap().get(selectedField).getDescribe();
List<Schema.PicklistEntry> picklistvalues = objFieldInfo.getPicklistValues();
for(Schema.PicklistEntry plv: picklistvalues) {
plValues.add(plv.getValue());
}
plValues.sort();
return plValues;
}
}
I welcome any answers.
Thank you!
This might be a decent start, just change the class name back to yours.
#isTest
public class Stack73155432Test {
#isTest
public static void testHappyFlow(){
List<String> picklistValues = Stack73155432.getMultiPicklistValues('Lead', 'LeadSource');
// these are just examples
System.assert(!picklistValues.isEmpty(), 'Should return something');
System.assert(picklistValues.size() > 5, 'At least 5 values? I dunno, whatever is right for your org');
System.assert(picklistValues[0] < picklistValues[1], 'Should be sorted alphabetically');
System.assert(picklistValues.contains('Web'), 'Or whatever values you have in the org');
}
#isTest
public static void testErrorFlow(){
// this is actually not too useful. You might want to catch this in your main code and throw AuraHandledExceptions?
try{
Stack73155432.getMultiPicklistValues('Account', 'AsdfNoSuchField');
System.assert(false, 'This should have thrown');
} catch(NullPointerException npe){
System.assert(npe.getMessage().startsWith('Attempt to de-reference a null object'), npe.getMessage());
}
}
}

Does this saving/loading pattern have a name?

There's a variable persistence concept I have integrated multiple times:
// Standard initialiation
boolean save = true;
Map<String, Object> dataHolder;
// variables to persist
int number = 10;
String text = "I'm saved";
// Use the variables in various ways in the project
void useVariables() { ... number ... text ...}
// Function to save the variables into a datastructure and for example write them to a file
public Map<String, Object> getVariables()
{
Map<String, Object> data = new LinkedHashMap<String, Object>();
persist(data);
return(data);
}
// Function to load the variables from the datastructure
public void setVariables(Map<String, Object> data)
{
persist(data);
}
void persist(Map<String, Object> data)
{
// If the given datastructure is empty, it means data should be saved
save = (data.isEmpty());
dataHolder = data;
number = handleVariable("theNumber", number);
text = handleVariable("theText", text);
...
}
private Object handleVariable(String name, Object value)
{
// If currently saving
if(save)
dataHolder.put(name, value); // Just add to the datastructure
else // If currently writing
return(dataHolder.get(name)); // Read and return from the datastruct
return(value); // Return the given variable (no change)
}
The main benefit of this principle is that you only have a single script where you have to mention new variables you add during the development and it's one simple line per variable.
Of course you can move the handleVariable() function to a different class which also contains the "save" and "dataHolder" variables so they wont be in the main application.
Additionally you could pass meta-information, etc. for each variable required for persisting the datastructure to a file or similar by saving a custom class which contains this information plus the variable instead of the object itself.
Performance could be improved by keeping track of the order (in another datastructure when first time running through the persist() function) and using a "dataHolder" based on an array instead of a search-based map (-> use an index instead of a name-string).
However, for the first time, I have to document this and so I wondered whether this function-reuse principle has a name.
Does someone recognize this idea?
Thank you very much!

Returning the class which is a foreign key in the database

I want to ask this question and I tried to search for a while without concrete answers.
I have made a database and used LINQ2SQL to auto-generate the classes needed.
I have set the serialization mode to unidirectional to make sure the classes are being serialized and making the datamembers.
Now, what I want to know is, how I can send the references to the other classes (which has been made through LINQ2SQL).
F.x. I have a Class called Scheduler which is referencing Reservation, and Seat, because Reservation and Seat have foreign keys.
You can see the dbml here:
http://imgur.com/rR6OxDi
The dbml file. This is the model of our database
Also you can see that when I run the WCF test client it does not return the objects of Seats and Reservation.
http://imgur.com/brxNBz7
Hopefully you can all help.
UPDATE
Here is the snippet of the code provided by LINQ2SQL.
This is the fields for the scheduler
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Scheduler")]
[global::System.Runtime.Serialization.DataContractAttribute()]
public partial class Scheduler : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private int _SchID;
private System.Nullable<System.DateTime> _Date;
private System.Nullable<System.TimeSpan> _Starttime;
private System.Nullable<int> _MovieID;
private System.Nullable<int> _HallID;
private EntitySet<Seat> _Seats;
private EntitySet<Reservation> _Reservations;
private EntityRef<Hall> _Hall;
private EntityRef<Movie> _Movie;
private bool serializing;
And here is the snippet part of the code where it references to Reservation and Seat:
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="Scheduler_Seat", Storage="_Seats", ThisKey="SchID", OtherKey="SchedulerID")]
[global::System.Runtime.Serialization.DataMemberAttribute(Order=6, EmitDefaultValue=false)]
public EntitySet<Seat> Seats
{
get
{
if ((this.serializing
&& (this._Seats.HasLoadedOrAssignedValues == false)))
{
return null;
}
return this._Seats;
}
set
{
this._Seats.Assign(value);
}
}
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="Scheduler_Reservation", Storage="_Reservations", ThisKey="SchID", OtherKey="SchedulerID")]
[global::System.Runtime.Serialization.DataMemberAttribute(Order=7, EmitDefaultValue=false)]
public EntitySet<Reservation> Reservations
{
get
{
if ((this.serializing
&& (this._Reservations.HasLoadedOrAssignedValues == false)))
{
return null;
}
return this._Reservations;
}
set
{
this._Reservations.Assign(value);
}
}
Update 2
Here is the Reservation class which LINQ2SQL made:
Here is the fields:
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Reservation")]
[global::System.Runtime.Serialization.DataContractAttribute()]
public partial class Reservation : INotifyPropertyChanging, INotifyPropertyChanged
{
private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
private int _ResID;
private System.Nullable<int> _CustomerID;
private System.Nullable<int> _SchedulerID;
private string _Row;
private string _Seat;
private EntityRef<Customer> _Customer;
private EntityRef<Scheduler> _Scheduler;
And here is the Scheduler reference part of the class
[global::System.Data.Linq.Mapping.AssociationAttribute(Name="Scheduler_Reservation", Storage="_Scheduler", ThisKey="SchedulerID", OtherKey="SchID", IsForeignKey=true, DeleteRule="SET DEFAULT")]
public Scheduler Scheduler
{
get
{
return this._Scheduler.Entity;
}
set
{
Scheduler previousValue = this._Scheduler.Entity;
if (((previousValue != value)
|| (this._Scheduler.HasLoadedOrAssignedValue == false)))
{
this.SendPropertyChanging();
if ((previousValue != null))
{
this._Scheduler.Entity = null;
previousValue.Reservations.Remove(this);
}
this._Scheduler.Entity = value;
if ((value != null))
{
value.Reservations.Add(this);
this._SchedulerID = value.SchID;
}
else
{
this._SchedulerID = default(Nullable<int>);
}
this.SendPropertyChanged("Scheduler");
}
}
}
All of these things should lead to where I could get the object like this:
Scheduler[] schedulers = client.GetAllSchedulers();
Reservation reservation = schedulers[0].Reservations.First();
But get this error due to WCF not sending the object, (which you could see in picture one).
Which is this error:
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: Sequence contains
no elements
UPDATE 3:
Ok so it appears that it works somehow.
I just had to make a join between the Scheduler and Reservation.
Also whenever I debug the code I can see the variables are there. (Due to my reputation I can not post links).
But some of you might recognize the following whenever you try to view a result in debug mode:
"expanding the results view will enumerate the ienumerable c#"
Whenever I do this, it works, but not if I run it in release mode.
Looks like only object types (Reservation,Seat) have null values.
I'm guessing either you are missing DataContract/DataMember attributes in your complex types or you might need to include KnownTypeAttribute
It'd be easier to tell if you could provide some code.
EDIT
What your are talking about later is deferred loading. See this blog for more information on deferred vs immediate loading.
When you expand the IEnumerable in debug mode, that makes the request to retrieve/load the objects.
What your probably want is to load your Reservation,Seat objects along with your Scheduler object. Something like the following:
YourDatabaseContext database = new YourDatabaseContext ())
{
DataLoadOptions options = new DataLoadOptions();
options.LoadWith<Scheduler>(sch=> sch.Reservation);
options.LoadWith<Scheduler>(sch=> sch.Seat);
database.LoadOptions = options;
}
See DataLoadOptions for more details.
If you want to understand deferred execution. See this article for more details.
Quote from the article:
By default LINQ uses deferred query execution. This means when you write a LINQ query it doesn't execute. LINQ queries execute when you 'touch' the query results. This means you can change the underlying collection and run the same query subsequent times in the same scope. Touching the data means accessing the results, for instance in a for loop or by using an aggregate operator like Average or AsParallel on the results.

Abstraction with variables

So I'm taking a highschool online Java class and well my teacher doesn't help...
so we are learning about abstraction and I had already done this with my "alien" class that moves, he will face one way going forward and another going backward by switching two images... However when they showed the code in an example it seemed overcomplicated and I was wondering if I am just missing something.
My Code
private String avatarRight = "Alien.png";
private String avatarLeft = "Alien1.png";
/**
* Act - do whatever the Alien wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
public void act()
{
movement(avatarRight, avatarLeft);
gatherPart();
}
(Superclass containing movement method)
/**
* Sets up the movement keys and facing for the Object
*/
public void movement(String avatarRight,String avatarLeft)
{
if (atWorldEdge() == false)
{
if (Greenfoot.isKeyDown("w"))
{
setLocation(getX(), getY()-2);
}
if (Greenfoot.isKeyDown("d"))
{
setImage(avatarRight);
setLocation(getX()+2, getY());
}
if (Greenfoot.isKeyDown("s"))
{
setLocation(getX(), getY()+2);
}
if (Greenfoot.isKeyDown("a"))
{
setImage(avatarLeft);
setLocation(getX()-2, getY());
}
}
else
{
}
}
Their Code
{
private GreenfootImage image1;
private GreenfootImage image2;
private boolean isKeyDown;
private String key;
private String sound;
/**
* Create a Duke and initialize his two images. Link Duke to a specific keyboard
* key and sound.
*/
public Duke(String keyName, String soundFile)
{
key = keyName;
sound = soundFile
image1 = new GreenfootImage("Duke.png")
image3 = new GreenfootImage("duke2.png")
setImage(image1);
}
}
Where I just say avatarRight = "this image"
they say key = keyname
key = "key"
edit:
So the way the set it up and I set mine up initially was
private int rotation;
public Capsule(int rot)
{
rotation = rot
setRotation(rotation);
}
but the one below works perfectly fine, as far as I can tell. Is there any reason why I would do the above code rather than the one below
public Capsule(int rot)
{
setRotation(rot);
}
OK, based on the commentary I'm inclined to say you're not comparing the same things.
Where I just say avatarRight = "this image" they say key = keyname key
= "key"
That doesn't seem to be exactly accurate. Where you say
private String avatarRight = "Alien.png"; and
private String avatarLeft = "Alien1.png";
they have the png hard coded in the constructor as "Duke.png" and "duke2.png", which by the way contains an error because as far as I can see there's no image3.
So the keyName doesn't seem to directly map as you say it does. Perhaps you should investigate the code further to see how they use the key or provide equal code for both examples so we can further see the differences.
By looking at it perhaps there's a map somewhere and the key would be used to access the specific alien or other type of game object.
To address your edit.
Is there any reason why I would do the above code rather than the one
below
It's not possible to tell by that code if the reason has any value; it doesn't appear to by what you've shown. I can tell you that the reason I would do that is because I need that value elsewhere but not now. That could be for any number of reasons. You have to look at all the code available to you and see if they ever use that variable anywhere else without passing it in. Then you have found the reason or the lack there of.

Use MEF to compose parts but postpone the creation of the parts

As explained in these questions I'm trying to build an application that consists of a host and multiple task processing clients. With some help I have figured out how to discover and serialize part definitions so that I could store those definitions without having to have the actual runtime type loaded.
The next step I want to achieve (or next two steps really) is that I want to split the composition of parts from the actual creation and connection of the objects (represented by those parts). So if I have a set of parts then I would like to be able to do the following thing (in pseudo-code):
public sealed class Host
{
public CreationScript Compose()
{
CreationScript result;
var container = new DelayLoadCompositionContainer(
s => result = s);
container.Compose();
return script;
}
public static void Main()
{
var script = Compose();
// Send the script to the client application
SendToClient(script);
}
}
// Lives inside other application
public sealed class Client
{
public void Load(CreationScript script)
{
var container = new ScriptLoader(script);
container.Load();
}
public static void Main(string scriptText)
{
var script = new CreationScript(scriptText);
Load(script);
}
}
So that way I can compose the parts in the host application, but actually load the code and execute it in the client application. The goal is to put all the smarts of deciding what to load in one location (the host) while the actual work can be done anywhere (by the clients).
Essentially what I'm looking for is some way of getting the ComposablePart graph that MEF implicitly creates.
Now my question is if there are any bits in MEF that would allow me to implement this kind of behaviour? I suspect that the provider model may help me with this but that is a rather large and complex part of MEF so any guidelines would be helpful.
From lots of investigation it seems that is not possible to separate the composition process from the instantiation process in MEF so I have had to create my own approach for this problem. The solution assumes that the scanning of plugins results in having the type, import and export data stored somehow.
In order to compose parts you need to keep track of each part instance and how it is connected to other part instances. The simplest way to do this is to make use of a graph data structure that keeps track of which import is connected to which export.
public sealed class CompositionCollection
{
private readonly Dictionary<PartId, PartDefinition> m_Parts;
private readonly Graph<PartId, PartEdge> m_PartConnections;
public PartId Add(PartDefinition definition)
{
var id = new PartId();
m_Parts.Add(id, definition);
m_PartConnections.AddVertex(id);
return id;
}
public void Connect(
PartId importingPart,
MyImportDefinition import,
PartId exportingPart,
MyExportDefinition export)
{
// Assume that edges point from the export to the import
m_PartConnections.AddEdge(
new PartEdge(
exportingPart,
export,
importingPart,
import));
}
}
Note that before connecting two parts it is necessary to check if the import can be connected to the export. In other cases MEF does that but in this case we'll need to do that ourselves. An example of how to approach that is:
public bool Accepts(
MyImportDefinition importDefinition,
MyExportDefinition exportDefinition)
{
if (!string.Equals(
importDefinition.ContractName,
exportDefinition.ContractName,
StringComparison.OrdinalIgnoreCase))
{
return false;
}
// Determine what the actual type is we're importing. MEF provides us with
// that information through the RequiredTypeIdentity property. We'll
// get the type identity first (e.g. System.String)
var importRequiredType = importDefinition.RequiredTypeIdentity;
// Once we have the type identity we need to get the type information
// (still in serialized format of course)
var importRequiredTypeDef =
m_Repository.TypeByIdentity(importRequiredType);
// Now find the type we're exporting
var exportType = ExportedType(exportDefinition);
if (AvailableTypeMatchesRequiredType(importRequiredType, exportType))
{
return true;
}
// The import and export can't directly be mapped so maybe the import is a
// special case. Try those
Func<TypeIdentity, TypeDefinition> toDefinition =
t => m_Repository.TypeByIdentity(t);
if (ImportIsCollection(importRequiredTypeDef, toDefinition)
&& ExportMatchesCollectionImport(
importRequiredType,
exportType,
toDefinition))
{
return true;
}
if (ImportIsLazy(importRequiredTypeDef, toDefinition)
&& ExportMatchesLazyImport(importRequiredType, exportType))
{
return true;
}
if (ImportIsFunc(importRequiredTypeDef, toDefinition)
&& ExportMatchesFuncImport(
importRequiredType,
exportType,
exportDefinition))
{
return true;
}
if (ImportIsAction(importRequiredTypeDef, toDefinition)
&& ExportMatchesActionImport(importRequiredType, exportDefinition))
{
return true;
}
return false;
}
Note that the special cases (like IEnumerable<T>, Lazy<T> etc.) require determining if the importing type is based on a generic type which can be a bit tricky.
Once all the composition information is stored it is possible to do the instantiation of the parts at any point in time because all the required information is available. Instantiation requires a generous helping of reflection combined with the use of the trusty Activator class and will be left as an exercise to the reader.