UISegemnted COntrol - selecting 3rd segment activates second segment - controls

I have a segmented control with 3 defined segments. i am looking to capture the segment index so I can use it in an if statement to update variables accordingly as such:
-(IBAction)numPlayers:(id)sender;
{
numPlayersSegment = [(UISegmentedControl *)sender retain];
if (numPlayersSegment.selectedSegmentIndex == 0)
{
numOfPlayers = 2;
}
else if (numPlayersSegment.selectedSegmentIndex = 1)
{
numOfPlayers = 3;
}
else if (numPlayersSegment.selectedSegmentIndex = 2)
{
numOfPlayers = 4;
}
else if (numPlayersSegment.selectedSegmentIndex = -1)
{
numOfPlayers = 0;
}
NSLog(#"Players selected = %d", numPlayersSegment.selectedSegmentIndex);
However whenever I press the third segment (index 2) it returns the value of the second segment (index 1) and also highlights the 2nd segment. I can see nothing untoward in IB.
Has anybody seen this and have any suggestions.
I am using xcode 3.2.1 on snow leopard
thanks

== and = don't function the same. At a minimum you should fix that. You also don't want the added retain to sender.

Related

Algorithm / data structure for resolving nested interpolated values in this example?

I am working on a compiler and one aspect currently is how to wait for interpolated variable names to be resolved. So I am wondering how to take a nested interpolated variable string and build some sort of simple data model/schema for unwrapping the evaluated string so to speak. Let me demonstrate.
Say we have a string like this:
foo{a{x}-{y}}-{baz{one}-{two}}-foo{c}
That has 1, 2, and 3 levels of nested interpolations in it. So essentially it should resolve something like this:
wait for x, y, one, two, and c to resolve.
when both x and y resolve, then resolve a{x}-{y} immediately.
when both one and two resolve, resolve baz{one}-{two}.
when a{x}-{y}, baz{one}-{two}, and c all resolve, then finally resolve the whole expression.
I am shaky on my understanding of the logic flow for handling something like this, wondering if you could help solidify/clarify the general algorithm (high level pseudocode or something like that). Mainly just looking for how I would structure the data model and algorithm so as to progressively evaluate when the pieces are ready.
I'm starting out trying and it's not clear what to do next:
{
dependencies: [
{
path: [x]
},
{
path: [y]
}
],
parent: {
dependency: a{x}-{y} // interpolated term
parent: {
dependencies: [
{
}
]
}
}
}
Some sort of tree is probably necessary, but I am having trouble figuring out what it might look like, wondering if you could shed some light on that with some pseudocode (or JavaScript even).
watch the leaf nodes at first
then, when the children of a node are completed, propagate upward to resolving the next parent node. This would mean once x and y are done, it could resolve a{x}-{y}, but then wait until the other nodes are ready before doing the final top-level evaluation.
You can just simulate it by sending "events" to the system theoretically, like:
ready('y')
ready('c')
ready('x')
ready('a{x}-{y}')
function ready(variable) {
if ()
}
...actually that may not work, not sure how to handle the interpolated nodes in a hacky way like that. But even a high level description of how to solve this would be helpful.
export type SiteDependencyObserverParentType = {
observer: SiteDependencyObserverType
remaining: number
}
export type SiteDependencyObserverType = {
children: Array<SiteDependencyObserverType>
node: LinkNodeType
parent?: SiteDependencyObserverParentType
path: Array<string>
}
(What I'm currently thinking, some TypeScript)
Here is an approach in JavaScript:
Parse the input string to create a Node instance for each {} term, and create parent-child dependencies between the nodes.
Collect the leaf Nodes of this tree as the tree is being constructed: group these leaf nodes by their identifier. Note that the same identifier could occur multiple times in the input string, leading to multiple Nodes. If a variable x is resolved, then all Nodes with that name (the group) will be resolved.
Each node has a resolve method to set its final value
Each node has a notify method that any of its child nodes can call in order to notify it that the child has been resolved with a value. This may (or may not yet) lead to a cascading call of resolve.
In a demo, a timer is set up that at every tick will resolve a randomly picked variable to some number
I think that in your example, foo, and a might be functions that need to be called, but I didn't elaborate on that, and just considered them as literal text that does not need further treatment. It should not be difficult to extend the algorithm with such function-calling features.
class Node {
constructor(parent) {
this.source = ""; // The slice of the input string that maps to this node
this.texts = []; // Literal text that's not part of interpolation
this.children = []; // Node instances corresponding to interpolation
this.parent = parent; // Link to parent that should get notified when this node resolves
this.value = undefined; // Not yet resolved
}
isResolved() {
return this.value !== undefined;
}
resolve(value) {
if (this.isResolved()) return; // A node is not allowed to resolve twice: ignore
console.log(`Resolving "${this.source}" to "${value}"`);
this.value = value;
if (this.parent) this.parent.notify();
}
notify() {
// Check if all dependencies have been resolved
let value = "";
for (let i = 0; i < this.children.length; i++) {
const child = this.children[i];
if (!child.isResolved()) { // Not ready yet
console.log(`"${this.source}" is getting notified, but not all dependecies are ready yet`);
return;
}
value += this.texts[i] + child.value;
}
console.log(`"${this.source}" is getting notified, and all dependecies are ready:`);
this.resolve(value + this.texts.at(-1));
}
}
function makeTree(s) {
const leaves = {}; // nodes keyed by atomic names (like "x" "y" in the example)
const tokens = s.split(/([{}])/);
let i = 0; // Index in s
function dfs(parent=null) {
const node = new Node(parent);
const start = i;
while (tokens.length) {
const token = tokens.shift();
i += token.length;
if (token == "}") break;
if (token == "{") {
node.children.push(dfs(node));
} else {
node.texts.push(token);
}
}
node.source = s.slice(start, i - (tokens.length ? 1 : 0));
if (node.children.length == 0) { // It's a leaf
const label = node.texts[0];
leaves[label] ??= []; // Define as empty array if not yet defined
leaves[label].push(node);
}
return node;
}
dfs();
return leaves;
}
// ------------------- DEMO --------------------
let s = "foo{a{x}-{y}}-{baz{one}-{two}}-foo{c}";
const leaves = makeTree(s);
// Create a random order in which to resolve the atomic variables:
function shuffle(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
[array[j], array[i]] = [array[i], array[j]];
}
return array;
}
const names = shuffle(Object.keys(leaves));
// Use a timer to resolve the variables one by one in the given random order
let index = 0;
function resolveRandomVariable() {
if (index >= names.length) return; // all done
console.log("\n---------------- timer tick --------------");
const name = names[index++];
console.log(`Variable ${name} gets a value: "${index}". Calling resolve() on the connected node instance(s):`);
for (const node of leaves[name]) node.resolve(index);
setTimeout(resolveRandomVariable, 1000);
}
setTimeout(resolveRandomVariable, 1000);
your idea of building a dependency tree it's really likeable.
Anyway I tryed to find a solution as simplest possible.
Even if it already works, there are many optimizations possible, take this just as proof of concept.
The background idea it's produce a List of Strings which you can read in order where each element it's what you need to solve progressively. Each element might be mandatory to solve something that come next in the List, hence for the overall expression. Once you solved all the chunks you have all pieces to solve your original expression.
It's written in Java, I hope it's understandable.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
public class StackOverflow {
public static void main(String[] args) {
String exp = "foo{a{x}-{y}}-{baz{one}-{two}}-foo{c}";
List<String> chunks = expToChunks(exp);
//it just reverse the order of the list
Collections.reverse(chunks);
System.out.println(chunks);
//output -> [c, two, one, baz{one}-{two}, y, x, a{x}-{y}]
}
public static List<String> expToChunks(String exp) {
List<String> chunks = new ArrayList<>();
//this first piece just find the first inner open parenthesys and its relative close parenthesys
int begin = exp.indexOf("{") + 1;
int numberOfParenthesys = 1;
int end = -1;
for(int i = begin; i < exp.length(); i++) {
char c = exp.charAt(i);
if (c == '{') numberOfParenthesys ++;
if (c == '}') numberOfParenthesys --;
if (numberOfParenthesys == 0) {
end = i;
break;
}
}
//this if put an end to recursive calls
if(begin > 0 && begin < exp.length() && end > 0) {
//add the chunk to the final list
String substring = exp.substring(begin, end);
chunks.add(substring);
//remove from the starting expression the already considered chunk
String newExp = exp.replace("{" + substring + "}", "");
//recursive call for inner element on the chunk found
chunks.addAll(Objects.requireNonNull(expToChunks(substring)));
//calculate other chunks on the remained expression
chunks.addAll(Objects.requireNonNull(expToChunks(newExp)));
}
return chunks;
}
}
Some details on the code:
The following piece find the begin and the end index of the first outer chunk of expression. The background idea is: in a valid expression the number of open parenthesys must be equal to the number of closing parenthesys. The count of open(+1) and close(-1) parenthesys can't ever be negative.
So using that simple loop once I find the count of parenthesys to be 0, I also found the first chunk of the expression.
int begin = exp.indexOf("{") + 1;
int numberOfParenthesys = 1;
int end = -1;
for(int i = begin; i < exp.length(); i++) {
char c = exp.charAt(i);
if (c == '{') numberOfParenthesys ++;
if (c == '}') numberOfParenthesys --;
if (numberOfParenthesys == 0) {
end = i;
break;
}
}
The if condition provide validation on the begin and end indexes and stop the recursive call when no more chunks can be found on the remained expression.
if(begin > 0 && begin < exp.length() && end > 0) {
...
}

p5.play counter not working

I'm trying to write a program in which the end screen of the game only shows up after the last animation finishes. I'm using a counter that's implemented after each object is removed (which is only after it finishes its animation), and when that counter gets to zero, it should show the end screen. Unfortunately, from what I can tell, the counter statement isn't registering at all. I've inserted a print statement that isn't functioning.
var star;
var score;
var counter;
function setup() {
createCanvas(600,400);
score = 0;
counter = 20;
for (var s = 0; s < 20; s++) {
star = createSprite(random(width), random(height));
star.addAnimation("idle", idleAnim);
star.addAnimation("explode", explAnim);
star.changeAnimation("idle");
star.onMousePressed = function() {
this.changeAnimation("explode");
this.animation.looping = false;
score +=1
if (this.getAnimationLabel() == "explode" && this.animation.getFrame() == this.animation.getLastFrame()) {
this.remove();
counter -= 1;
print(counter);
}
}
}
}
function draw() {
if (score == 20 && counter == 0) {
background(255,222,51)
textSize(90);
fill(0)
text("YOU WIN!",95,225)
} else {
drawSprites();
}
}
You need to take a step back and debug your program. For example, are you sure the star.onMousePressed() function is firing? Are you sure the if statement is working the way you expected? Are you sure the player.dir() function is being called?
It sounds like your if statement is not being entered. can you find out the value of everything on that line? Which thing has a different value from what you expected?
Use console.log() statements, or use the JavaScript debugger, to answer all of the above. Figure out exactly which line of code is behaving differently from what you expected, and then isolate that problem in a MCVE. Good luck.

Making a game with 4 possible answer buttons

I am new to ActionScript-3 and I am attempting to make a game to learn more.
For every picture that is displayed I want there to be 4 choices (buttons) and only one of them to be the correct one. But how can I make it so that the text from the buttons will be random.
As you can see I've made it so the 4th button is always the correct answer. I don't want to make all this thing for every picture that is displayed...to much pointless code.
Can anybody help me? If you need extra information I will gladly provide it.
var k:int;
for(k=1;k<=3;k++)
{
GAME.variante.buttonMode=true;
GAME.variante.addEventListener(MouseEvent.MOUSE_OVER,mouse_over_variante);
GAME.variante.addEventListener(MouseEvent.MOUSE_OUT,mouse_out_variante);
GAME.variante.varianta_corecta.addEventListener(MouseEvent.CLICK,variante);
GAME.variante.varianta_gresita1.addEventListener(MouseEvent.CLICK,variante_gresiteunu);
GAME.variante.varianta_gresita2.addEventListener(MouseEvent.CLICK,variante_gresitedoi);
GAME.variante.varianta_gresita3.addEventListener(MouseEvent.CLICK,variante_gresitetrei);
GAME.varianta1.text = "Cameleon";
GAME.varianta2.text = "Snake";
GAME.varianta3.text = "Frog";
GAME.varianta4.text = "Snail";
function variante_gresiteunu(e:MouseEvent){
if (varianta_gresita_apasata1 == 1){
totalScore -= score_variante_gresite;
GAME.text1.text = totalScore;
varianta_gresita_apasata1 = 2;
}
}
function variante_gresitedoi(e:MouseEvent){
if (varianta_gresita_apasata2 == 1){
totalScore -= score_variante_gresite;
GAME.text1.text = totalScore;
varianta_gresita_apasata2 = 2;
}
}
function variante_gresitetrei(e:MouseEvent){
if (varianta_gresita_apasata3 == 1){
totalScore -= score_variante_gresite;
GAME.text1.text = totalScore;
varianta_gresita_apasata3 = 2;
}
}
}
GAME.extra_points.visible = false;
function variante (e:MouseEvent) {
if (GAME.stichere.sticker1.currentFrame == (1)){
GAME.extra_points.visible = true;
GAME.extra_points.plus_ten1.gotoAndPlay(1);
}
//go to great job screen
GAME.greatJob.stars.gotoAndPlay(1);
GAME.greatJob.visible = true;
}
function mouse_over_variante (e:MouseEvent) {
trace(e.target.name);
e.target.gotoAndPlay(1);
}
function mouse_out_variante (e:MouseEvent) {
e.target.gotoAndStop(1);
}
You like to have 4 images and they will be tested right?
The text below the images will be randomness. I saw your code and I
confess I was confused. I made a different one.
I undestand that this code is a little diferent of what you ask, but i think it will > give you some new ideas and help you on your app...
//start button added on the sceen named f3toc. I give a function name for him f3roll.
f3toc.addEventListener(MouseEvent.CLICK,f3roll);
function f3roll(e:MouseEvent):void{
//creating variables for the picture.
var bola:Number
var quadrado:Number
var pentagono:Number
//Here is just a randomization code, you can change it to the what you want to use after the =
bola = Math.ceil(Math.random() * 10);
pentagono = Math.ceil(Math.random() * 10);
f3res1_txt.text = String (bola + 8 + 8);
f3res2_txt.text = String(bola - 1 + bola);
f3res3_txt.text = String (pentagono + 10 - bola);
//converting number to string so we can put tem into the text fields.
var pentagonotring:String = pentagono.toString();
var bolastring:String = bola.toString();
//function to check wen the name is correct. each wrong do nothing and every correct add 1 to a variable, in the end wen this variable reach 3 it does something.
f3check_bnt.addEventListener (MouseEvent.CLICK, f3check);
function f3check (e:MouseEvent):void{
if (f3inp2_txt.text == pentagonotring){
f3ver_ext2.text = "Correct"
} else {f3ver_ext2.text = "Wrong";}
if (f3inp1_txt.text == bolastring){
f3ver_ext1.text = "Correct"
}else {f3ver_ext1.text = "Wrong";}
// function to check wen the variable pass reach 3
pass = 0;
if (f3ver_ext1.text == "Correct"){
pass++
}
if (f3ver_ext2.text == "Correct"){
pass++
if (pass == 3){
nextFrame();
}}}}

Replace certain cell values in a column

Disclaimer: I am Newb. I understand scripting a little, but writing it is a pain for me, mostly with loops and arrays, hence the following.
I am attempting to pull all of the data from a specific column (in this case H [8]), check each cell's value in that column and if it is a y, change it to Yes; if it's n, change it to No; if it's empty, leave it alone and move onto the next cell.
Here's what I have so far. As usual, I believe I'm pretty close, but I can't set the value of the active cell and I can't see where I'm messing it up. At one point I actually changed ever value to Yes in the column (so thankful for undo in these cases).
Example of Sheet:
..... COL-H
r1... [service] <-- header
r2... y
r3... y
r4... n
r5... _ <-- empty
r6... y
Intent: Change all y's to Yes and all n's to No (skip blank cells).
What I've tried so far:
Function attempt 1
function Thing1() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("mySheet");
var lrow = ss.getLastRow();
var rng = ss.getRange(2, 8, lrow - 1, 1);
var data = rng.getValues();
for (var i=0; i < data.length; i++) {
if (data[i][0] == "y") {
data[i][0] == "Yes";
}
}
}
Function attempt 2
function Thing2() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("mySheet");
var lrow = ss.getLastRow();
var rng = ss.getRange(2, 8, lrow - 1, 1);
var data = rng.getValues();
for (var i=0; i < data.length; i++) {
if (data[i][0] == "n") {
data.setValue("No");
} else if (data[i][0] == "y") {
data.setValue("Yes");
}
}
}
Usage:
Once I'm done here, I want to modify the function so that I can target any column and change one value to another (I already have a method for that, but I need to be able to set the value). It would be like so: =replace(sheet, col, orig_value, new_value). I will post it as well below.
Thanks in advance for the help.
Completed Code for searching and replacing within a column
function replace(sheet, col, origV1, newV1, origV2, newV2) {
// What is the name of the sheet and numeric value of the column you want to search?
var sheet = Browser.inputBox('Enter the target sheet name:');
var col = Browser.inputBox('Enter the numeric value of the column you\'re searching thru');
// Add old and new targets to change (Instance 1):
var origV1 = Browser.inputBox('[Instance 1:] What old value do you want to replace?');
var newV1 = Browser.inputBox('[Instance 1:] What new value is replacing the old?');
// Optional - Add old and new targets to change (Instance 2):
var origV2 = Browser.inputBox('[Instance 2:] What old value do you want to replace?');
var newV2 = Browser.inputBox('[Instance 2:] What new value is replacing the old?');
// Code to search and replace data within the column
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet);
var lrow = ss.getLastRow();
var rng = ss.getRange(2, col, lrow - 1, 1);
var data = rng.getValues();
for (var i=0; i < data.length; i++) {
if (data[i][0] == origV1) {
data[i][0] = newV1;
} else if (data[i][0] == origV2) {
data[i][0] = newV2;
}
}
rng.setValues(data);
}
Hope this helps someone out there. Thanks Again #ScampMichael!
The array named data was created from the values in the range and is independent of the spreadsheet after it is created so changing an element in the array does not affect the spreadsheet. You must modify the array and then put the whole array back where it came from.
for (var i=0; i < data.length; i++) {
if (data[i][0] == "n") {
data[i][0] = "No";
} else if (data[i][0] == "y") {
data[i][0] = "Yes";
}
}
rng.setValues(data); // replace old data with new
}

