我是一名新手程序员(有5天的经验),我正在制作一个简单的tic tac toe代码以了解有关C#的更多信息。
我的问题是从方法Turn
返回新值后,变量PlayerTurn
的值不变。
我猜问题出在静态与非静态之间,这让我感到困惑
MainClass
using gamemainbody;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MehdiTicTacToe
{
class Program
{
static void Main(string[] args)
{
GameMainBody GMB = new GameMainBody();
int Turn = 0; // 1 if player turn else 0
string[] TheBoard = new string[9];
GMB.PlayerTurn(Turn);
Console.WriteLine(Turn);
GMB.Board(TheBoard);
Console.ReadLine();
}
}
}
1级
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace gamemainbody
{
class GameMainBody
{
private string[] theBoard;
private int turn;
public int Turn {
get => turn;
set => turn = value; }
public string[] TheBoard {
get => theBoard;
set => theBoard = value; }
public void Board(string[] TheBoard)
{
this.TheBoard = TheBoard;
Console.WriteLine(" | | ");
Console.WriteLine(" {0} | {1} | {2}", TheBoard[0], TheBoard[1], TheBoard[2]);
Console.WriteLine("_____|_____|_____ ");
Console.WriteLine(" | | ");
Console.WriteLine(" {0} | {1} | {2}", TheBoard[3], TheBoard[4], TheBoard[5]);
Console.WriteLine("_____|_____|_____ ");
Console.WriteLine(" | | ");
Console.WriteLine(" {0} | {1} | {2}", TheBoard[6], TheBoard[7], TheBoard[8]);
Console.WriteLine(" | | ");
}
public int PlayerTurn(int Turn)
{
this.Turn = Turn;
Console.WriteLine("Type X if you chose X");
Console.WriteLine("Type O if you chose O");
string UserInput = Console.ReadLine();
if (UserInput == "X" || UserInput == "x")
{
Console.WriteLine("PlayerTurn");
Turn += 1;
return Turn;
}
if (UserInput == "O" || UserInput == "o")
{
Turn = 0;
Console.WriteLine("AI Turn");
return Turn;
}
else
{
Turn -= 1;
return Turn;
}
}
public void GameCore(int Turn, string[] Board)
{
}
}
}
运行这段代码后,我打印了变量Turn的值,它的值仍然是0。
感谢您的帮助!
答案 0 :(得分:3)
import sys
from PyQt5 import QtCore, QtWidgets
def expandPath(index, view):
if not index.isValid():
return
indexes = []
ix = index
while ix.isValid():
indexes.insert(0, ix)
ix = ix.parent()
for ix in indexes:
view.expand(ix)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
model = QtWidgets.QFileSystemModel()
model.setRootPath(QtCore.QDir.rootPath())
view = QtWidgets.QTreeView()
view.setModel(model)
view.setRootIndex(model.index(QtCore.QDir.rootPath()))
doc_directory = QtCore.QStandardPaths.writableLocation(
QtCore.QStandardPaths.DocumentsLocation
)
ix = model.index(doc_directory)
expandPath(ix, view)
view.resize(640, 480)
for i in (1, 2, 3):
view.setColumnHidden(i, True)
view.show()
sys.exit(app.exec_())
是Value Type,因此您需要在Main方法中使用它来接收更改:
Turn
答案 1 :(得分:0)
您还可以明确指定Turn
作为ref
传递:
using System;
public class Program
{
static void ModifyInt(ref int x) # ref keyword here
{
x = x * 2;
}
public static void Main()
{
int value = 22;
ModifyInt(ref value); # ref keyword here
Console.WriteLine( value );
}
}
这样,您的ValueType被引用显式传递和更改:ref (C# Reference)
输出:
44
尽管我会首选使用返回值:)