How can I wait for a button press in a loop? - actionscript-2

Say I have simple program that emulates a board game with a number of players who take turns rolling dice to move across a board. The players can be human or computer.
If this was a command-line style game, I could simply make a loop to iterate over the players which would call the diceRoll function for that player.
If the player is a computer player, diceRoll simply tells the computer to roll the dice.
If the player is a human, the diceRoll will wait until a user inputs the roll command and then continues.
How can I transfer this idea to a graphic design? I don't think it makes sense to continuously check to see if the roll button has been pressed. I am working with actionscript 2, but ideas can be in whatever language you want. I'd just like some opinions on the best way to design this. I don't suppose there's some sort of 'waitForButtonPress' function that I don't know about?

I think I've found a solution that I like.
The main game class will have a nextTurn function like so:
nextTurn() {
bool guiSet = false
while (guiSet = false) {
//Get the next player
if (next player is human) {
//enable the gui (ie. the 'Roll Dice' button)
guiSet = true
} else {
//The player is a computer
//Have the computer roll the dice and make any necessary decisions
}
}
}
When a human player is finished his turn, a call will be made to nextTurn to continue the game play. When a computer finishes a turn, the flow is still in the while loop so the game will continue.

depending on the game if you have N turns and every other turn is the humans turn then you could simply call a getUserResponse() from within the loop using if elses..
for i to N
if(i%2==0)
getUserRoll()
else
getComputerRoll()
and if there's any contraints check them in the if conditon.

Related

How to change variables between scripts in UnityScript?

I made a game have two objects in the hierarchy panel. One called GameScreen and another called Clock I set up. Each has its own script attached. GameScreen uses game.js and the other uses clock.js.
When I win the game a popup box appears and says, "You've won!" This is caused by the game.js script. However, the clock.js is still running, so my clock is still counting down. When the time is up the clock.js makes a popup box saying, "you lose!"
This causes for a "you win" screen to pop up when you win and then later a you lose screen to appear. As you can probably guess, this is super annoying. If there was a way I could change variables in one script from another,, I could get the clock to stop when you won or I could get the game to stop when the time ran out.
Is there some way to do this??
For example here are two javascript files one on clock and the other on GameScreen . I want the first one to change the variable changeMe in the second to two.
1.js:
function start(){
}
2.js:
var changeMe:int;
When you win the game, you can change clock's variable from game.js this way:
GameObject.Find("Clock").GetComponent("clock.js").variable_name = new_value;
, where [variable_name] and [new_value] obviously depend on your project. variable_name has to be an exposed variable.
You can simply use SendMessage() it will make you able to call a function from another object easily.Basically you need to write a function to destroy the clock after wining the game,let's say your function is called destroyClock so you should add that to your game.js script:
gameobject.Find("here goes the name of your clock obj").sendMessage("destroyClock")

Kaltura - Force player to stop with API only?

Is there any way to force a Kaltura videoplayer to stop ONLY using code and the Kaltura API?
Currently I have solved it by adding a Access Control Profile named "Free preview" under Settings > Access Control in KMC and then added this profile to the Entries I've choosen.
I then add the session to the players flashvars to restrict non-members to only watch the preview, not the whole clip.
But I would like to restrict ALL, or even better selected Categories of clips by using only code, so I don't need to involve KMC.
Is that possible?
Alt) Can you create a new player in KMC and restrict it to viewing only X seconds, no matter what length of Entry? Then I can do the check if user is valid or not and get the category via API and show it in the "preview-player" och the "default player".
If I use the mediaProxy.mediaPlayTo attribute the clip stops, but is easily started again by presing play.
Would greatly appreciate an answer
I got this answer from a guy named oferc in a different forum:
You can listen to the head move event and pause the clip it goes beyond a certain time (then if someone pressed play, you can stop it again)
function jsCallbackReady(player_id) {
my_kdp = $("#"+player_id).get(0); // document.getElementById(player_id) if you do not use jquery/ prefer pure js
my_kdp.addJsListener("kdpReady", "kdpReady"); // when you load the player with an entry (and the player is ready to begin playing it using doPlay for instance)
}
function kdpReady() {
my_kdp.addJsListener("playerUpdatePlayhead","headMove");
}
function headMove(position) {
if (position > "30") { // Your Time, example 30 seconds
my_kdp.sendNotification('doStop')
}
}
Works like a charm!
fredrik_w - neither of the ways you chosen here are a good option to restrict access.
in both cases, your videos are made public, and can be easily accessible by anyone.
The best way to limit access to a video is by defining an Access Control, and like everything in Kaltura, you can define an ACL using API as well.
Check this out as a reference sample-
http://blog.kaltura.org/turning-profit-online-video-made-easy-using-paypal-html5-digital-goods

