VB: Encapsulating an Application Object with a Process
I am starting an external application from Visual Basic to perform CPU and
memory intensive computations. The code more or less looks like the
following:
gApp = New CANoe.ApplicationgApp = New CANoe.Application
While gApp Is Nothing 'wait until CANoe started
Threading.Thread.Sleep(100)
End While
gApp.Open(canoeConfigFile, False, False)
gApp.Configuration.OfflineSetup.Source = dataFile
gMeasurement.Start()
While (gMeasurement.Running)
Threading.Thread.Sleep(1000)
End While
gApp.Quit()
Would it be possible to encapsulate the above code into a process? I am
ultematelly looking for something like:
Dim canoeProcess As New Process
canoeProcess.StartInfo.FileName = "C:\Program Files (x86)\Vector CANoe
8.1\Exec32\CANoe32.exe"
canoeProcess.Start()
gApp = canoeProcess.Application
...
' (the code continues as the above)
...
The reason why I want to encapusalte the application into the process is
that (i) I want to run muliple instances of the executable with different
dataFiles as jobs and (ii) in case the canoe software hangs or does
something weird I'd like to be able to kill the process from the VB
application.
Is it possible to achieve the reverse? I.e., giving gApp Application
object (that is running) to get its Process ID?
Any comments?
Monday, 2 September 2013
Step 3 of Angular.js tutorial
Step 3 of Angular.js tutorial
I am on step 3 of the angular tutorial. I've gotten everything to work
before step 3. However, on step 3, when I run ./scripts/e2e-test.sh, I get
the following error:
Uncaught ReferenceError: describe is not defined
I believe it is referring to scenarios.js. Any help would be most
appreciated.
I am on step 3 of the angular tutorial. I've gotten everything to work
before step 3. However, on step 3, when I run ./scripts/e2e-test.sh, I get
the following error:
Uncaught ReferenceError: describe is not defined
I believe it is referring to scenarios.js. Any help would be most
appreciated.
IOS error while using a search bar
IOS error while using a search bar
Hi in my app I've a TableView in which I show something and I want to
search in this TableView for a text I write in the search bar, so I
followed this tutorial. In my app I'm having a problem, when I run the app
and I try to search a letter it crash and in xCode I see this information:
Terminating app due to uncaught exception 'NSUnknownKeyException', reason:
'[<__NSCFString 0x9e45990> valueForUndefinedKey:]: this class is not key
value coding-compliant for the key name.'. I checked my Storyboard to see
if I have something wrong, but it's all ok. So I guess the problem it's in
the code, I will post here my code and I hope you can help me what's
wrong.
#import "TableWasteViewController.h"
#import "WasteXmlParser.h"
#import "WasteDetailViewController.h"
@interface TableWasteViewController ()
@property(nonatomic,strong)NSArray *arrayWastes;
@property(nonatomic,strong)NSMutableArray *typeOfWaste;
@property(nonatomic,strong)NSMutableArray *typeOfBin;
@property(nonatomic,strong)NSMutableArray *indexWastes;
@property(nonatomic,strong)NSMutableArray *typeOfWasteBackup;
@end
@implementation TableWasteViewController
@synthesize searchBar;
@synthesize filteredWasteArray;
@synthesize typeOfWaste;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle
*)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
WasteXmlParser *parser = [[WasteXmlParser alloc]init];
[parser parseWasteXml];
self.arrayWastes = [[NSArray alloc]init];
self.arrayWastes = [parser.arrayWastes mutableCopy];
self.indexWastes = [[NSMutableArray alloc]init];
typeOfWaste = [[NSMutableArray alloc]init];
self.typeOfBin = [[NSMutableArray alloc]init];
for (int i = 0; i < [self.arrayWastes count]; i++) {
[typeOfWaste addObject:[self.arrayWastes[i] objectForKey:@"type"]];
}
self.filteredWasteArray = [NSMutableArray
arrayWithCapacity:[self.typeOfWaste count]];
self.typeOfWasteBackup = [self.typeOfWaste mutableCopy];
}
#pragma mark Content Filtering
- (void)filterContentForSearchText:(NSString*)searchText
scope:(NSString*)scope {
[self.filteredWasteArray removeAllObjects];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.name
contains[c] %@", searchText];
filteredWasteArray = [NSMutableArray arrayWithArray:[typeOfWaste
filteredArrayUsingPredicate:predicate]];
}
#pragma mark - UISearchDisplayController Delegate Methods
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString {
[self filterContentForSearchText:searchString scope:
[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchScope:(NSInteger)searchOption {
[self
filterContentForSearchText:self.searchDisplayController.searchBar.text
scope:
[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:searchOption]];
return YES;
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
//return self.arrayWastes.count;
if (self.tableWaste ==
self.searchDisplayController.searchResultsTableView) {
return [filteredWasteArray count];
} else {
return [self.arrayWastes count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
UIFont *myFont = [UIFont fontWithName:@"Arial" size:14.0];
if (cell == nil) {
cell = [[UITableViewCell
alloc]initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
cell.textLabel.font = myFont;
cell.textLabel.numberOfLines = 2;
//cell.textLabel.text =
[self.arrayWastes[indexPath.row]objectForKey:@"type"];
if (self.tableWaste ==
self.searchDisplayController.searchResultsTableView) {
cell.textLabel.text =
[self.filteredWasteArray[indexPath.row]objectForKey:@"type"];
} else {
cell.textLabel.text =
[self.arrayWastes[indexPath.row]objectForKey:@"type"];
}
return cell;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
NSIndexPath *indexPath = [self.tableWaste indexPathForSelectedRow];
WasteDetailViewController *vc = segue.destinationViewController;
vc.typeOfWaste = [self.arrayWastes[indexPath.row]objectForKey:@"type"];
vc.typeOfBin = [self.arrayWastes[indexPath.row]objectForKey:@"place"];
vc.urlPic = [self.arrayWastes[indexPath.row]objectForKey:@"imgUrl"];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (IBAction)backToHome:(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
@end
Thank you!
Hi in my app I've a TableView in which I show something and I want to
search in this TableView for a text I write in the search bar, so I
followed this tutorial. In my app I'm having a problem, when I run the app
and I try to search a letter it crash and in xCode I see this information:
Terminating app due to uncaught exception 'NSUnknownKeyException', reason:
'[<__NSCFString 0x9e45990> valueForUndefinedKey:]: this class is not key
value coding-compliant for the key name.'. I checked my Storyboard to see
if I have something wrong, but it's all ok. So I guess the problem it's in
the code, I will post here my code and I hope you can help me what's
wrong.
#import "TableWasteViewController.h"
#import "WasteXmlParser.h"
#import "WasteDetailViewController.h"
@interface TableWasteViewController ()
@property(nonatomic,strong)NSArray *arrayWastes;
@property(nonatomic,strong)NSMutableArray *typeOfWaste;
@property(nonatomic,strong)NSMutableArray *typeOfBin;
@property(nonatomic,strong)NSMutableArray *indexWastes;
@property(nonatomic,strong)NSMutableArray *typeOfWasteBackup;
@end
@implementation TableWasteViewController
@synthesize searchBar;
@synthesize filteredWasteArray;
@synthesize typeOfWaste;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle
*)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
WasteXmlParser *parser = [[WasteXmlParser alloc]init];
[parser parseWasteXml];
self.arrayWastes = [[NSArray alloc]init];
self.arrayWastes = [parser.arrayWastes mutableCopy];
self.indexWastes = [[NSMutableArray alloc]init];
typeOfWaste = [[NSMutableArray alloc]init];
self.typeOfBin = [[NSMutableArray alloc]init];
for (int i = 0; i < [self.arrayWastes count]; i++) {
[typeOfWaste addObject:[self.arrayWastes[i] objectForKey:@"type"]];
}
self.filteredWasteArray = [NSMutableArray
arrayWithCapacity:[self.typeOfWaste count]];
self.typeOfWasteBackup = [self.typeOfWaste mutableCopy];
}
#pragma mark Content Filtering
- (void)filterContentForSearchText:(NSString*)searchText
scope:(NSString*)scope {
[self.filteredWasteArray removeAllObjects];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.name
contains[c] %@", searchText];
filteredWasteArray = [NSMutableArray arrayWithArray:[typeOfWaste
filteredArrayUsingPredicate:predicate]];
}
#pragma mark - UISearchDisplayController Delegate Methods
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString {
[self filterContentForSearchText:searchString scope:
[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchScope:(NSInteger)searchOption {
[self
filterContentForSearchText:self.searchDisplayController.searchBar.text
scope:
[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:searchOption]];
return YES;
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
//return self.arrayWastes.count;
if (self.tableWaste ==
self.searchDisplayController.searchResultsTableView) {
return [filteredWasteArray count];
} else {
return [self.arrayWastes count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
UIFont *myFont = [UIFont fontWithName:@"Arial" size:14.0];
if (cell == nil) {
cell = [[UITableViewCell
alloc]initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
cell.textLabel.font = myFont;
cell.textLabel.numberOfLines = 2;
//cell.textLabel.text =
[self.arrayWastes[indexPath.row]objectForKey:@"type"];
if (self.tableWaste ==
self.searchDisplayController.searchResultsTableView) {
cell.textLabel.text =
[self.filteredWasteArray[indexPath.row]objectForKey:@"type"];
} else {
cell.textLabel.text =
[self.arrayWastes[indexPath.row]objectForKey:@"type"];
}
return cell;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
NSIndexPath *indexPath = [self.tableWaste indexPathForSelectedRow];
WasteDetailViewController *vc = segue.destinationViewController;
vc.typeOfWaste = [self.arrayWastes[indexPath.row]objectForKey:@"type"];
vc.typeOfBin = [self.arrayWastes[indexPath.row]objectForKey:@"place"];
vc.urlPic = [self.arrayWastes[indexPath.row]objectForKey:@"imgUrl"];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (IBAction)backToHome:(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
@end
Thank you!
Selecting distinct values for multiple columns in Single Row
Selecting distinct values for multiple columns in Single Row
I have a SQL table called "calculation" that looks like this:
id | InsulationMaterialId1 | InsulationMaterialId2| InsulationMaterialId3
| InsulationMaterialId4
-----------------------
1 | 34 | 45 | 34 | 50
2 | 34 | 78 | 35 | 51
3 | 35 | 32 | 34 | 52
4 | 36 | 30 | 34 | 53
5 | 40 | 39 | 34 | 34
6 | 41 | 34 | 34 | 56
7 | 42 | 36 | 34 | 53
In these table , we have 4 columns with insulation ids , I want to get
unique insulation ids in one single column with ',' separated means Output
like this :-
id | InsulationMaterialIds
-----------------------
1 | 34,45,50
2 | 34,78,35,51
3 | 35,32,34,52
4 | 36,30,34,53
5 | 40,39,34
6 | 41,34,56
7 | 42,36,34,53
I have a SQL table called "calculation" that looks like this:
id | InsulationMaterialId1 | InsulationMaterialId2| InsulationMaterialId3
| InsulationMaterialId4
-----------------------
1 | 34 | 45 | 34 | 50
2 | 34 | 78 | 35 | 51
3 | 35 | 32 | 34 | 52
4 | 36 | 30 | 34 | 53
5 | 40 | 39 | 34 | 34
6 | 41 | 34 | 34 | 56
7 | 42 | 36 | 34 | 53
In these table , we have 4 columns with insulation ids , I want to get
unique insulation ids in one single column with ',' separated means Output
like this :-
id | InsulationMaterialIds
-----------------------
1 | 34,45,50
2 | 34,78,35,51
3 | 35,32,34,52
4 | 36,30,34,53
5 | 40,39,34
6 | 41,34,56
7 | 42,36,34,53
Sunday, 1 September 2013
how to calculate the distance between two points and find the fare accordingly
how to calculate the distance between two points and find the fare
accordingly
jcJobNo.setText(Contsants.Jobno);
jcStartTime.setText(Contsants.jobStartTime);
jcEndTime.setText(Contsants.jobEndTime);
// total distance finding here
float totalKm = Contsants.jobEndKm-Contsants.jobStartKm;
jcTotalKms.setText(Float.toString(totalKm));
//jcTotalKms.setText(Float.toString((float) (totalKm/16.0)));
//finding total fare here
float totalfare=totalKm *16;
jcTotalFare.setText(Float.toString(totalfare));
here is a simple code for calculating the distance between two points and
calculate the fare according to the distance. But i din't get exact fare
value and the output is in negative. I don't know how to resolve this
error. If any one knows please help me.
accordingly
jcJobNo.setText(Contsants.Jobno);
jcStartTime.setText(Contsants.jobStartTime);
jcEndTime.setText(Contsants.jobEndTime);
// total distance finding here
float totalKm = Contsants.jobEndKm-Contsants.jobStartKm;
jcTotalKms.setText(Float.toString(totalKm));
//jcTotalKms.setText(Float.toString((float) (totalKm/16.0)));
//finding total fare here
float totalfare=totalKm *16;
jcTotalFare.setText(Float.toString(totalfare));
here is a simple code for calculating the distance between two points and
calculate the fare according to the distance. But i din't get exact fare
value and the output is in negative. I don't know how to resolve this
error. If any one knows please help me.
Ok in simulator but throwing exception in ios device
Ok in simulator but throwing exception in ios device
when i am running my app in the simulator everything is working perfectly
.But when i running the same app in the Ipad exception is being thrown.
Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: 'data parameter is nil. In my app at one step i have to request a
web-URl and need to parsed the returned JSON response. But I have checked
the web-url and have been able to parse perfectly in simulator. But all
the problem has been arisen in real ios device.But I think i have
identified the code where it is getting wrong.
+ (NSDictionary*) getParsedJSON:(NSString*) urlString {
NSLog(@"################################################################################");
NSLog(@"getParsedJSON => urlString:");
NSLog(@"%@", urlString);
NSURL* url = [NSURL URLWithString:urlString];
NSURLRequest* request = [NSURLRequest requestWithURL:url];
NSURLResponse *response1 = nil;
NSError *error = nil;
NSData* response = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response1 error:&error];
//NSData* response = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
NSLog(@"--------------------------------------------------------------------------------");
NSString* responseString = [[NSString alloc] initWithData:response
encoding:NSUTF8StringEncoding];
NSLog(@"getParsedJSON => responseString:\n%@", responseString);
NSLog(@"--------------------------------------------------------------------------------");
NSError* jsonParsingError = nil;
NSDictionary* parsedJSON = [NSJSONSerialization
JSONObjectWithData:response options:0 error:&jsonParsingError]; // here is
place where exception seems to be thrown.
if (jsonParsingError) {
NSLog(@"ERROR in parsing JSON: %@", jsonParsingError);
} else {
NSLog(@"getParsedJSON => parsedJSON: \n%@", [parsedJSON description]);
}
NSLog(@"################################################################################");
return parsedJSON;
}
I have identified the line where it seems to be wrong .I have also
attached screen shot of the exception report..Hoping for your experienced
reply.
when i am running my app in the simulator everything is working perfectly
.But when i running the same app in the Ipad exception is being thrown.
Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: 'data parameter is nil. In my app at one step i have to request a
web-URl and need to parsed the returned JSON response. But I have checked
the web-url and have been able to parse perfectly in simulator. But all
the problem has been arisen in real ios device.But I think i have
identified the code where it is getting wrong.
+ (NSDictionary*) getParsedJSON:(NSString*) urlString {
NSLog(@"################################################################################");
NSLog(@"getParsedJSON => urlString:");
NSLog(@"%@", urlString);
NSURL* url = [NSURL URLWithString:urlString];
NSURLRequest* request = [NSURLRequest requestWithURL:url];
NSURLResponse *response1 = nil;
NSError *error = nil;
NSData* response = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response1 error:&error];
//NSData* response = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
NSLog(@"--------------------------------------------------------------------------------");
NSString* responseString = [[NSString alloc] initWithData:response
encoding:NSUTF8StringEncoding];
NSLog(@"getParsedJSON => responseString:\n%@", responseString);
NSLog(@"--------------------------------------------------------------------------------");
NSError* jsonParsingError = nil;
NSDictionary* parsedJSON = [NSJSONSerialization
JSONObjectWithData:response options:0 error:&jsonParsingError]; // here is
place where exception seems to be thrown.
if (jsonParsingError) {
NSLog(@"ERROR in parsing JSON: %@", jsonParsingError);
} else {
NSLog(@"getParsedJSON => parsedJSON: \n%@", [parsedJSON description]);
}
NSLog(@"################################################################################");
return parsedJSON;
}
I have identified the line where it seems to be wrong .I have also
attached screen shot of the exception report..Hoping for your experienced
reply.
Python 2: Best way to terminate WXWidgets app main thread when user closes app?
Python 2: Best way to terminate WXWidgets app main thread when user closes
app?
The situation is this:
I'm writing a simple game using WXWidgets. The logic I have is that the
game's main routine first launches the GUI, and then spawns a new separate
thread to actually run the game's logic. The game logic runs sequentially,
occasionally (but not very frequently) accepting input from the user via
the GUI and updating the GUI with game data. The game uses a lot of audio
so the GUI itself is not being manipulated much.
The game thread often does things that must block - and this is
appropriate given that this is a game. AI computations, loading data from
the Internet, etc. all cause the game thread to block. This is fine since
the game thread manages the UI to make sure users can't manipulate the UI
in any situation where the game thread might not be able to respond.
The problem arises if the user hits Alt+F4 or Command-Q to exit the app
completely. This causes the main GUI to close, but it obviously does not
kill the game logic thread. The game thread continues running in the
background, now disconnected from the UI, and as soon as it tries to
interact with the UI it will crash (as would be expected in that
situation).
What I am looking to do is to have a way to signal to the thread that the
user has exited the app - BUT - without having to litter my code with tons
of "check if the user closed the GUI" routines. First of all, that method
wouldn't even always work since, as I said, often the game thread blocks
while it is doing something and thus several seconds could go by where
such a call never gets checked.
Since the game thread starts out as a function, I was thinking a good way
to possibly solve this would be if there is some way for me to cause a
custom exception to be raised on the thread. I could then write a simple
wrapper function would wrap the main game function inside a try block,
specifically looking for that exception. If that exception is raised, I
could then gracefully close sockets, shut down AI players, etc. as
necessary, then gracefully exit the thread.
Is there a way to cause something like this to happen?
Here is some very rough pseudocode to illustrate the problem:
Currently:
def PlayGame(self):
# Get the game ready
self.initGame()
# Go into a loop to run the game
while (True):
# Get user's move
move = self.GUI_GetMove()
# Act based on the move
gameOver = self.processMove(move)
# If we got True, game is over.
if (gameOver == True): return
# Run the AI's logic - THIS MIGHT BLOCK AS THE AI PROCESSES AND/OR
# GRABS STUFF OFF THE INTERNET ETC.
move = self.AI_GetMove()
# Act based on the move
gameOver = self.processMove(move)
# (Let's pretend in this game the AI never ends the game)
continue
Very ugly method:
def PlayGame(self):
# Get the game ready
self.initGame()
# Go into a loop to run the game
while (True):
# Get user's move
move = self.GUI_GetMove()
if (move == "EXIT" or self.GUI_Exited == True):
return
# Act based on the move
gameOver = self.processMove(move)
# If we got True, game is over.
if (gameOver == True): return
if (self.GUI_Exited == True):
return
# Run the AI's logic - THIS MIGHT BLOCK AS THE AI PROCESSES AND/OR
# GRABS STUFF OFF THE INTERNET ETC.
move = self.AI_GetMove()
# self.AI_GetMove might take 10 or more seconds - game will appear to
# be STUCK if user exits during an AI Process!
if (self.GUI_Exited == True):
return
# Act based on the move
gameOver = self.processMove(move)
if (self.GUI_Exited == True):
return
# (Let's pretend in this game the AI never ends the game)
continue
# That self.GUI_Exited code is duplicated SO many times - making
# this an awfully ugly and confusing block of code! In the real
# app, the check might need to be duplicated 100+ times!!!
What I'd like to be able to do:
def PlayGame(self):
try:
self._PlayGame()
except UserExitedApplicationError:
self.AI.Stop()
self.sockets.closeAll()
return # return gracefully so thread exits
(Remember a lot of that is not real code or functions - this just gives
you the idea of what I was thinking would be a good solution)
app?
The situation is this:
I'm writing a simple game using WXWidgets. The logic I have is that the
game's main routine first launches the GUI, and then spawns a new separate
thread to actually run the game's logic. The game logic runs sequentially,
occasionally (but not very frequently) accepting input from the user via
the GUI and updating the GUI with game data. The game uses a lot of audio
so the GUI itself is not being manipulated much.
The game thread often does things that must block - and this is
appropriate given that this is a game. AI computations, loading data from
the Internet, etc. all cause the game thread to block. This is fine since
the game thread manages the UI to make sure users can't manipulate the UI
in any situation where the game thread might not be able to respond.
The problem arises if the user hits Alt+F4 or Command-Q to exit the app
completely. This causes the main GUI to close, but it obviously does not
kill the game logic thread. The game thread continues running in the
background, now disconnected from the UI, and as soon as it tries to
interact with the UI it will crash (as would be expected in that
situation).
What I am looking to do is to have a way to signal to the thread that the
user has exited the app - BUT - without having to litter my code with tons
of "check if the user closed the GUI" routines. First of all, that method
wouldn't even always work since, as I said, often the game thread blocks
while it is doing something and thus several seconds could go by where
such a call never gets checked.
Since the game thread starts out as a function, I was thinking a good way
to possibly solve this would be if there is some way for me to cause a
custom exception to be raised on the thread. I could then write a simple
wrapper function would wrap the main game function inside a try block,
specifically looking for that exception. If that exception is raised, I
could then gracefully close sockets, shut down AI players, etc. as
necessary, then gracefully exit the thread.
Is there a way to cause something like this to happen?
Here is some very rough pseudocode to illustrate the problem:
Currently:
def PlayGame(self):
# Get the game ready
self.initGame()
# Go into a loop to run the game
while (True):
# Get user's move
move = self.GUI_GetMove()
# Act based on the move
gameOver = self.processMove(move)
# If we got True, game is over.
if (gameOver == True): return
# Run the AI's logic - THIS MIGHT BLOCK AS THE AI PROCESSES AND/OR
# GRABS STUFF OFF THE INTERNET ETC.
move = self.AI_GetMove()
# Act based on the move
gameOver = self.processMove(move)
# (Let's pretend in this game the AI never ends the game)
continue
Very ugly method:
def PlayGame(self):
# Get the game ready
self.initGame()
# Go into a loop to run the game
while (True):
# Get user's move
move = self.GUI_GetMove()
if (move == "EXIT" or self.GUI_Exited == True):
return
# Act based on the move
gameOver = self.processMove(move)
# If we got True, game is over.
if (gameOver == True): return
if (self.GUI_Exited == True):
return
# Run the AI's logic - THIS MIGHT BLOCK AS THE AI PROCESSES AND/OR
# GRABS STUFF OFF THE INTERNET ETC.
move = self.AI_GetMove()
# self.AI_GetMove might take 10 or more seconds - game will appear to
# be STUCK if user exits during an AI Process!
if (self.GUI_Exited == True):
return
# Act based on the move
gameOver = self.processMove(move)
if (self.GUI_Exited == True):
return
# (Let's pretend in this game the AI never ends the game)
continue
# That self.GUI_Exited code is duplicated SO many times - making
# this an awfully ugly and confusing block of code! In the real
# app, the check might need to be duplicated 100+ times!!!
What I'd like to be able to do:
def PlayGame(self):
try:
self._PlayGame()
except UserExitedApplicationError:
self.AI.Stop()
self.sockets.closeAll()
return # return gracefully so thread exits
(Remember a lot of that is not real code or functions - this just gives
you the idea of what I was thinking would be a good solution)
Subscribe to:
Posts (Atom)