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()を追加しました(実装を参照):
>> c = deck.get_card(3, 10)
c =
Card handle
Properties:
type: 3
value: 10
Methods, Events, Superclasses
2つの意見:
1)これがMatLABのOOPを初めて使用する場合は、の意味を理解することが非常に役立つ場合がありclassdef Card < handle
ます。
2)オブジェクト配列の初期化に関する質問があります:クラスオブジェクトの均一な出力のためのMatlabのarrayfun
更新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