Objective-c -> class method to main file query

Sorry to bug twice so quickly, but since people were so kind in their informative responces, I figured it couldnt hurt to ask another question.
The same program i tried to make it rather swanky and have a main screen which allows you to click on a button which leads to a limited options screen. This lets you switch the music on or off. Or at least it should do.
The music running code is in the main file (game.m), under the following:
//Music
[Settings setMusicEnabled:YES];
music = [SPSound soundWithContentsOfFile:#"music.caf"];
channel = [[music createChannel] retain];
channel.loop = YES;
channel.volume = 0.25;
if([Settings musicEnabled]){
[channel play];
}
I apologize for the strange format, but it is Sparrow framework. basically, the Settings file contains the class methods I am trying to use. If the methods cause YES, the music is on. If it is No, then the music is off.
settings.m
static BOOL isMusicEnabled;
#implementation Settings
+ (BOOL)musicEnabled
{
return isMusicEnabled;
}
+ (void)setMusicEnabled:(BOOL)value
{
isMusicEnabled = value;
NSLog(#"SME? %i", isMusicEnabled);
}
#end
Now, the options file is working and i tested that section. The program is reading that isMusicEnabled is getting a new value, thus musicEnabled is being altered as well, so there should be a change and the music should be switched off.
However, nothing happens. I have tried to use debugger, but I am not very good at it and I dont understand a lot of the information i am given. I do understand that the problem is sending the message from Settings file to the main/Game file.
I would appriciate anyone's help who could enlighten me as to how this could be solved.
I'm not familiar with Sparrow Framework, but let me make a guess anyway.
[channel play]; starts playing the music in background until the channel is asked to stop playing.
Changing the isMusicEnabled does not trigger any code to stop the currently playing music. When you change the value in Settings, you should inform the channel to stop (most probably by somehow accessing the channel and calling [channel stop].
There's another problem - isMusicEnabled is just a variable in memory, your program will not remember its state between restarts. And Settings are usually supposed to be remembered.
To summarize I see two problems: persisting settings between restarts first and informing about change of settings second. To remember settings I suggest you look into NSUserDefaults class. To inform the channel to stop playing you have couple of options - depending on you skills. Easiest is to simply access the channel variable from within the setMusicEnabled and call stop. Another option would be to use notifications, but for a beginner programmer that is more complicated (look for NSNotificationCenter if interested).

What's the modern equivalent of GetNextEvent in Cocoa?

I'm porting an archaic C++/Carbon program to Obj-C and Cocoa. The current version uses asynchronous usb reads and GetNextEvent to read the data.
When I try to compile this in Objective C, GetNextEvent isn't found because it's in the Carbon framework.
Searching Apple support yields nothing of use.
EDIT TO ADD:
Ok, so what I'm trying to do is run a document scanner through USB. I have set up the USBDeviceInterface and the USBInterfaceInterface (who came up with THAT name???) and I call (*usbInterfaceInterface)->WritePipeTO() to ask the scanner to scan. I believe this works. AT least the flatbed light moves across the page...
Then I try to use *(usbInterfaceInterface))->ReadPipeAsyncTO() to read data. I give this function a callback function, USBDoneProc().
The general structure is:
StartScan()
WaitForScan()
StartScan() calls the WritePipeTO and the ReadPipeAsyncTO
WaitForScan() has this:
while (deviceActive) {
EventRecord event;
GetNextEvent(0,&event);
if (gDataPtr != saveDataPtr) { // more data up the timeout
timeoutTicks = TickCount() + 60 * 60;
saveDataPtr = gDataPtr;
}
if (TickCount() > timeoutTicks) {
deviceActive = false;
}
}
Meanwhile, USBDoneProc incrementing gDataPtr to be the end of the data that we've read so far. It gets called several times during the asynchronous read, called automatically by the callback, as far as I can tell.
If I cake out the GetNextEvent() call in the WORKING code the USBDoneProc doesn't get called until the asynchronous readpipe timesout.
So it looks to me that I need something to give control back to the event handler so that the USBRead interrupts can actually interrupt and make the USBDoneProcget called...
Does that make any sense?
thanks.
I suppose the nearest thing to a Cocoa equivalent would be -[NSApplication nextEventMatchingMask:untilDate:inMode:dequeue:]. But bear in mind that GetNextEvent is archaic even for Carbon. The preferred way of handing events is the "don't call us, we'll call you" scheme, where the app calls NSApplicationMain or RunApplicationEventLoop and events are dispatched to you.
EDIT to add: Does you app have a normal event loop? If so, maybe WaitForScan could start a Carbon timer and return to the event loop. Each time the timer fires, do what you did in the WaitForScan loop.
there is a USB hidapi that works for mac on windows.
http://www.signal11.us/oss/hidapi/
may this could be of help to you?
It works fine (I can list the connected USB devices and connect/write/read to a device);
however, if i USB device is connected/disconnected during the runtime of the application, I don't see the new connected/disconnected devices.
See: https://github.com/signal11/hidapi/issues/14
If I add the following code to hidapi, then hidapi detects the new USB devices.
#include <Carbon/Carbon.h>
void check_apple_events() {
printf("check_apple_events\n");
RgnHandle cursorRgn = NULL;
Boolean gotEvent=TRUE;
EventRecord event;
while (gotEvent) {
gotEvent = WaitNextEvent(everyEvent, &event, 0L, cursorRgn);
}
}
I need to compile this on OSX10.5 because it uses Carbon instead of Cocoa.
I am currently looking how to transform this to Cocoa.
you are also trying to move your code to cocoa, right?
let me know if you find out; I'll post it here if I get it.
regards,
David
Have you considered throwing the whole thing out and using Image Kit's new-in-10.6 scanner support instead? Even if it's custom, writing a TWAIN driver for it might be easier (and is certainly better) than trying to twist Cocoa into a GetNextEvent shape.

How do I pause a function in c or objective-c on mac without using sleep()

Hi I would like to pause the execution of a function in an cocoa project. I dont want to use sleep() because the function needs to resume after user interaction. I also want to avoid doing this with multiple calls to sleep.
Thanks for your responses. Ok I started the code while waiting for some answers. I then realized that sleep or pause would not be usefull to me because it freeses my whole program. I think I might have to do some threading. Here is the situation:
I have a program that uses coreplot. I also use it to debug and develop algorithms so I do lots of plots while the data is being processed (ie in the midfle of the code but I need the flexibility to put it anywhaere so I cant separate my function). I was able to do this with NSRunAlertPanel but having a message box like that doesnt make it very presentable and I cant do much with the main window while an alert is open.
I hope I am not too confusing with my explanation but if I am ill try to one line it here:
I would like to interact with my cocoa interface while one of my functions is stopped in the middle of what it is doing.
Its sounds to me like you're looking for -NSRunLoop runUntilDate:
Apple's Docs: runUntilDate
This code will cause the execution within your method to pause but still let other events like timers and user input occur:
while ( functionShouldPause )
{
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]];
}
Switching functionShouldPause back to false will allow the rest of the method to execute.
It seems more like you are interested in reacting to user events rather than "pausing" the function. You would probably want to put the code that you want to execute into another function that is called as a result of the user's actions.
In C you can use the pause() function in <unistd.h>. This causes the calling program to suspend until it receives a signal, at which point the pause call will return and your program will continue (or call a signal handler; depending on what signal was received).
So it sounds like you want to break the function into two parts; the bit that happens before the sleep and the bit that happens afterward. Before going to sleep, register for a notification that calls the "after" code, and can be triggered by the UI (by an IBAction connected to whatever UI element). Now instead of calling sleep(), run the run loop for the period you want to go to sleep for, then after that has returned post the "after" notification. In the "after" code, remove the object as an observer for that notification. Now, whichever happens first - the time runs out or the user interrupts you - you get to run the "after" code.
Isn't there a clock or timer function? When your button is pressed start running a loop like timeTillAction = 10 and do a loop of timeTillAction = timeTillAction - 1 until it reaches 0 then run whatever code after the 10 seconds.
Sorry if this isn't well explained.