How to resolve the algorithm 24 game step by step in the LiveCode programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm 24 game step by step in the LiveCode programming language

Table of Contents

Problem Statement

The 24 Game tests one's mental arithmetic.

Write a program that randomly chooses and displays four digits, each from 1 ──► 9 (inclusive) with repetitions allowed. The program should prompt for the player to enter an arithmetic expression using just those, and all of those four digits, used exactly once each. The program should check then evaluate the expression. The goal is for the player to enter an expression that (numerically) evaluates to 24.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm 24 game step by step in the LiveCode programming language

Source code in the livecode programming language

on mouseUp
    put empty into fld "EvalField"
    put empty into fld "AnswerField"
    put random(9) & comma & random(9) & comma & random(9) & comma & random(9) into fld "YourNumbersField"
end mouseUp

on keyDown k
    local ops, nums, allowedKeys, numsCopy, expr
    put "+,-,/,*,(,)" into ops
    put the text of fld "YourNumbersField" into nums
    put the text of fld "EvalField" into expr
    if matchText(expr & k,"\d\d") then 
        answer "You can't enter 2 digits together"
        exit keyDown
    end if
    repeat with n = 1 to the number of chars of expr
        if offset(char n of expr, nums) > 0 then
            delete char offset(char n of expr, nums) of nums
        end if
    end repeat
    put ops & comma & nums into allowedKeys
    if k is among the items of allowedKeys then
        put k after expr
        delete char offset(k, nums) of nums
        replace comma with empty in nums
        try
            put the value of merge("[[expr]]") into fld "AnswerField"
            if the value of fld "AnswerField" is 24 and nums is empty then
                answer "You win!"
            end if
        end try
        pass keyDown
    else
        exit keyDown
    end if
end keyDown

  

You may also check:How to resolve the algorithm Sum and product of an array step by step in the R programming language
You may also check:How to resolve the algorithm Colour bars/Display step by step in the ActionScript programming language
You may also check:How to resolve the algorithm Function composition step by step in the Objective-C programming language
You may also check:How to resolve the algorithm Stair-climbing puzzle step by step in the Groovy programming language
You may also check:How to resolve the algorithm Strip comments from a string step by step in the Applesoft BASIC programming language