【发布时间】:2017-12-16 18:38:53
【问题描述】:
我有这个用 python 编写的简单代码来创建一个小的 纸牌游戏,我想用打字稿做同样的事情,但我 在我的 Typescript 主课中遇到“this”的大问题 这是原始的python类:
class deck:
card_type=['Hearts ','Diamonds','Spades','Clubs']
card_rank=[2,3,4,5,6,7,8,9,10,'A','J','Q','K']
full_deck=[]
def build_deck(self):
single={}
for card in self.card_type:
for n in self.card_rank:
single={n: card}
self.full_deck.append(single)
shuffle(self.full_deck)
def reshuffle (self):
print('Re-shuffling again!')
shuffle(self.full_deck)
def choose_card(self):
chosen=choice(self.full_deck)
the_index= self.full_deck.index(chosen)
self.full_deck.pop(the_index)
return chosen
def pick_hand(self, number_of_cards):
hand=[]
new_card={}
for i in range(number_of_cards):
new_card = self.choose_card()
hand.append(new_card)
return hand
在我的主游戏文件中,我做了这样的事情:
from classes import deck
deck1= deck()
deck1.build_deck()
my_hand=deck1.pick_hand(3)
compu_hand=deck1.pick_hand(3)
但是当我尝试在类型脚本中创建一个类似的类时,我写了以下内容:
export class deck {
single_card: {
cType: string;
cNumber: any;
};
fullDeck: any[] = [];
card_type=['Hearts ','Diamonds','Spades','Clubs'];
card_rank=[2,3,4,5,6,7,8,9,10,'A','J','Q','K'];
shuffle() {
let counter = this.fullDeck.length;
// While there are elements in the array
while (counter > 0) {
// Pick a random index
let index = Math.floor(Math.random() * counter);
// Decrease counter by 1
counter--;
// And swap the last element with it
let temp = this.fullDeck[counter];
this.fullDeck[counter] = this.fullDeck[index];
this.fullDeck[index] = temp;
}
// return this.fullDeck;
}
buildDeck (){
for (let t in this.card_type) {
for ( let n in this.card_rank) {
this.single_card.cType = this.card_type[t];
this.single_card.cNumber = this.card_rank[n];
this.fullDeck.push(this.single_card);
console.log(this.single_card);
}
}
// this.shuffle()
}
}
当我尝试像这样使用主“ts”文件中的类时:
import {deck} from './myclasses'
$(document).ready (function(){
let deck1= new deck;
deck1.buildDeck();
});
console.log 调用返回同样的错误:
jQuery.Deferred 异常:无法设置未定义的属性“cType” TypeError:无法设置未定义的属性“cType” 在deck.buildDeck (file:///run/media/Work/HTML_Porjects/Game_TS/built/myclasses.js:132:44)
它是如何未定义的? 我需要做什么才能使 Typescript 代码像 Python 代码一样工作?
提前致谢...
【问题讨论】:
-
抱歉,我给出了一个我认为可能大错特错的答案。
-
但您似乎在奇怪地使用
single_card。您不是将其定义为数据类型吗?那么为什么要像对象属性一样使用呢? -
感谢您的回复,我确实尝试了箭头功能它不起作用
-
抱歉,您是什么意思? single_card 是甲板类的属性
-
看起来不像。它没有像所有其他属性一样出现在
this中。它必须有一些语法不正确的东西。但我不知道打字稿;)
标签: javascript python python-3.x typescript this