Write a MATLAB function to play a modified version of the game of Yahtzee. This
ID: 657941 • Letter: W
Question
Write a MATLAB function to play a modified version of the game of Yahtzee. This function will have no input. The output arguments are a logical value (Y) and an n x 5 matrix of turns (rolls) The rules are as follows:
You have 3 turns in which to roll five dice with the same value (Yahtzee). On the first roll, all 5 dice are rolled. On subsequent rolls, fewer than five may be rolled. Choose what to keep by the using guidelines below. Reroll the dice that you do not keep. o Always keep 2 or more dice that match o Always keep the most matched dice (if you roll three 1s and two 6s, keep the 1s) o In case of a tie, keep the higher number (if you roll two 5s and two 3s, keep the 5s)
If Yahtzee, is rolled, return
Explanation / Answer
gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @yahtzee_OpeningFcn, ... 'gui_OutputFcn', @yahtzee_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin & isstr(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before yahtzee is made visible. function yahtzee_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % Choose default command line output for yahtzee handles.output = hObject; handles.version = '1.05'; handles.date = 'February 17, 2004'; % Update handles structure guidata(hObject, handles); init(handles); %%%%%%%%%%%%%%%%%% initialize %%%%%%%%%%%%%%%%%%%% function init(handles) home; handles.Dicecolor = 1; % default off handles.Sounds = 0; % default on handles.Autoroll = 1; % default off handles = resetdice(handles); enableundo(handles, 'off'); % hide set(handles.YBonustext, 'Visible', 'off'); set(handles.YBonusedit, 'Visible', 'off'); set(handles.YBonusedit, 'String', ''); set(handles.YBonusedit, 'Value', 0); % update handle structure guidata(handles.figure1, handles); % make sure all fields are cleared clearallfields(handles) %%%%%%%%%%%%%%%%%% reset dice to 0, roll = 0 %%%%%%%%%%%%%%%%%%%% function varargout = resetdice(handles) handles.rollnumber = 0; handles.dice = -1*ones(1,5); handles.diceunselected = ones(1,5); % set 'Visible', 'off'; axeshandles = getaxeshandles(handles); for k = 1:5 diceplot(-1, axeshandles(k), 0); end % Update handles structure guidata(handles.figure1, handles); drawselect(handles); if nargout varargout{1} = handles; end %%%%%%%%%%%%%% clear all texts from scoring boxes %%%%%%%%%%%%%%% function clearallfields(handles) fieldstoclear = {'Onesedit', 'Twosedit', 'Threesedit', 'Foursedit', 'Fivesedit', 'Sixesedit', ... 'Threeofakindedit', 'Fourofakindedit', 'Fullhouseedit', 'Smallstraightedit', ... 'Largestraightedit', 'Yahtzeeedit', 'Chanceedit', 'Totaledit', 'Bonusedit', ... 'Uppertotaledit', 'Lowertotaledit', 'Combinedtotaledit'}; points.earned = []; points.potential = []; for i = 1:length(fieldstoclear) h(i) = getfield(handles, fieldstoclear{i}); set(h(i), 'String', []); % clear displayed string set(h(i), 'UserData', points); % clear scores end % --- Outputs from this function are returned to the command line. function varargout = yahtzee_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on button press in rollbutton. function rollbutton_Callback(hObject, eventdata, handles) axeshandles = getaxeshandles(handles); rollnumber = handles.rollnumber; dice = handles.dice; % add rollingpatterns here switch rollnumber case 0 dicetoroll = 1:5; % roll all of them % unselect all of them handles.diceunselected = ones(size(handles.diceunselected)); drawselect(handles); case 3 beep return otherwise % 1 , 2 dicetoroll = find(handles.diceunselected == 1); end % compute new dice hand for i = dicetoroll dice(i) = fix(6*rand(1)) + 1; end handles.dice = dice; % plot new dice hand for i = 1:5 diceplot(dice(i), axeshandles(i), ~handles.Dicecolor); end handles.rollnumber = rollnumber + 1; guidata(hObject, handles); % don't set button enabling % play sound if you want if strcmp(get(handles.Menu_Sounds, 'Checked'), 'on') try [y, Fs] = wavread('dice-cup.wav'); wavplay(y, Fs, 'async'); end end % disable Undo if you roll again undotest = handles.rollnumber; if ~handles.Autoroll undotest = undotest - 1 ; end if undotest enableundo(handles, 'off'); end % go do scoring deal tryscoring(handles); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%% helper function for rollbutton_Callback %%%%%%%% function axeshandles = getaxeshandles(handles) axeshandles(1) = handles.Dice1_axes; axeshandles(2) = handles.Dice2_axes; axeshandles(3) = handles.Dice3_axes; axeshandles(4) = handles.Dice4_axes; axeshandles(5) = handles.Dice5_axes; %%% end function %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%% helper function for diceselect_Callback %%%%%%%% function selecthandles = getselecthandles(handles) selecthandles(1) = handles.Select1_axes; selecthandles(2) = handles.Select2_axes; selecthandles(3) = handles.Select3_axes; selecthandles(4) = handles.Select4_axes; selecthandles(5) = handles.Select5_axes; %%% end function % -------------------------------------------------------------------- function Menu_Game_Callback(hObject, eventdata, handles) %%%%%%%%%%% enable or disable the High Scores button %%%%%%%%%%%%% directory = dir; for l = 1:length(directory) % search for filename match(l) = strcmp(directory(l).name, 'high_scores.mat'); end if ~sum(match) set(handles.Menu_Scores, 'Enable', 'off'); else set(handles.Menu_Scores, 'Enable', 'on'); end % -------------------------------------------------------------------- function Menu_New_Callback(hObject, eventdata, handles) % hObject handle to Menu_New (see GCBO) % handles structure with handles and user data (see GUIDATA) Dicecolor = handles.Dicecolor; % get current options states Sounds = handles.Sounds; Autoroll = handles.Autoroll; handles = resetdice(handles); init(handles); % restart game handles.Dicecolor = Dicecolor; %restore options states handles.Sounds = Sounds; handles.Autoroll = Autoroll; handles.diceunselected = ones(size(handles.diceunselected)); guidata(hObject, handles); drawselect(handles); % use to reset colors on texts hf = tryscoring(handles); % now you have to reset disabling set(hf, 'Enable', 'off'); % -------------------------------------------------------------------- function Menu_Scores_Callback(hObject, eventdata, handles) % hObject handle to Menu_Scores (see GCBO) % handles structure with handles and user data (see GUIDATA) if ~isappdata(handles.figure1,'ScoresDlg') | ~ishandle(getappdata(handles.figure1,'ScoresDlg')) % Create dialog figure % scale from characters to pixels ScoresPosition = get(handles.figure1, 'Position') * 5; figProp.Name = 'High Scores'; figProp.NumberTitle = 'off'; figProp.Menubar = 'none'; figProp.Resize = 'on'; figProp.Position = ScoresPosition + [0 0 0 20]; figProp.Color = [.925 .914 .847]; hscores = figure(figProp); % Store dialog figure handle to the main figure's appdata setappdata(handles.figure1,'ScoresDlg', hscores); % Start creating the Axes hax = axes('units', 'normalized', 'visible', 'off', ... 'position', [0 0 1 1], 'parent', hscores); % Start creating the Text namesText = {'{fontsize{16}High Scores}'}; scoresText = {' '}; try load high_scores.mat for i = 1:length(data) namesText = deal( [namesText, {[num2str(i),'. ',data(i).name]} ] ); scoresText{i} = num2str(data(i).score); end % Place the names text htext = text(.03, .95, namesText, 'parent', hax, 'Color', [0.7 0.1 0.2]); set(htext, 'HorizontalAlignment', 'left', 'VerticalAlignment', 'top'); % Place the scores text htext = text(.75, .80, scoresText, 'parent', hax, 'Color', [0.7 0.1 0.2]); set(htext, 'HorizontalAlignment', 'left', 'VerticalAlignment', 'top'); end try % Button to close the Scores Dialog Box hclose = uicontrol('string','Close','parent',hscores,'units','pixels', ... 'position',[(ScoresPosition(3)-120)/2 15 60 20],'callback','closereq'); % Button to clear the high scores hclear = uicontrol('string','Clear All...','parent',hscores,'units','pixels', ... 'position',[(ScoresPosition(3)+60)/2 15 60 20],'callback', 'yahtzee(''clearscores_Callback'',gcbo,[],guidata(gcbo))'); end else % Dialog exists, so make it active figure(getappdata(handles.figure1,'ScoresDlg')); end % ------------------- clear high scores ------------------------------ function clearscores_Callback(hObject, eventdata, handles) answer = questdlg('Are you sure you want to clear the High Scores?'); if strcmp(answer, 'Yes') delete('high_scores.mat'); closereq end % -------------------------------------------------------------------- function Menu_Exit_Callback(hObject, eventdata, handles) closereq; % close the figure % -------------------------------------------------------------------- function Menu_Undo_Callback(hObject, eventdata, handles) return % unused % -------------------------------------------------------------------- function Menu_Unscore_Callback(hObject, eventdata, handles) % hObject handle to Menu_Unscore (see GCBO) % handles structure with handles and user data (see GUIDATA) unscore_data = get(hObject, 'UserData'); handles.dice = unscore_data.dice; handles.diceunselected = unscore_data.diceunselected; handles.rollnumber = unscore_data.rollnumber; guidata(hObject, handles); scoredObject = unscore_data.hObject; set(scoredObject, 'String', []); points.earned = []; points.potential = []; set(scoredObject, 'UserData', points); % plot new dice hand dice = handles.dice; axeshandles = getaxeshandles(handles); for i = 1:5 diceplot(dice(i), axeshandles(i), ~handles.Dicecolor); end handles = updatetotals(handles); drawselect(handles); tryscoring(handles); guidata(hObject, handles); return % -------------------------------------------------------------------- function Menu_Options_Callback(hObject, eventdata, handles) % unused % -------------------------------------------------------------------- function Menu_Colors_Callback(hObject, eventdata, handles) % hObject handle to Menu_Colors (see GCBO) % handles structure with handles and user data (see GUIDATA) checked = get(hObject, 'Checked'); onoff = {'on', 'off'}; % define constant setting = strcmp(checked, 'on'); % on = 1; off = 0 set(hObject, 'Checked', onoff{setting+1}); handles.Dicecolor = setting; %update handle structure guidata(hObject, handles); % -------------------------------------------------------------------- function Menu_Sounds_Callback(hObject, eventdata, handles) % hObject handle to Menu_Sounds (see GCBO) % handles structure with handles and user data (see GUIDATA) checked = get(hObject, 'Checked'); onoff = {'on', 'off'}; % define constant setting = strcmp(checked, 'on'); % on = 1; off = 0 set(hObject, 'Checked', onoff{setting+1}); handles.Sounds = setting; %update handle structure guidata(hObject, handles); % -------------------------------------------------------------------- function Menu_Autoroll_Callback(hObject, eventdata, handles) % hObject handle to Menu_Autoroll (see GCBO) % handles structure with handles and user data (see GUIDATA) checked = get(hObject, 'Checked'); onoff = {'on', 'off'}; % define constant setting = strcmp(checked, 'on'); % on = 1; off = 0 set(hObject, 'Checked', onoff{setting+1}); handles.Autoroll = setting; %update handle structure guidata(hObject, handles); % -------------------------------------------------------------------- function Menu_Help_Callback(hObject, eventdata, handles) % unused % -------------------------------------------------------------------- function Menu_Rules_Callback(hObject, eventdata, handles) if ~isappdata(handles.figure1,'RulesDlg') | ~ishandle(getappdata(handles.figure1,'RulesDlg')) % Create dialog figure screen = get(0, 'ScreenSize'); width = 375; height = 520; RulesPosition = [screen(3)-width-5 screen(4)-height-30 width height]; figProp.Name = 'Rules'; figProp.NumberTitle = 'off'; figProp.Menubar = 'none'; figProp.Resize = 'on'; figProp.Position = RulesPosition; figProp.Color = [.925 .914 .847]; hrules = figure(figProp); % Store dialog figure handle to the main figure's appdata setappdata(handles.figure1,'RulesDlg',hrules); % Start creating the Axes and Text hax = axes('units', 'normalized', 'visible', 'off', ... 'position', [0 0 1 1], 'parent', hrules); rulesText = {'{fontsize{16}Yahtzee}', ... ' You have 5 dice which you can roll. Each turn consists of'... ' up to 3 rolls. To start, you roll all the dice. You then', ... ' may score the roll or re-roll any or all of the dice. After', ... ' rolling three times, you must score the roll. ', ... ' Once you have scored the roll, you repeat until all 13 ', ... ' categories are filled. You may only score the unfilled ', ... ' categories; you may need to score zero in empty boxes.', ... ' ', ... '{fontsize{14}Scoring}',... ' In the top section, you score according to the number ',... ' of dice showing the number of 1''s, 2''s and so on.',... ' In the bottom section, you score if your throw belongs ',... ' to one of these special cases:',... 'Name Condition Score',... ' Three of a kind 3 dice of the same kind sum of all the dice',... ' Four of a kind 4 dice of the same kind sum of all the dice',... ' Full house 2 of one kind, 3 of another. 25 points',... ' Small straight 4 consecutive numbers 30 points',... ' Large straight 5 consecutive numbers 40 points',... ' Yahtzee 5 dice of the same kind 50 points',... ' Chance any combination sum of all the dice', ... '', ... 'A Bonus of 35 is earned if the total in the top section is >= 63.', ... 'A YAHTZEE Bonus may be earned on a duplicate Yahzee only',... ' if one Yahtzee was already scored in the appropriate box.',... 'If a Yahtzee is rolled and the Yahtzee box and the appropriate',... ' box in the upper section is filled, it may be used as a ',... ' Joker in the lower section.'}; try % Place the info text htext = text(.03, .98, rulesText, 'parent', hax, 'Color', [0.7 0.1 0.2]); set(htext, 'HorizontalAlignment', 'left', 'VerticalAlignment', 'top'); % Button to close the Rules Dialog Box hclose = uicontrol('string','Close','parent',hrules,'units','pixels', ... 'position',[(width-60)/2 10 60 20],'callback','closereq'); end else % Dialog exists, so make it active figure(getappdata(handles.figure1,'RulesDlg')); end % -------------------------------------------------------------------- function Menu_About_Callback(hObject, eventdata, handles) % First check to see if the dialog is open already if ~isappdata(handles.figure1,'aboutDlg') | ~ishandle(getappdata(handles.figure1,'aboutDlg')) % Create dialog figure screen = get(0, 'ScreenSize'); width = 160; height = 215; AboutPosition = [screen(3)-width-5 screen(4)-height-30 width height]; figProp.Name = 'About...'; figProp.NumberTitle = 'off'; figProp.Menubar = 'none'; figProp.Resize = 'on'; figProp.Position = AboutPosition; figProp.Color = [.925 .914 .847]; habout = figure(figProp); % Store dialog figure handle to the main figure's appdata setappdata(handles.figure1,'aboutDlg',habout); % Start creating the Axes and Text hax = axes('units', 'normalized', 'visible', 'off', ... 'position', [0 0 1 1], 'parent',habout); aboutText = { '{fontsize{16}Yahtzee}', ... ' ', ... ' Eric Burdette', ... [' Version ' handles.version], ... [' ' handles.date], ... '', ... 'This is my solitaire',... 'incarnation of the',... 'game Yahtzee'}; try % Place the info text htext = text(.05, .95, aboutText, 'parent', hax, 'Color', [0.7 0.1 0.2]); set(htext, 'HorizontalAlignment', 'left', 'VerticalAlignment', 'top'); % Button to close the About Dialog Box hclose = uicontrol('string','Close','parent',habout,'units','pixels', ... 'position',[(width-60)/2 15 60 20],'callback','closereq'); end else % Dialog exists, so make it active! figure(getappdata(handles.figure1,'aboutDlg')); end % --- Executes during object creation, after setting all properties. function Onesedit_CreateFcn(hObject, eventdata, handles) if ispc set(hObject,'BackgroundColor','white'); else set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor')); end % --- Executes during object creation, after setting all properties. function Twosedit_CreateFcn(hObject, eventdata, handles) if ispc set(hObject,'BackgroundColor','white'); else set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor')); end % --- Executes during object creation, after setting all properties. function Threesedit_CreateFcn(hObject, eventdata, handles) if ispc set(hObject,'BackgroundColor','white'); else set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor')); end % --- Executes during object creation, after setting all properties. function Foursedit_CreateFcn(hObject, eventdata, handles) if ispc set(hObject,'BackgroundColor','white'); else set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor')); end % --- Executes during object creation, after setting all properties. function Fivesedit_CreateFcn(hObject, eventdata, handles) if ispc set(hObject,'BackgroundColor','white'); else set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor')); end % --- Executes during object creation, after setting all properties. function Sixesedit_CreateFcn(hObject, eventdata, handles) if ispc set(hObject,'BackgroundColor','white'); else set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor')); end % --- Executes during object creation, after setting all properties. function Threeofakindedit_CreateFcn(hObject, eventdata, handles) if ispc set(hObject,'BackgroundColor','white'); else set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor')); end % --- Executes during object creation, after setting all properties. function Fourofakindedit_CreateFcn(hObject, eventdata, handles) if ispc set(hObject,'BackgroundColor','white'); else set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor')); end % --- Executes during object creation, after setting all properties. function Fullhouseedit_CreateFcn(hObject, eventdata, handles) if ispc set(hObject,'BackgroundColor','white'); else set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor')); end % --- Executes during object creation, after setting all properties. function Smallstraightedit_CreateFcn(hObject, eventdata, handles) if ispc set(hObject,'BackgroundColor','white'); else set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor')); end % --- Executes during object creation, after setting all properties. function Largestraightedit_CreateFcn(hObject, eventdata, handles) if ispc set(hObject,'BackgroundColor','white'); else set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor')); end % --- Executes during object creation, after setting all properties. function Yahtzeeedit_CreateFcn(hObject, eventdata, handles) if ispc set(hObject,'BackgroundColor','white'); else set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor')); end % --- Executes during object creation, after setting all properties. function Chanceedit_CreateFcn(hObject, eventdata, handles) if ispc set(hObject,'BackgroundColor','white'); else set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor')); end % --- Executes during object creation, after setting all properties. function Totaledit_CreateFcn(hObject, eventdata, handles) if ispc set(hObject,'BackgroundColor','white'); else set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor')); end % --- Executes during object creation, after setting all properties. function Bonusedit_CreateFcn(hObject, eventdata, handles) if ispc set(hObject,'BackgroundColor','white'); else set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor')); end % --- Executes during object creation, after setting all properties. function Uppertotaledit_CreateFcn(hObject, eventdata, handles) if ispc set(hObject,'BackgroundColor','white'); else set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor')); end % --- Executes during object creation, after setting all properties. function Lowertotaledit_CreateFcn(hObject, eventdata, handles) if ispc set(hObject,'BackgroundColor','white'); else set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor')); end % --- Executes during object creation, after setting all properties. function YBonusedit_CreateFcn(hObject, eventdata, handles) if ispc set(hObject,'BackgroundColor','white'); else set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor')); end % --- Executes during object creation, after setting all properties. function Combinedtotaledit_CreateFcn(hObject, eventdata, handles) if ispc set(hObject,'BackgroundColor','white'); else set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor')); end %%%%%%%%%%%%5 changes the state of "selected dice axes" %%%%%%% function diceselect_Callback(hObject,eventdata,handles) if ~handles.rollnumber % roll is 0, no change return else selecthandles = getselecthandles(handles); axeshandles = getaxeshandles(handles); % get index to dice currentObject = max( [(find(selecthandles == hObject)), (find(axeshandles == hObject))] ); % change the state of selection axes strstate = get( selecthandles(currentObject), 'Visible'); % get current state state = strcmp(strstate, 'on'); % on = 1, off = 0 handles.diceunselected( currentObject) = state; % change state array guidata(hObject, handles); % update the handles drawselect(handles); % update the drawing of selections end %%%%%%%%%%%%% helper function to draw selection changes %%%%%% function drawselect(handles) % changes the viewed state of dice selection axes selecthandles = getselecthandles(handles); selected = handles.diceunselected; onoff = {'on', 'off'}; % static variable for i = 1:length(selected) % go through all dice set( selecthandles(i), 'Visible', onoff{selected(i)+1}); % change state end %%%%%%%%%%%%%% enable or disable the undo button %%%%%%%%%%%%%%%% function enableundo(handles, onoff) h(1) = handles.Menu_Undo; h(2) = handles.Menu_Unscore; set(h, 'Enable', onoff); %%%%%%%%%%%%%%%% tryscoring %%%%%%%%%%%%%%%%% function varargout = tryscoring(handles) % set constant, fields handlefields = {'Onesedit', 'Twosedit', 'Threesedit', 'Foursedit', 'Fivesedit', 'Sixesedit', ... 'Threeofakindedit', 'Fourofakindedit', 'Fullhouseedit', 'Smallstraightedit', ... 'Largestraightedit', 'Yahtzeeedit', 'Chanceedit'}; textfields = {'Onestext', 'Twostext', 'Threestext', 'Fourstext', 'Fivestext', 'Sixestext', ... 'Threeofakindtext', 'Fourofakindtext', 'Fullhousetext', 'Smallstraighttext', ... 'Largestraighttext', 'Yahtzeetext', 'Chancetext'}; % test what points are scorable with given dice potentialpoints = scoring(handles.dice); % return what points have already been earned % get scoring and handles for k = 1:length(handlefields) % get handle to objects hf(k) = getfield(handles, handlefields{k}); ht(k) = getfield(handles, textfields{k}); % get already earned scores pointsdata = get(hf(k), 'Userdata'); earnedpoints{k} = pointsdata.earned; end % add Yahtzee bonus ability if potentialpoints{12} == 50 % Yahtzee scored! % make turn (roll) done handles.rollnumber = 3; guidata(handles.figure1, handles); if ~(handles.Sounds) % play bell if Sounds selected dingding; end if earnedpoints{12} == 50 % Bonus earned! cscore = get(handles.YBonusedit, 'Value') + 100; set(handles.YBonusedit, 'Value', cscore); set(handles.YBonusedit, 'String', num2str(cscore)); set(handles.YBonusedit, 'Visible', 'on'); set(handles.YBonustext, 'Visible', 'on'); end if ~isempty(earnedpoints{12}) % no bonus, but still Yahtzee potentialpoints(9:11) = {25,30,40}; % use wildcard scoring potentialpoints([7,8,13]) = {sum(handles.dice),sum(handles.dice),sum(handles.dice)}; end end for i = 1:length(potentialpoints) % update points and field enabling if isempty(earnedpoints{i}) % set the potential earned points pointsdata = get(hf(i), 'UserData'); pointsdata.potential = potentialpoints{i}; set(hf(i), 'UserData', pointsdata); set(hf(i), 'Enable', 'on'); else set(hf(i), 'Enable', 'off'); end % change text color of best options if isempty(earnedpoints{i}) & (potentialpoints{i} ~= 0) set(ht(i), 'ForegroundColor', [1.0 0 0]); else set(ht(i), 'ForegroundColor', [0 0 0]); end end if nargout varargout{1} = hf; end %%%%%%%%%%%%%%%% do scoring %%%%%%%%%%%%%%%%% function doscore_Callback(hObject,eventdata,handles) pointsdata = get(hObject,'UserData'); % get allowable points to current object pointsdata.earned = pointsdata.potential; set(hObject,'UserData', pointsdata); set(hObject,'String', num2str(pointsdata.earned)); % save current state unscore_data.dice = handles.dice; unscore_data.diceunselected = handles.diceunselected; unscore_data.rollnumber = handles.rollnumber; unscore_data.hObject = hObject; handles = resetdice(handles); [handles, hf, htxt, earnedpoints] = updatetotals(handles); % reset all to disabled set(hf, 'Enable', 'off'); set(htxt, 'ForegroundColor', [0 0 0]); gameover = isgameover(handles, earnedpoints); if ~gameover % if game is not over yet, allow Undo set(handles.Menu_Unscore, 'UserData', unscore_data); enableundo(handles, 'on'); end % if Auto roll, do button roll if ~handles.Autoroll rollbutton_Callback(handles.rollbutton, [], handles); end %%%%%%%%%%%%%%%% update totals %%%%%%%%%%%%%%%%% function varargout = updatetotals(handles) handlefields = {'Onesedit', 'Twosedit', 'Threesedit', 'Foursedit', 'Fivesedit', 'Sixesedit', ... 'Threeofakindedit', 'Fourofakindedit', 'Fullhouseedit', 'Smallstraightedit', ... 'Largestraightedit', 'Yahtzeeedit', 'Chanceedit'}; textfields = {'Onestext', 'Twostext', 'Threestext', 'Fourstext', 'Fivestext', 'Sixestext', ... 'Threeofakindtext', 'Fourofakindtext', 'Fullhousetext', 'Smallstraighttext', ... 'Largestraighttext', 'Yahtzeetext', 'Chancetext'}; % get all handles and already earned points for m = 1:length(handlefields) hf(m) = getfield(handles, handlefields{m}); htxt(m) = getfield(handles, textfields{m}); pointsdata = get(hf(m), 'Userdata'); earnedpoints{m} = pointsdata.earned; end % tally up totals totalarray(1) = sum(cell2mat(earnedpoints(1:6))); if (totalarray(1) >= 63) totalarray(2) = 35; % Bonus else totalarray(2) = 0; % no Bonus yet end totalarray(3) = totalarray(1) + totalarray(2); totalarray(4) = sum(cell2mat(earnedpoints(7:13))); % total equals upper and lower totals plus Yahtzee bonuses totalarray(5) = totalarray(3) + totalarray(4) + get(handles.YBonusedit, 'Value'); % update totals fields handletotals = {'Totaledit', 'Bonusedit', 'Uppertotaledit', 'Lowertotaledit', 'Combinedtotaledit'}; for n = 1:length(handletotals) htot(n) = getfield(handles, handletotals{n}); set(htot(n), 'String', num2str(totalarray(n)) ); set(htot(n), 'Value', totalarray(n) ); end varargout{1} = handles; if nargout > 1 varargout{2} = hf; varargout{3} = htxt; varargout{4} = earnedpoints; end %%%%%%%%%%%%%%%% isgameover %%%%%%%%%%%%%%%%% function bool = isgameover(handles, earnedpoints) %returns boolean 1 if game is over for i = 1:length(earnedpoints) if isempty(earnedpoints{i}) bool = 0; return % if any found not to be filled yet end end bool = 1; check_addhighscore(get(handles.Combinedtotaledit, 'Value'), handles) clearallfields(handles) %%%%%%%%%%%%%%%% updates high scores if necessary %%%%%%%%%%%%%% function check_addhighscore(yourscore, handles) try % see if the file exists load high_scores; filexists = 1; catch % it doesn't t = lasterr; filexists = ~any( strfind(t, 'Unable to read file') ); if filexists error('Matlab:check_addhighscores','unknown error'); end end nrecords = 5; % number of records to keep if filexists clear scores; for m = 1:size(data, 2) % get existing scores scores(m) = data(m).score; end [scores, indxs] = sort([scores, yourscore]); % ascending order indxs = fliplr(indxs); % sort descending [junk, addindex] = max(indxs); % determine where in the list you fall if addindex > nrecords; % off the range of high score list % you don't win. (not within range) % I'll show your score and warning off MATLAB:QUESTDLG:stringMismatch; button = questdlg(['Your Score: ',num2str(yourscore)],'Game Over','OK', 'default'); return % bail end % otherwise, append your name to lists, the sort it data(size(data,2)+1).score = yourscore; data = data(indxs); if size(data,2) == (nrecords+1) % lop off those over limit data(6) = []; end else % file doesn't exists, you are only data addindex = 1; data.score = yourscore; end % collects the name for high scoring prompt={'Please enter you name:'}; def={'Anonymous'}; % default dlgTitle='You have a HIGH SCORE!'; yournamecell = inputdlg(prompt, dlgTitle, 1, def); % add the returned name to data data(addindex).name = yournamecell{1}; if ~(handles.Sounds) [y, Fs] = wavread('applause.wav'); wavplay(y/3, Fs, 'async'); end save high_scores.mat data Menu_Scores_Callback([], [], handles); function dingding [y, Fs] = wavread('ding.wav'); wavplay([ repmat(y(500:3000),5,1);y(500:end)]/3, Fs, 'async'); % --- Executes on button press in Onesedit. function Onesedit_Callback(hObject, eventdata, handles)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.