Nested if/else statements in Lua - Corona SDK - if-statement

Trying to make movement halt when (x) key is lifted (w,a,s,d) however I do not want the movement to stop if another key is held down. This is the snippet of code I was trying to use which was not working:
if (event.keyName == 'w' and event.phase == 'up') then
if (event.keyName == 's' and event.phase == 'down') then
testObj.deltaPerFrame = {testObj.deltaPerFrame[1], 2 }
else
testObj.deltaPerFrame = {testObj.deltaPerFrame[1], 0 }
return true
end
end

You have the same key event object so event.keyName or event.phase cannot have two different values. Hence your condition doesn't make any sense.
Please refer to the CoronaSDK manual.
https://docs.coronalabs.com/api/event/key/keyName.html
You'll have to maintain a list of keys that are currently pressed.

Related

Equation in if branch is not executed

I have a question that confused me for a long time. As you know, when we use an if condition in Modelica, that means if the expression is true, then Modelica will do the corresponding equation.
But when i test the following code, I am confused:
model Model134
Real a(start = 0);
equation
if not sample(0, 2) then
a = 1;
else
a = 3;
end if;
end Model134;
I think a will be changed every 2s (start time=0), but when I simulate this model, it dose not change and a is equal to 1 all the time.
Dose anybody know the root cause?
a does change its value, but depending on your simulation tool you might not see it in the plot.
sample(0, 2) creates a time event every 2 seconds. The return value of sample() is only true during the event. So the value of a changes, but after the event it immediately changes back.
In this answer to a similar question, it is mentioned that Dymola stores the value before and after the event in result file. Intermediate values are skipped for efficiency reasons (there can be many for every event, which would bloat up your result file). Hence you can not plot this change in Dymola. For OpenModelica see the answer by
Akhil Nandan.
To proof that a really does change its value you can use this code for example:
model Model134
import Modelica.Utilities.Streams.print;
Real a;
equation
if sample(0, 2) then
a = 1;
else
a = 0;
end if;
when a > 0.5 then
print("a is " + String(a) + " at t=" + String(time) + "s");
end when;
annotation (experiment(StopTime=10));
end Model134;
You should see something like this in the simulation log:
a is 1 at t=2s
a is 1 at t=4s
a is 1 at t=6s
a is 1 at t=8s
a is 1 at t=10s
This is the plot simulated when trying your above code in OpenModelica with settings shown in the second figure.
A time event is triggered when sample(startTime,interval) evaluates true at every multiple of 2 seconds and based on your code logic this should activate else
block and assign value of variable a to be 3.

How to fix a loop with boolean variable