how to set "smart" breakpoint in Xcode when method returns a specific value?

I have a method which returns a bool value, with several exit points.
However, it does not seem to work correctly, so I would like to set an automatic breakpoint to see when it returns a YES value, so I can check all the variables and calculations in the debugger.
I would like to stop the debugger whenever a YES value is returned.
I have a similar smart breakpoint set for objc_exception_throw, so I know it's possible, I am just not sure how.
(In case it helps anyone, the way you can set the exception breakpoint: in the Breakpoints window (Run -> Show -> Breakpoints) enter objc_exception_throw as "Breakpoint", and libobjc.A.dylib as "Location")
EDIT: the specific code I would like to use it for:
- (BOOL)collisionOccured {
// Assumption: helicopter is of square shape (collision calculated by radius), walls are rectangles
// This approach is based on the solution seen here: http://stackoverflow.com/questions/401847/circle-rectangle-collision-detection-intersection/402010#402010
float helicopterImageWidth = [helicopter texture].contentSize.width;
float wallImageWidth = [[walls lastObject] texture].contentSize.width;
float wallImageHeight = [[walls lastObject] texture].contentSize.height;
float helicopterCollisionRadius = helicopterImageWidth * 0.4f;
CGPoint helicopterPosition = helicopter.position;
int numWalls = [walls count];
for (int i = 0; i < numWalls; i++) {
CCSprite *wall = [walls objectAtIndex:i];
if ([wall numberOfRunningActions] == 0) {
// The wall is not moving, we can skip checking it.
continue;
}
CGPoint wallPosition = wall.position;
float helicopterDistanceX = abs(helicopterPosition.x - wallPosition.x - wallImageWidth/2);
float helicopterDistanceY = abs(helicopterPosition.y - wallPosition.y - wallImageHeight/2);
if (helicopterDistanceX > (wallImageWidth/2 + helicopterCollisionRadius)) { return NO; }
if (helicopterDistanceY > (wallImageHeight/2 + helicopterCollisionRadius)) { return NO; }
if (helicopterDistanceX <= (wallImageWidth/2)) { return YES; }
if (helicopterDistanceY <= (wallImageHeight/2)) { return YES; }
float cornerDistance_sq = powf((helicopterDistanceX - wallImageWidth/2), 2) +
powf((helicopterDistanceY - wallImageHeight/2), 2);
return (cornerDistance_sq <= powf(helicopterCollisionRadius, 2));
}
// this should not occur
return NO;
}
This method is called via
- (void)update:(ccTime)delta {
if ([self collisionOccured]) {
NSLog(#"A collision occured");
}
}
The problem is that the update method takes delta (time passed) as argument, so I can't check what's happening frame by frame -- whenever I continue the execution, I am presented with a different scene.
(I am using cocos2d in the code)
You can set conditional breakpoints. With a slight tweak to update:
- (void)update:(ccTime)delta {
BOOL collided = [self collisionOccured];
if (collided) {
NSLog(#"A collision occured");
}
}
you can set a breakpoint as normal after the BOOL's assignment (i.e. on the if line), then right-click on the blue breakpoint arrow and select "Show Message Bubble", and add collided as the Condition. The extra variable should get optimized away in Release build mode.
If you're using a local return variable:
- (BOOL)someMethod {
BOOL ret = NO;
if (something) {
ret = YES;
} else if (something_else) {
ret = YES;
}
// ... and so on
return ret;
}
You can just set a watch point on ret
Otherwise, you're probably stuck with stepping through the code—hopefully some clever combination of conditional breakpoints will help you not have to break on every invocation. Setting a method breakpoint like you do with objc_exception_throw wouldn't work, because it will stop on every invocation, and breaking on the return value at the calling site is too late to figure out how you got there.
If you can post the code, we may be able to give more specific help as to a debugging strategy. Good luck. :-)

Resources