There is one button.
The javascript program contains 3 sections.
//section 1
var x = 3;
console.log("x = " + x);
//section 2
x += 7;
console.log("x = " + x);
//section 3:
x += 6;
console.log("x = " + x);
The effect I want to achieve is:
I'm clicking the button - only section 1 is being executed
I'm clicking the button again - execution of section 2 only
I'm clicking the button again - execution of section 3 only
I'm clicking the button once more - execution of section 1 only
I'm clicking the button again - execution of section 2 only
and so on.
A loop is not necessary, this can be done with the same event handler for the button.
As a side note, if you are looking for a way to debug step by step, that can be done using the 'Debug or Debugger' tab of the brwoser afte right click -> inspect. You can set breakpoints and run the script step by step.
var output = document.getElementById("output");
var theButton = document.getElementById("theButton");
var section = 0;
var x;
theButton.onclick = function(){
section++;
var temporaryResult = "Nothing";
if(section == 4){
section = 1;
}
if(section == 1){
//Do the math
x = 0;
// Set the result to show
temporaryResult = x;
}
if(section == 2){
//Do the math
x += 10;
// Set the result to show
temporaryResult = x;
}
if(section == 3){
x -= 25;
temporaryResult = x;
}
output.innerHTML = temporaryResult;
//For console log:
console.log(temporaryResult);
}
<div id="output">Results here</div>
<button id="theButton">Next</Button>
Related
Im trying to add settings to a snake game made in processing. I want to have something like easy, normal and hard or something along the lines of that and change the speed and maybe size of the grid. If anyone coudl explain how to id greatly appreciate it!
ArrayList<Integer> x = new ArrayList<Integer>(), y = new ArrayList<Integer>();
int w = 30, h = 30, bs = 20, dir = 2, applex = 12, appley = 10;
int[] dx = {0,0,1,-1}, dy = {1,-1,0,0};
boolean gameover = false;
void setup() {
size(600,600);
x.add(5);
y.add(5);
}
void draw() {
background(255);
for(int i = 0 ; i < w; i++) line(i*bs, 0, i*bs, height); //Vertical line for grid
for(int i = 0 ; i < h; i++) line(0, i*bs, width, i*bs); //Horizontal line for grid
for(int i = 0 ; i < x.size(); i++) {
fill (0,255,0);
rect(x.get(i)*bs, y.get(i)*bs, bs, bs);
}
if(!gameover) {
fill(255,0,0);
rect(applex*bs, appley*bs, bs, bs);
if(frameCount%5==0) {
x.add(0,x.get(0) + dx[dir]);
y.add(0,y.get(0) + dy[dir]);
if(x.get(0) < 0 || y.get(0) < 0 || x.get(0) >= w || y.get(0) >= h) gameover = true;
for(int i = 1; i < x.size(); i++) if(x.get(0) == x.get(i) && y.get(0) == y.get(i)) gameover = true;
if(x.get(0)==applex && y.get(0)==appley) {
applex = (int)random(0,w);
appley = (int)random(0,h);
}else {
x.remove(x.size()-1);
y.remove(y.size()-1);
}
}
} else {
fill(0);
textSize(30);
text("GAME OVER. Press Space to Play Again", 20, height/2);
if(keyPressed && key == ' ') {
x.clear(); //Clear array list
y.clear(); //Clear array list
x.add(5);
y.add(5);
gameover = false;
}
}
if (keyPressed == true) {
int newdir = key=='s' ? 0 : (key=='w' ? 1 : (key=='d' ? 2 : (key=='a' ? 3 : -1)));
if(newdir != -1 && (x.size() <= 1 || !(x.get(1) ==x.get(0) + dx[newdir] && y.get (1) == y.get(0) + dy[newdir]))) dir = newdir;
}
}
You need to break your problem down into smaller steps:
Step one: Can you store the difficulty in a variable? This might be an int that keeps track of a level, or a boolean that switches between easy and hard. Just hardcode the value of that variable for now.
Step two: Can you write your code so it changes behavior based on the difficulty level? Use the variable you created in step one. You might use an if statement to check the difficulty level, or maybe the speed increases over time. It's completely up to you. Start out with a hard-coded value. Change the value to see different behaviors.
Step three: Can you programatically change that value? Maybe this requires a settings screen where the user chooses the difficulty, or maybe it gets more difficult over time. But you have to do the first two steps before you can start this step.
If you get stuck on a specific step, then post an MCVE and we'll go from there.
int x = 31;
int y = 31;
int x_dir = 4;
int y_dir = 0;
void setup ()
{
size (800, 800);
}
void draw ()
{
background (150);
ellipse (x,y,60, 60);
if (x+30>=width)
{
x_dir =-4;
y_dir = 4;
}
if (y+30>=height)
{
x_dir=4;
y_dir = 0;
}
if (x+30>=width)
{
x_dir = -4;
}
x+=x_dir;
y+=y_dir;
println(x,y);
}
Hi,
I have to create this program in processing which produces an animation of a ball going in a Z pattern (top left to top right, diagonal top right to bottom left, and then straight from bottom left to bottom right) which then goes backwards along the same path it came.
While I have the code written out for the forward direction, I don't know what 2 if or else statements I need to write for the program so that based on one condition it goes forwards, and based on another condition it will go backwards, and it will continue doing so until it terminates.
If I am able to figure out which two if statements I need to write, all I need to do is copy and reverse the x_dir and y_dir signs on the forward loop.
There are a ton of different ways you can do this.
One approach is to keep track of which "mode" you're in. You could do this using an int variable that's 0 when you're on the first part of the path, 1 when you're on the second part of the path, etc. Then just use an if statement to decide what to do, how to move the ball, etc.
Here's an example:
int x = 31;
int y = 31;
int mode = 0;
void setup ()
{
size (800, 800);
}
void draw ()
{
background (150);
ellipse (x, y, 60, 60);
if (mode == 0) {
x = x + 4;
if (x+30>=width) {
mode = 1;
}
} else if (mode == 1) {
x = x - 4;
y = y + 4;
if (y+30>=height) {
mode = 2;
}
} else if (mode == 2) {
x = x + 4;
if (x+30>=width) {
mode = 3;
}
} else if (mode == 3) {
x = x - 4;
y = y - 4;
if (y-30 < 0) {
mode = 2;
}
}
}
Like I said, this is only one way to approach the problem, and there are some obvious improvements you could make. For example, you could store the movement speeds and the conditions that change the mode in an array (or better yet, in objects) and get rid of all of the if statements.
I have a problem in the below code:
var Directions : Vector3[]; //*
function FindNext(){
if(Set.length == 0){
Debug.Log("We're done.");
return;
}
var previous : Transform = Set[0];
var pScript : Cell = previous.GetComponent("Cell");
var next : Transform;
var nextScript : Cell;
var prevX : int = pScript.Position.x;
var prevZ : int = pScript.Position.z;
var randDirection : Vector3;
var randSeed : int = Random.Range(0,4);
var nextX : int;
var nextZ : int;
var counter : int;
do{
do{
randDirection = Directions[randSeed];
nextX = prevX+randDirection.x;
nextZ = prevZ+randDirection.z;
randSeed = (randSeed+1) % 4;
counter++;
if(counter > 4){
Set.RemoveAt(0);
previous.GetComponent.<Renderer>().material.color = Color.black;
yield WaitForEndOfFrame();
return;
}
}while(nextX < 0 || nextZ < 0 || nextX + 1 >= GridSize.x || nextZ + 1 >= GridSize.z);
next = GridArr[nextX,nextZ];
nextScript = next.GetComponent("Cell");
//nextScript.IsOpened = false;
}while(nextScript.IsOpened);
AddToSet(next);
DrawDebugLines(10, previous, next);
ClearWalls(previous, next);
yield WaitForEndOfFrame();
}
For some reason there's a problem with the array index, and I don't really know what it is.
Below is the error that I get:
IndexOutOfRangeException: Array index is out of range.
Grid+$FindNext$5+$.MoveNext () (at Assets/Scripts/Grid.js:74)
UnityEngine.MonoBehaviour:StartCoroutine_Auto(IEnumerator)
Grid:Update() (at Assets/Scripts/Grid.js:122)
I'm using UnityScript with Unity 5.
Well the solution was simple, like this program are running on Unity, the array that was Out of Range it's a public array with transforms, so to fix the problem, the only thing that need to do it's set the array values:
(0,1)(1,0)(1,1)(1,0)
This values are because the array must contain the four possible direction in a maze.
Need to animate a sorting algorithm, with source code line by line visualization.
INTRO:
For the begining, there is a FORM (see it in the picture attached). On top of that form is displayed a dinamicaly created array of Edit components, containing the array to sort.
A little below, on the right is placed a Memo component, containing the algorithm. At the left of each line of that algorithm, dinamicaly is placed a Label, that indicates the line number in algorithm.
The idea is to highlight line by colouring that label, where is the execution at the moment. Sorting starts when "Start" button is clicked. The action for it is following:
int n = 10;
bool swapped = true; hl(1);
int j = 0; hl(2);
int tmp; hl(3);
while (swapped) { hl(4);
swapped = false; hl(5);
j++; hl(6);
for (int i = 0; i < n - j; i++) { hl(7);
if (arr[i] > arr[i + 1]) { hl(8);
tmp = arr[i]; hl(9);
arr[i] = arr[i + 1]; hl(10);
arr[i + 1] = tmp; hl(11);
swapped = true; hl(12);
} hl(13);
} hl(14);
} hl(15);
The hl function must colour labels and pause execution by using Sleep() function
void TForm2::hl(int l)
{
for (int i = 0; i < 24; i++) {
Form2->lines[i]->Font->Color = clGray;
}
Form2->lines[l-1]->Font->Color = clRed;
Sleep(300);
}
PROBLEM:
Code execution is pausing (sleep function works properly), but the labels are still gray, with no visible changes, except the last one, when event finishes. The 15th line is red.
QUESTION:
Can anybody tell me, where I'm wrong, and how to do it right?
http://i.stack.imgur.com/crGyC.jpg
You need to allow the paint message to be processed in order to visually update the display. You can do that with either the Refresh or Update procedures:
Form2->Lines[l-1]->Font->Color = clGray;
Form2->Update(); // or Form2->Refresh();
I am trying to draw a graph that has a scrollbar,
the graph uses time for the x-axis and i'd like to have a limited x-axis (1 minute)
so up until 1 minute, the scroll bar's page is the length of the scrollbar,
after that the page should be '60 seconds long' and the scrollbar max should be 'elapsed time' long
when you drag the scrollbar it tracks along, and pulls up the relevant bit of the graph.
the graph should auto-scroll until its dragged away (and auto-scroll once its dragged back to max)
this is what i have so far
is defined at the top of the wndproc
static SCROLLINFO sci = {sizeof(SCROLLINFO),SIF_RANGE|SIF_POS|SIF_PAGE|SIF_TRACKPOS,0,0,0,0,0};
in the WM_HSCROLL event:
GetScrollInfo((HWND)lParam, SB_CTL, &sci);
int pos;
pos = sci.nPos;
switch(LOWORD(wParam))
{
case SB_PAGELEFT:
pos -= sci.nPage;
break;
case SB_LINELEFT:
pos -= (sci.nMax/10);
break;
case SB_PAGERIGHT:
pos += sci.nPage;
break;
case SB_LINERIGHT:
pos += (sci.nMax/10);
break;
case SB_THUMBTRACK:
tsTracking = true;
pos = sci.nTrackPos;
break;
case SB_THUMBPOSITION:
tsTracking = false;
pos = sci.nTrackPos;
break;
}
if (pos < sci.nMin) pos = sci.nMin;
if (pos > sci.nMax) pos = sci.nMax;
if (pos != sci.nPos)
{
sci.fMask = SIF_POS;
sci.nPos = pos;
if(sci.nPos >= (sci.nMax-(sci.nPage*1.2)-1)) //this should detect when the thumb has reached the end of the scrollbar
sci.nPos = sci.nMax;
SetScrollInfo((HWND)lParam, SB_CTL, &sci, TRUE);
PostMessage(hWnd, WM_COMMAND, IDM_DISPLAYRESULTS, 0);
}
break;
in the drawing code called from WM_PAINT
(yes i realize i shouldn't be setting the scrollbar's info here, i intend to put it in its proper place once its working properly)
at the top of the graph-drawing function:
static SCROLLINFO sci = {sizeof(SCROLLINFO),SIF_RANGE|SIF_POS|SIF_PAGE|SIF_TRACKPOS,0,0,0,0,0};
in the graph-drawing function:
__int64
elapsed_time = g_h_maxX-g_h_minX, //the elapsed time
windowLengthMS, //the current window length in ms (between 0 and MAX_TIME_WIDTH_MS)
start, //the start of the current window
end; //the end of the current window
static UINT32 windowMaxS = 1; //how long the window max is (used for x sub-divisions)
double
xTickStep, //x division step
yTickStep, //y division step
xScale, //x-scale (used to get the time relative to the elapsed time and size of the graph)
yScale; //y-scale (used to get the data being plotted relative to its max, and the size of the graph)
if(!tsTracking) //a global bool, checking if the scrollbar's thumb is being dragged
{
GetScrollInfo(get_chwnd(IDCW_HARMONICSRESULTSTIMESHIFTSB),SB_CTL,&sci); //gets the scroll info for the scrollbar
int pos = sci.nPos*(double(elapsed_time)/double(sci.nMax - sci.nMin)); //gets the position relative to the new max
sci.nMin = g_h_minX; //sets min (should always be the same, done for completeness)
sci.nMax = (((g_h_maxX-MAX_TIME_WIDTH_MS)>0)?(g_h_maxX):0); //sets max to either max, or 0 (if max isnt bigger then page length)
sci.nPage = MAX_TIME_WIDTH_MS; //sets the page length to the window length
sci.nPos = pos; //sets position to its new value
if(sci.nPos >= (sci.nMax-(sci.nPage*1.2)-1)) //if position is one "page" from the end
sci.nPos = sci.nMax; //set it to max
SetScrollInfo(get_chwnd(IDCW_HARMONICSRESULTSTIMESHIFTSB),SB_CTL,&sci,true);
} //set scroll info
if (elapsed_time > MAX_TIME_WIDTH_MS) //if elapsed time is longer then the max window length
{
end = ((double)sci.nPos / double(sci.nMax)) * g_h_maxX; //set the end to current (scroll position / scroll max) * latest time -> this should put end relative to the scrollbar
start = end-MAX_TIME_WIDTH_MS; //sets start to end - window length
if (start < 0) //if start is now less than zero
{
end = MAX_TIME_WIDTH_MS; //set end to window length
start = 0; //set start to 0
}
}
else //if (elapsed_time <= MAX_TIME_WIDTH_MS)
{
start = g_h_minX; //start is min
end = g_h_maxX; //end is max
}
windowLengthMS = (end-start); //find the current window length
if(_MSTOSECS(windowLengthMS) > windowMaxS) //if the current window length beats one fo the markers
windowMaxS = ((windowMaxS < 10)?windowMaxS+1:(windowMaxS==40)?windowMaxS*1.5:windowMaxS*2); //change subdiv scaling
xScale = double(graph_width)/double(windowLengthMS); //set x-scale to width / window length
yScale = (double)(graph_height)/((double)g_h_maxY - (double)g_h_minY); //set y-scale to height / (maxVal-minVal)
int ticks = _MSTOSECS(elapsed_time); //ticks = full seconds elapsed
xTickStep = double(graph_width)/double(ticks+1); //tickstep = seconds+1 (accounts for 0)
yTickStep = double(graph_height)/double(Y_TICKS); //6 y-ticks, constant.
SelectObject(hDC,hThickPen);
{ //scope to clear variables!
double x; //x to store subdiv x-location
for(i = ticks; i >= 0; i--) //for each subdiv
{
if(((windowMaxS>40)?(!(i%3)):(windowMaxS >20)?(!(i%2)):i)) //have if <=20 secs, each second is shown on x, >20 <=40, every second second is shown, >40 seconds, every 3rd second is shown
{
x = round((_SECSTOMS(i)*xScale)); //find x-pos
sprintf(buf,"%d",(i+_MSTOSECS(start))); //print to buffer
SetRect(&rc, fr.left+x-5, fr.bottom+5, fr.left+x+xTickStep, fr.bottom+25); //get text rectangle
DrawText(hDC, buf, -1, &rc, DT_SINGLELINE | DT_VCENTER | DT_LEFT); //draw text
}
if (i!=ticks && (windowMaxS>40)?(!(i%6)):(windowMaxS >20)?(!(i%4)):(windowMaxS>10)?(!(i%2)):i)//every <10, each sec gets a subdiv, <20 each second tick gets a subdiv, <40 each 6th tick gets a subdiv
{
MoveToEx(hDC, GRAPH_XL_OFFSET+x, graph_bottom, NULL); //draw the line
LineTo(hDC, GRAPH_XL_OFFSET+x, graph_bottom-graph_height); //draw the line
}
}
}
as for globals:
g_h_minX is the start time and
g_h_maxX is the last result time
MAX_TIME_WIDTH_MS is the "window length" in ms -> how long i want the scroll bar page (60 seconds)
so the idea is to set end to where the scroll bar is, and get the start by taking the window length from end, and working out which part of the graph we're trying to look at.
i've been fiddling with this for the last 2 days and i'm running out of ideas.
im sure i'm close, but i cant quite figure it out,
edit:
updated the code slightly
it also seems i forgot to say what the problem was.
the scolling code isnt working properly, it autoscrolls when new data comes in,
but when i drag the thumb away from the end of the scrollbar, it just snaps to the start, and wont move.
on closer inspection, the arrows work, and the "page-right" "page-left" on the right-click menu work, just not the tracking
any help would be appreciated.
thanks in advance.
I have managed to find the problem,
I ended up converting everything to seconds and working with that, that ended up working, so i must have been having some scaling issues.
the code ended up like this:
case WM_HSCROLL:
{
SCROLLINFO sci = {sizeof(SCROLLINFO),SIF_RANGE|SIF_POS|SIF_PAGE|SIF_TRACKPOS,0,0,0,0,0};
GetScrollInfo((HWND)lParam, SB_CTL, &sci);
int pos;
pos = sci.nPos;
switch(LOWORD(wParam))
{
case SB_PAGELEFT:
pos -= sci.nPage;
break;
case SB_LINELEFT:
pos -= 2;
break;
case SB_PAGERIGHT:
pos += sci.nPage;
break;
case SB_LINERIGHT:
pos += 2;
break;
case SB_THUMBTRACK:
tsTracking = true;
pos = sci.nTrackPos;
break;
case SB_THUMBPOSITION:
tsTracking = false;
pos = sci.nTrackPos;
break;
case SB_LEFT:
pos = sci.nMin;
break;
case SB_RIGHT:
pos = sci.nMax;
break;
}
if (pos < sci.nMin) pos = sci.nMin;
if (pos > sci.nMax) pos = sci.nMax;
if (pos != sci.nPos)
{
sci.fMask = SIF_POS;
sci.nPos = pos;
//if(sci.nPos >= (sci.nMax-sci.nPage)) //this should detect when the thumb has reached the end of the scrollbar
// sci.nPos = sci.nMax;
SetScrollInfo((HWND)lParam, SB_CTL, &sci, TRUE);
PostMessage(hWnd, WM_COMMAND, IDM_DISPLAYRESULTS, 0);
}
}
break;
for the scrolling code and
__int64
elapsed_time = g_h_maxX-g_h_minX, //the elapsed time
windowLengthMS, //the current window length in ms (between 0 and MAX_TIME_WIDTH_MS)
start, //the start of the current window
end; //the end of the current window
static UINT32 windowMaxS = 1; //how long the window max is (used for x sub-divisions)
double
xTickStep, //x division step
yTickStep, //y division step
xScale, //x-scale (used to get the time relative to the elapsed time and size of the graph)
yScale; //y-scale (used to get the data being plotted relative to its max, and the size of the graph)
GetScrollInfo(get_chwnd(IDCW_HARMONICSRESULTSTIMESHIFTSB),SB_CTL,&sci); //gets the scroll info for the scrollbar
if (elapsed_time >= MAX_TIME_WIDTH_MS) //if elapsed time is longer then the max window length
{
start = _SECSTOMS(sci.nPos); //sets start to end - window length
end = start+MAX_TIME_WIDTH_MS; //set the end to current (scroll position / scroll max) * latest time -> this should put end relative to the scrollbar
}
else //if (elapsed_time <= MAX_TIME_WIDTH_MS)
{
start = g_h_minX; //start is min
end = g_h_maxX; //end is max
}
windowLengthMS = (end-start); //find the current window length
if(_MSTOSECS(windowLengthMS) > windowMaxS) //if the current window length beats one fo the markers
windowMaxS = ((windowMaxS < 10)?windowMaxS+1:(windowMaxS==40)?windowMaxS*1.5:windowMaxS*2); //change subdiv scaling
xScale = double(graph_width)/double(windowLengthMS); //set x-scale to width / window length
yScale = (double)(graph_height)/((double)max - (double)g_h_minY); //set y-scale to height / (maxVal-minVal)
if(!(g_h_maxY-g_h_minY))
yScale = 1;
if(!windowLengthMS)
xScale = 1;
int ticks = _MSTOSECS(elapsed_time); //ticks = full seconds elapsed
xTickStep = double(graph_width)/double(ticks+1); //tickstep = seconds+1 (accounts for 0)
yTickStep = double(graph_height)/double(Y_TICKS); //6 y-ticks, constant.
for the graph x-scaling