我正在用 JavaScript 圖形制作井字游戲(我認為),我呼叫了一個函式來獲取點擊的行(不起作用的函式是 getRow 函式)并且該函式沒有任何輸出
var WIDTH = 400;
var HEIGHT = 400;
setSize(WIDTH, HEIGHT);
var WINNING_LINE_WIDTH = 10;
var WINNING_LINE_COLOR = Color.red;
//high
var width = getWidth() / 3;
//thick
var height = getHeight() / 3;
//x != o
var shape = 0;
//1 2 3, as easy as A B C
var row = 0;
//ready, set, GO!!!!
function start(){
grid();
mouseClickMethod(click);
}
//lines
function grid(){
var line1 = new Line(width, 0, width, getHeight());
var line2 = new Line(width * 2, 0, width * 2, getHeight());
var line3 = new Line(0, height, getWidth(), height);
var line4 = new Line(0, height * 2, getWidth(), height * 2);
add(line1);
add(line2);
add(line3);
add(line4);
}
//notrick
function click(e){
var clicky = e.getY();
getRow(clicky,row);
println(row);
println(clicky);
println(height);
println(height * 2);
println(height * 3);
}
//row row row ur boat
function getRow(clicky, row){
if(clicky < height){
return row 1;
} if(clicky >= height && clicky <= height * 2 ){
return row 2;
} else{
return row 3;
} return row - 1;
println("nothing");
}
uj5u.com熱心網友回復:
此代碼在您撰寫的內容上正常作業,但您需要更改一些內容以獲得預期的功能。
首先,函式的回傳值是通過陣列呼叫本身回傳的。似乎在您的示例代碼中,您將“clicky”和“row”作為引數傳遞,并嘗試在函式中設定這些變數的值。但是,當您創建引數時,實際上是在使用相同名稱覆寫當前范圍內的任何其他變數并創建區域變數,而您只是在函式呼叫中傳入變數的值。所以這就是你的程式中發生的事情:
var row = 0;
function getRow(row) {
// defining row as a parameter creates a new local variable called "row"
row = 1; // sets the "row" local variable to 1, but doesn't affect the "row" outside of the function
console.log(row); // prints "1" because that's the value of the local var
}
getRow(row);
console.log(row); // prints 0 because that's the value of the global variable "row"
因此,您要做的是在單擊時傳遞游標的 y 值(您已經在這樣做了!它將它保存為函式引數“clicky”),但您也不需要傳遞行。然后,您可以為您的行值回傳一個整數!(而不是像現在這樣將其添加到全域變數中)然后您所要做的就是通過將 row 設定為等于函式呼叫來將 row 設定為該值。
// variable values for example
var row = -1;
var height = 100 / 3; // each row will be ~33 pixels
function click(e){
var clicky = e.getY();
row = getRow(clicky); // set row to the value returned from getRow()!
}
//row row row ur boat
function getRow(clicky){
if(clicky < height){
return 1;
} if(clicky >= height && clicky <= height * 2 ){
return 2;
} else{
return 3;
} return -1;
println("nothing"); // also note: you can delete this as it will never run, as its after a return (which stops running the function)
}
// testing:
console.log(row); // before click (-1)
click({getY:()=>0}); // test object I made so it can get a y-value (it'll just be your click event in your code)
console.log(row); // after clicking at y = 0 (0)
click({getY:()=>40});
console.log(row); // after clicking at y = 40 (1)
click({getY:()=>90});
console.log(row); // after clicking at y = 90 (2)
希望這有幫助!如果您需要澄清任何事情,請告訴我。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/424887.html
標籤:javascript 功能
下一篇:C等價于Python格式方法
