我正在尝试创建一个函数,以检查两副牌的顺序是否相同。
我编写了一个辅助功能cardEq来测试两张Card是否相同,并且可以正常工作。在deckEq函数中不起作用。
import sys
from cx_Freeze import setup, Executable
# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = {"packages": ["os"], "excludes": ["tkinter"]}
# GUI applications require a different base on Windows (the default is for a
# console application).
base = None
if sys.platform == "win64":
base = "Win64GUI"
setup( name = "cev",
version = "0.1",
description = "My CEV application!",
options = {"build_exe": build_exe_options},
executables = [Executable("cev.py", base=base)])
我希望它返回true或false,但是会引发错误: TypeError:无法读取未定义的属性“ suit” 在cardEq(代表:2:12) 在deckEq(repl:7:8)
编辑:我将while语句中的(i <53)更改为(i <52)。感谢您抓住@Christopher和@ traktor53。我猜问题是该函数正在不存在的数组项(第52个)上调用cardEq。由于这是为了比较卡片组,因此只能使用第51个元素(第52个卡片)。
答案 0 :(得分:0)
@Christopher推测,该问题是在deckEq
内从零开始的52张卡片的阵列中检查53张卡片。将while循环语句更改为
while (i < 52){
看到它可以在52张卡座中正常工作-
"use strict";
//Card Struct
//value 1 is ace, 11 is Jack, 12 is Queen, and 13 is King
function Card(suit, value, color){
this.suit = suit,
this.value = value,
this.color = color
}
//Check if two Cards are the same
function cardEq(card1, card2){
if(card1.suit === card2.suit
&& card1.value === card2.value
&& card1.color === card2.color){
return true;
} else {return false;}
}
//Check if two Decks/arrays of Cards are in the same order
function deckEq(deck1, deck2){
let i = 0;
let flag = false;
while (i < 52){
let x = deck1[i];
let y = deck2[i];
if(cardEq(x, y) === true){
flag = true;
i = i + 1;
} else {flag = false; break;}
}
return flag;
}
function createDeck(){
const deck = [];
const colors = ["black", "red", "red", "black"];
for( var i = 0; i < 52; ++i) {
var suite = Math.floor( i / 13);
var value = i % 13 + 1;
var color = colors[ suite];
deck.push( new Card( suite, value, color));
}
return deck;
}
let deck1 = createDeck();
let deck2 = createDeck();
console.log( deckEq( deck1, deck2)); // expect true
deck2[42] = deck2[0];
console.log( deckEq( deck1, deck2)); // expect false
最好还是使用卡座数组的长度来控制while循环迭代的次数,并在开始循环之前测试卡座的长度是否相同。
答案 1 :(得分:-1)
this
仅在将函数用作“ constructor function”时才起作用,这需要构造函数生成的对象的new
实例。这就是this
将绑定到的对象,否则,this
将绑定到window
并且window
没有suit
属性。
//Card Struct
//value 1 is ace, 11 is Jack, 12 is Queen, and 13 is King
function Card(suit, value, color){
this.suit = suit,
this.value = value,
this.color = color
}
//Check if two Cards are the same
function cardEq(card1, card2){
if(card1.suit === card2.suit
&& card1.value === card2.value
&& card1.color === card2.color){
return true;
} else {return false;}
}
//Check if two Decks/arrays of Cards are in the same order
function deckEq(deck1, deck2){
let ceq = new cardEq(x,y); // <-- Need an instance produces by the function
let i = 0;
let flag = false;
while (i < 53){
let x = deck1[i];
let y = deck2[i];
if(ceq === true){ // <-- Use the instance
flag = true;
i = i + 1;
} else {flag = false; break;}
}
return flag;
}