IF statement in Switch React JS - reactjs

I'm making a snake game in React and it works fine but I have defined a switch case, where you can control the snake with the arrow keys. But there's a problem, when the snake is going to one direction I don't want it to be able to go to the opposite direction.
as in prevent changing direction along same axis, ie left if currently moving right, down if currently moving up
Now I'm wondering how can I define an If statement in my switch case for it?
My code so far looks like this :
//handle user input
const handleKeyPress = (e) => {
e = e || window.event;
setStarted(true);
switch (e.keyCode) {
case 38:
setDirection('UP');
break;
case 40:
setDirection('DOWN');
break;
case 37:
setDirection('LEFT');
break;
case 39:
setDirection('RIGHT');
break;
default:
break;
}
};
//moving the snake
const moveSnake = () => {
//take temporary positions
let tempSnakePosition;
let dir;
//get fresh cordinates
setSnakeCordinates((prev) => {
tempSnakePosition = [...prev];
return prev;
});
setDirection((prev) => {
dir = prev;
return prev;
});
//find head
let tempHead = tempSnakePosition[tempSnakePosition.length - 1];
//change head
let l = tempHead.left;
let t = tempHead.top;
switch (dir) {
case 'RIGHT':
if ('LEFT' && 'UP')
l = tempHead.left + size
break;
case 'LEFT':
if ('RIGHT')
l = tempHead.left - size;
break;
case 'DOWN':
t = tempHead.top + size;
break;
case 'UP':
t = tempHead.top - size;
break;
default:
break;
}

const [prevDir, setPrevDir] = useState('');
const handleKeyPress = (e) => {
switch (e.keyCode) {
case 38:
if(prevDir !== 'DOWN') {
setDirection('UP');
}
break;
case 40:
if(prevDir !== 'UP') {
setDirection('DOWN');
break;
}
case 37:
if(prevDir !== 'RIGHT') {
setDirection('LEFT');
}
break;
case 39:
if(prevDir !== 'LEFT') {
setDirection('RIGHT');
break;
}
default:
break;
}
}
setDirection((prev) => {
dir = prev;
setPrevDir(prev);
return prev;
});

Try using you dir variable like this:
//handle user input
const handleKeyPress = (e) => {
e = e || window.event;
setStarted(true);
switch (e.keyCode) {
case 38:
if(dir !== 'DOWN')
setDirection('UP');
break;
case 40:
if(dir !== 'UP')
setDirection('DOWN');
break;
case 37:
if(dir !== 'RIGHT')
setDirection('LEFT');
break;
case 39:
if(dir !== 'LEFT')
setDirection('RIGHT');
break;
default:
break;
}
};

Related

Declaring a variable gives an error, makes me think there's something else I'm missing

I have a function in C that compiles fine until I add another case to my switch statement and declare a variable.
Here's the function
void evaluate(int num_inputs) {
struct gate *ptr = gatehead;
while (ptr->next != NULL) {
switch (ptr->kind) {
case 0:
if (get_input_value(ptr->params[0]) && get_input_value(ptr->params[1])) {
write_to_output(true, ptr->output);
} else {
write_to_output(false, ptr->output);
}
break;
case 1:
if (get_input_value(ptr->params[0]) || get_input_value(ptr->params[1])) {
write_to_output(true, ptr->output);
} else {
write_to_output(false, ptr->output);
}
break;
case 2:
if (!(get_input_value(ptr->params[0]) && get_input_value(ptr->params[1]))) {
write_to_output(true, ptr->output);
} else {
write_to_output(false, ptr->output);
}
break;
case 3:
if (!(get_input_value(ptr->params[0])) && !(get_input_value(ptr->params[1]))) {
write_to_output(true, ptr->output);
} else {
write_to_output(false, ptr->output);
}
break;
case 4:
if ((get_input_value(ptr->params[0]) || get_input_value(ptr->params[1])) && !(get_input_value(ptr->params[0]) && get_input_value(ptr->params[1]))) {
write_to_output(true, ptr->output);
} else {
write_to_output(false, ptr->output);
}
break;
case 5:
if (get_input_value(ptr->params[0])) {
write_to_output(false, ptr->output);
} else {
write_to_output(true, ptr->output);
}
break;
case 6:
if (get_input_value(ptr->params[0])) {
write_to_output(true, ptr->output);
} else {
write_to_output(false, ptr->output);
}
break;
case 7:
char* d = "DECODER";
printf("%s", d);
break;
}
ptr = ptr->next;
}
}
If I comment out case 7, everything works fine. Even keeping the print and break compiles, but declaring the char* causes the error "expected expression"
The problem is that the case 7: label is immediately followed by a variable declaration.
case 7:
char* d = "DECODER";
A label can only be applied to a statement, and a declaration is not considered a statement. You can get around this by adding an empty statement before the case label:
case 7:
;
char* d = "DECODER";

SimpleJSON returns null

i have an error in c# of NullReferenceException: Object reference not set to an instance of an object
SimpleJSON.JSONNode.Parse (System.String aJSON) (at Assets/Scenes/scripts/SimpleJSON.cs:553)
I found this post in the link below but i didn't understand the solution
SimpleJSON returns null when handling a call from Postmen
Can any one explain it for me, please?
the error is :
NullReferenceException: Object reference not set to an instance of an object
SimpleJSON.JSONNode.Parse (System.String aJSON) (at Assets/Scenes/scripts/SimpleJSON.cs:553)
SimpleJSON.JSON.Parse (System.String aJSON) (at Assets/Scenes/scripts/SimpleJSON.cs:1363)
Control.Update () (at Assets/Control.cs:123)
knowing that i'm sending json data using websocket and i'm receiving it in the console unity. i use simpleJSON script to deserialize the data.
here where the error is provided in line JSONNode root = JSON.Parse(last_message); :
private void Update()
{
if (ws == null)
{
return;
}
List<GameObject> object_to_keep = new List<GameObject>();
JSONNode root = JSON.Parse(last_message);
JSONNode Face = root["streams"][0]["objects"][0];
{
int id = Face["mono"]["id"].AsInt;
JSONNode position = Face["mono"]["position"];
Vector3 pos = new Vector3(position["x"].AsFloat, position["y"].AsFloat, position["z"].AsFloat);
GameObject mono = GetMonoObject();
WintualFaceController win_controller = mono.GetComponent<WintualFaceController>();
win_controller.face_id = id;
if(mono)
{
mono.transform.localPosition = pos;
object_to_keep.Add(mono);
}
else
print("Mono not found");
}
}
The error in SImpleJSON script wan in line: while (i < aJSON.Length)
public static JSONNode Parse(string aJSON)
{
Stack<JSONNode> stack = new Stack<JSONNode>();
JSONNode ctx = null;
int i = 0;
StringBuilder Token = new StringBuilder();
string TokenName = "";
bool QuoteMode = false;
bool TokenIsQuoted = false;
while (i < aJSON.Length)
{
switch (aJSON[i])
{
case '{':
if (QuoteMode)
{
Token.Append(aJSON[i]);
break;
}
stack.Push(new JSONObject());
if (ctx != null)
{
ctx.Add(TokenName, stack.Peek());
}
TokenName = "";
Token.Length = 0;
ctx = stack.Peek();
break;
case '[':
if (QuoteMode)
{
Token.Append(aJSON[i]);
break;
}
stack.Push(new JSONArray());
if (ctx != null)
{
ctx.Add(TokenName, stack.Peek());
}
TokenName = "";
Token.Length = 0;
ctx = stack.Peek();
break;
case '}':
case ']':
if (QuoteMode)
{
Token.Append(aJSON[i]);
break;
}
if (stack.Count == 0)
throw new Exception("JSON Parse: Too many closing brackets");
stack.Pop();
if (Token.Length > 0 || TokenIsQuoted)
{
ParseElement(ctx, Token.ToString(), TokenName, TokenIsQuoted);
TokenIsQuoted = false;
}
TokenName = "";
Token.Length = 0;
if (stack.Count > 0)
ctx = stack.Peek();
break;
case ':':
if (QuoteMode)
{
Token.Append(aJSON[i]);
break;
}
TokenName = Token.ToString();
Token.Length = 0;
TokenIsQuoted = false;
break;
case '"':
QuoteMode ^= true;
TokenIsQuoted |= QuoteMode;
break;
case ',':
if (QuoteMode)
{
Token.Append(aJSON[i]);
break;
}
if (Token.Length > 0 || TokenIsQuoted)
{
ParseElement(ctx, Token.ToString(), TokenName, TokenIsQuoted);
TokenIsQuoted = false;
}
TokenName = "";
Token.Length = 0;
TokenIsQuoted = false;
break;
case '\r':
case '\n':
break;
case ' ':
case '\t':
if (QuoteMode)
Token.Append(aJSON[i]);
break;
case '\\':
++i;
if (QuoteMode)
{
char C = aJSON[i];
switch (C)
{
case 't':
Token.Append('\t');
break;
case 'r':
Token.Append('\r');
break;
case 'n':
Token.Append('\n');
break;
case 'b':
Token.Append('\b');
break;
case 'f':
Token.Append('\f');
break;
case 'u':
{
string s = aJSON.Substring(i + 1, 4);
Token.Append((char)int.Parse(
s,
System.Globalization.NumberStyles.AllowHexSpecifier));
i += 4;
break;
}
default:
Token.Append(C);
break;
}
}
break;
default:
Token.Append(aJSON[i]);
break;
}
++i;
}
this is my json:
{
"cmd": "data",
"frame_time": "2021-06-30T09:04:16.464836+00:00",
"start_time": "2021-06-30T07:51:33.452079+00:00",
"streams": [
{
"name": "usb-0001:012.0-3",
"objects": [
{
"name": "face",
"mono": {
"id": "190",
"position": {
"x": "-0.012259",
"y": "0.059731",
"z": "0.707695"
}
},
"multi": [
{
"id": "190",
"position": {
"x": "-0.012263",
"y": "0.059753",
"z": "0.707151"
}
}
]
}
]
}
]
}

How to do switching between two diffrent swich statements using C?

I have written a c code for switching between two different switch statements,
but I am looking for a more generic solution, meaning without using state variable and while loop, or jump from one switch statement to another switch statement.
I want some suggestion or key input from you.
Thank you and please excuse my poor English.
#include <stdio.h>
int main()
{
unsigned char state,state1;
enum
{
Add,Sub,Mul,Div,START,STOP
}Arith_Op;
enum
{
Add1,Sub1,Mul1,Div1,START1,STOP1
}Arith_Op1;
Arith_Op = Add;
Arith_Op1 = Add1;
state = START;
while (state != STOP)
{
switch(Arith_Op)
{
case Add :
printf("Add\n");
Arith_Op = Sub;
break;
case Sub :
printf("sub\n");
Arith_Op = Mul;
break;
case Mul :
printf("mul\n");
Arith_Op = Div;
break;
case Div :
printf("div\n");
Arith_Op = STOP;
break;
default :
printf("default\n");
state = STOP;
state1 = START1;
break;
}
}
printf(" state out of while and Switch case ");
while (state1 != STOP1)
{
switch(Arith_Op1)
{
case Add1 :
printf("Add1\n");
Arith_Op1 = Sub1;
break;
case Sub1 :
printf("sub1\n");
Arith_Op1 = Mul1;
break;
case Mul1 :
printf("mul1\n");
Arith_Op1 = Div;
break;
case Div1 :
printf("div1\n");
Arith_Op1 = STOP1;
break;
default :
printf("default1\n");
state1 = STOP1;
break;
}
}
printf(" state 1 out of while and Switch case ");
return 0;
}

Variable is printed properly right before an if else loop, but does not retain that value one in the if else loop

I've written a program that reads an account value from a text file and then assigns these values to a variable for each account. Once this is done, reading from the same text file, an action to be done to each account value is identified in the format "Account# Actiontype ActionModifier". All the correct values are being scanned and the proper values are being stored when I insert printfs to check, but immediately after the correct value is printed, the value is put through an else if loop. When doing this for some reason the value is being read as 1 no matter what and is executing the actions in the else if loop as if it were equal to 1.
loopState = 1;
while(loopState != 0)
{
for(i = 1;i < 100 ;i++)
{
if(i < 6)// This executes fine
{
fscanf(bankfile,"%f",&accValue);
switch(i)
{
case 1:
acc1 = accValue;
break;
case 2:
acc2 = accValue;
break;
case 3:
acc3 = accValue;
break;
case 4:
acc4 = accValue;
break;
case 5:
acc5 = accValue;
printf("Done module one\n");
break;
}
}
else // scan for the the first value, than the second, then the third
{
fscanf(bankfile,"%d",&accNum);
if(accNum != 0)
{
fscanf(bankfile,"%c",&accAction);
if(accAction == 'W' || accAction == 'D')
{
fscanf(bankfile,"%f",&actValue);
printf("%d %c %.2f\n",accNum,accAction,actValue);//this will be correct
printf("%d\n",accNum); //this will print say "2"
if(accNum = 1)//but this if statement will be run
{//thus printing the below printf
printf("If accNum = 1 this will print\n");
switch(accAction)
{
case 'W':
final1 = withdrawl(acc1,actValue);
break;
case 'D':
final1 = deposit(acc1,actValue);
break;
}
}
else if(accNum = 2)
{
switch(accAction)
{
case 'W':
final2 = withdrawl(acc2,actValue);
break;
case 'D':
final2 = deposit(acc2,actValue);
break;
}
}
else if(accNum = 3)
{
switch(accAction)
{
case 'W':
final3 = withdrawl(acc3,actValue);
break;
case 'D':
final3 = deposit(acc3,actValue);
break;
}
}
else if(accNum = 4)
{
switch(accAction)
{
case 'W':
final4 = withdrawl(acc4,actValue);
break;
case 'D':
final4 = deposit(acc4,actValue);
break;
}
}
else if(accNum = 5)
{
switch(accAction)
{
case 'W':
final5 = withdrawl(acc5,actValue);
break;
case 'D':
final5 = deposit(acc5,actValue);
break;
}
}
}
else if(accAction == 'B' || accAction == 'U')
{
printf("%d %c\n",accNum,accAction);//this will be correct
printf("%d\n",accNum);//this will print say "4"
if(accNum = 1)//but this if statement will be run
{//thus printing this printf below
printf("If accNum = 1 this will print\n");
switch(accAction)
{
case 'B':
final1 = balance(acc1);
break;
case 'U':
final1 = update(acc1);
break;
}
}
else if(accNum = 2)
{
switch(accAction)
{
case 'B':
final2 = balance(acc2);
break;
case 'U':
final2 = update(acc2);
break;
}
}
else if(accNum = 3)
{
switch(accAction)
{
case 'B':
final3 = balance(acc3);
break;
case 'U':
final3 = update(acc3);
break;
}
}
else if(accNum = 4)
{
switch(accAction)
{
case 'B':
final4 = balance(acc4);
break;
case 'U':
final4 = update(acc4);
break;
}
}
else if(accNum = 5)
{
switch(accAction)
{
case 'B':
final5 = withdrawl(acc5,actValue);
break;
case 'U':
final5 = deposit(acc5,actValue);
break;
}
}
}
}
else
loopState = 0;
}
}
}
printf("Exited Loop");
}
From my understanding I can't see where the value is being altered if just the line before it is being seen as the correct value
Your conditional statements are doing assignment.
else if (accNum = 3)
should be
else if (accNum == 3)

C SDL Keyboard Events SDL_KEYUP Triggering When Key Is Down

I am using SDL in C, and I'm trying to make a character move on the screen when a key is pressed, and stop when it is released, but it seems as if the KEYUP event is triggering when the key is still being held down. If I remove the KEYUP section in pressed(), the characters will slide across the screen, but obviously won't stop on their own. If I leave the KEYUP section in, I have to press the key repeatedly to move them across the screen.
Any idea what I'm doing wrong?
Here's what I have:
...
int done = 0;
while (done==0)
{
pressed();
if (kenter == 1)
{
state = 1;
subscreen();
}
if (kescape == 1)
{
done = 1;
}
if (kup == 1)
{
playery += -2;
}
if (kdown == 1)
{
playery += 2;
}
if (kright == 1)
{
playerx += 2;
}
if (kleft == 1)
{
playerx += - 2;
}
...
int pressed ()
{
SDL_Event keyevent;
while (SDL_PollEvent(&keyevent))
{
switch(keyevent.type)
{
case SDL_KEYDOWN:
switch(keyevent.key.keysym.sym)
{
case SDLK_RETURN:
{
kenter = 1;
break;
}
case SDLK_ESCAPE:
{
kescape = 1;
break;
}
case SDLK_a:
{
ka = 1;
break;
}
case SDLK_s:
{
ks = 1;
break;
}
case SDLK_UP:
{
kup = 1;
break;
}
case SDLK_DOWN:
{
kdown = 1;
break;
}
case SDLK_RIGHT:
{
kright = 1;
break;
}
case SDLK_LEFT:
{
kleft = 1;
break;
}
default:
break;
}
}
switch(keyevent.type)
{
case SDL_KEYUP:
switch(keyevent.key.keysym.sym)
{
case SDLK_RETURN:
{
kenter = 0;
break;
}
case SDLK_ESCAPE:
{
kescape = 0;
break;
}
case SDLK_a:
{
ka = 0;
break;
}
case SDLK_s:
{
ks = 0;
break;
}
case SDLK_UP:
{
kup = 0;
break;
}
case SDLK_DOWN:
{
kdown = 0;
break;
}
case SDLK_RIGHT:
{
kright = 0;
break;
}
case SDLK_LEFT:
{
kleft = 0;
break;
}
default:
break;
}
}
}
return 0;
}
I think your switch statements are broken.
Use this less confusing way
int pressed ()
{
SDL_Event event;
while(SDL_PollEvent(&event) )
{
if(event.type == SDLK_KEYDOWN)
{
switch(event.key.keysym.sym)
{
case SDLK_RETURN:
doStuff = 1
break;
default:
break;
}
}
if(event.type == SDLK_KEYUP)
{
switch(event.key.keysym.sym)
{
case SDLK_RETURN:
doStuff = 0;
break;
default:
break;
}
}
}
}
Also important:
SDL Tutorials: Practical Keyboard Input
Oh and avoid using global variables!
Your use of two switch statements is odd and confusing, you should probably fix that.
The issues you're seeing are likely due to keyboard repeat, see the SDL_EnableKeyRepeat() call for how to disable it.
don't use switch. I experienced same thing, but I resolved into using 'if' like this. Maybe switch has 'else if'.
if(event.type == SDL_KEYDOWN){
....
}
if(event.type == SDL_KEYUP){
....
}

Resources