我是一名计算机科学本科生,正在学习’人工智能’课程。
这是一个简单的反射代理程序,使用’Python’编写,但我也尝试在p5.js(JavaScript)上实现它,以便创建一个用户界面。
但是我遇到了这个错误,有人能告诉我为什么this.currentRoom无法获取到this.room1吗?
或者您可以直接复制代码到在线编辑器中查看实际情况。
如果我的提问方式不好,请原谅我,这是我第一次在stackoverflow上提问。
function setup(){ createCanvas(600,400); vc = new VAgent(); twoRooms = new VEnvironment(vc); twoRooms.executeStep(6);}function draw(){ background(0);}class Room{ constructor(location,status){ this.location=location; this.status=status; } getAll(){ console.log(this.location); console.log(this.status); }}class VEnvironment{ contructor(agent){ this.agent=agent; this.room1=new Room('a','Dirty'); this.room2=new Room('b','Dirty'); this.currentRoom=this.room1; this.actionStatus=''; this.step=0; } executeStep(n){ for(var i=0;i<n;i++){ this.displayPerception(); this.agent.sense(this); var res = this.agent.action(); if(res=='clean'){ this.currentRoom.status=='clean' }else if(res=='Right'){ this.currentRoom=this.room2; }else{ this.currentRoom=this.room1; } this.displayAction(); this.step++; } } displayPerception(){ console.log('Agent is Present At Room '+this.currentRoom.location+' And The Status For Room Is '+this.currentRoom.status); } displayAction(){ console.log('Agent took at'+this.step+' And Action was ... '+this.currentRoom+'...'); }}class VAgent{ constructor(){ } sense(currentEnv){ this.en=currentEnv; } action(){ if(this.en.currentRoom.status=='dirty'){ return 'Clean' }else if(this.en.currentRoom.location=='a'){ return 'Left' }else{ return 'Right' } }}
回答:
当你遇到一段复杂的代码无法理解时,最好的做法是将问题简化为一个简化的示例程序。
例如,你可以将问题隔离到以下代码中:
function setup() { createCanvas(600, 400); const myContainer = new Container(); myContainer.displayValue();}function draw() { background(0);}class Value { constructor() { this.x = 42; }}class Container { contructor() { this.value = new Value(); this.currentvalue = this.value; console.log('constructor value: ' + this.currentValue); } displayValue() { console.log('display value: ' + this.value.x); }}
这段代码展示了与你的代码相同的问题,但没有与问题无关的额外代码。
如果运行这段代码,你会注意到constructor value
的打印语句从未被触发。这是一个提示,让你更仔细地查看构造函数。
你的问题是一个拼写错误:你写的是contructor
而不是constructor
。