也许您不需要将卡片组作为一个类,因为您可以使用Card
对象数组执行大部分操作。这是一个例子。
classdef Card < handle
properties
type % number: 1-4
value % number: 1-13
end
methods
function obj = Card(type, value)
% some code to check [type, value] should be inserted here
obj.type = type;
obj.value = value;
end
function c = get_card(obj, t, v)
c = obj([obj.type] == t & [obj.value] == v);
end
function c_arr = get_cards_array(obj, t, v)
c_arr = obj(ismember([obj.type], t) & ismember([obj.value], v));
end
function print(obj)
for k = 1 : numel(obj)
fprintf('Card type = %g; value = %g\n', obj(k).type, obj(k).value);
end
end
end
end
以及用法:
%% build array
deck = Card.empty();
for type = 1 : 4
for value = 1 : 13
deck(end + 1, 1) = Card(type, value);
end
end
%% if needed, you can reshape it into 4x13
deck = reshape(deck, 4, 13);
%% you can also use Card's methods from array:
>> deck.print
Card type = 1; value = 1
Card type = 1; value = 2
Card type = 1; value = 3
...
%% get certain card
c = deck([deck.type] == 3 & [deck.value] == 10);
c.print
%% shuffle
idx = randperm(numel(deck));
deck = deck(idx);
更新:将 get_card() 添加到 Card 的方法中(参见实现):
>> c = deck.get_card(3, 10)
c =
Card handle
Properties:
type: 3
value: 10
Methods, Events, Superclasses
两个备注:
1) 如果这是您第一次使用 MatLAB 的 OOP,那么理解classdef Card < handle
.
2)这是一个关于对象数组初始化的问题:Matlab's arrayfun for uniform output of class objects
更新 2:添加了 get_cards_array() 方法。用法:
%% get array of cards
t = [1, 2];
v = [5, 6, 12];
c = deck.get_cards_array(t, v);
>> c.print
Card type = 1; value = 5
Card type = 1; value = 6
Card type = 1; value = 12
Card type = 2; value = 5
Card type = 2; value = 6
Card type = 2; value = 12