I'm doing a project for a class, and I opted to make a text based game in python. I'm trying to set it up so that the question will loop until the player confirms their choice, and I'm having problems with the while loop in this section.
def pc_cls_sc(x):
# code does some stuff
print "You are sure about" + str(x)
exVar = raw_input("Right?")
if exVar == "y":
print "Alright!"
conf_Class = True
else:
print "Ok then."
conf_Class = False
while conf_Class is False:
pc_Class = raw_input(#asks some question)
pc_cls_sc(pc_Class)
The rest of this code functions properly, but the loop continues after the conf_Class variable is supposed to be set to true. I have a similar loop earlier in my code, which works just fine. I've tried moving the variable reassignment outside of the pc_cls_sc function, but all it did was cause double output. Can anyone tell me how to fix this?
You can use break to exit the loop. The code below will keep asking a user for input until they say 'y'.
while True:
x=input("Right? " )
if (x=='y'):
break

How can I create a checkbox filter on c++

I'm having a problem that seems way more easy than it is. I think its more of an algorithmic problem than a coding one.
EDIT:
Imagine you have a database with a name and N boolean parameters, like if the person is blonde or not, if the person likes baseball or not, if person have a smartphone or not etc...
How could you print the name of someone that likes baseball AND is blonde, but doesn't matter if any of the other N parameters are true of false? How can I do that without having to write a test for every single of the (N^2)-1 possibilities?
I created a dictionary that maps a string to a struct with 4 boolean variables and some strings.
I want the user to select which booleans are important to them and return only the information that is true for all variable that he chose.
Something like a checkbox which you can use to filter a column in excel.
For instance if a user chose variables 1 and 2, I would like to know if there is a better way to return the result rather than testing every one of the 16 possibilities, like:
void filter(map<string, Mystruct> Mydictionary, bool bool1, bool bool2, bool bool3, bool bool4){
if(bool1 == true && bool2 == true && bool3 == false && bool4==false){
cout << Mydictionary.bool1Info << Mydictionary.bool2Info
if(bool1 == true && bool2 == false && bool3 == false && bool4==false)
...
Even more, for me its only important to test the booleans that the user picked up, so even if he didn't choose boolean3, it's not important to test if its true or false.
Any ideas?
I would be very glad if anyone could help me with this one
I can help you with your algorithm part ,
instead of checking all 16 possibilities just check 4 conditions separately for bool1,2,3,4 and print their info if they are true.
This way you can complete your task with only 4 if statements.
Hope this answers your query.

How to have a Button Change images from three different pictureboxes whilst making the previous invisible

I have 3 picture boxes added on my Visual Basic and I have one button
essentially i want the button to display the next image when its pressed and to hide the previous image (all images are set to invisible on startup)
i've tried to do stuff like
If pic1.visible then
pic2.visible = true
pic3.visible = true
else
pic 1 .visible = true
end if
etc etc
Instead of basing your if-statement logic on the visibility of other images, I would suggest to create a counter that will keep track of the active image.
To keep it simple, have the counter loop between 1, 2 and 3 (i.e. clicking the button 4 times would make the counter == 1). Then simply have your if-statement logic based on the current value of the counter.
For instance:
if (counter == 1) {
pic1.show();
pic2.hide();
pic3.hide();
} else if (counter == 2) {
...
}
You can use switch statements if you'd like but I think this should give you a general idea.

Pre-order exploration of tictactoe search space not generating all states

I am trying to implement q-learning for tictactoe. One of the steps in doing so involves enumerating all the possible states of the tictactoe board to form a state-value table. I have written a procedure to recursively generate all possible states starting from the empty board. To do this, I am performing implicitly the pre-order traversal of the search space tree. However, at the end of it all, I am getting only 707 unique states whereas the general consensus is that the number of legal states is around 5000.
Note: I am referring to the number of legal states. I am aware that the number of states is closer to 19,000 if either player is allowed to continue playing after a game is completed (what I mean by an illegal state).
CODE:
def generate_state_value_table(self, state, turn):
winner = int(is_game_over(state)) #check if, for the current turn and state, game has finished and if so who won
#print "\nWinner is ", winner
#print "\nBoard at turn: ", turn
#print_board(state)
self.add_state(state, winner/2 + 0.5) #add the current state with the appropriate value to the state table
open_cells = open_spots(state) #find the index (from 0 to total no. of cells) of all the empty cells in the board
#check if there are any empty cells in the board
if len(open_cells) > 0:
for cell in open_cells:
#pdb.set_trace()
row, col = cell / len(state), cell % len(state)
new_state = deepcopy(state) #make a copy of the current state
#check which player's turn it is
if turn % 2 == 0:
new_state[row][col] = 1
else:
new_state[row][col] = -1
#using a try block because recursive depth may be exceeded
try:
#check if the new state has not been generated somewhere else in the search tree
if not self.check_duplicates(new_state):
self.generate_state_value_table(new_state, turn+1)
else:
return
except:
#print "Recursive depth exceeded"
exit()
else:
return
You can look at the full code here if you want.
EDIT:
I tidied the code up a bit both in the link and here with more comments to make things clearer. Hope that helps.
So I finally solved the issue and I am putting up this answer for anyone who faces a similar issue. The bug was in the way I was handling duplicate states. If the new state generated was generated before somewhere else in the search tree, then it should not be added to the state table, but the mistake I made was in cutting short the pre-order traversal on finding a duplicate state when it should have gone one.
Simply put: removing the else clause from the code below gave me the number of states as 6046:
#check if the new state has not been generated somewhere else in the search tree
if not self.check_duplicates(new_state):
self.generate_state_value_table(new_state, turn+1)
else:
return
Furthermore, I stopped exploring the search tree branch when I encountered a state where there was a clear winner. Concretely, I added the following code after self.add_state(state, winner/2 + 0.5):
#check if the winner returned is one of the players and go back to the previous state if so
if winner != 0:
return
This gave me the number of states as 5762 which is what I was looking for.