Here we demonstrate an example where the guess_game.py python program, which implements a guess the number game, is converted to jac-lang, which is shown in guess_game1.jac. This Transformation has a one-to-one mapping with the python program.
However, as the iterations progress in the game version you me discover fascinating changes which will show you the way of jac. The final implementation ins guess_game5.jac is the ultimate realization of jac using the data spatial architecture.
# type: ignore# flake8: noqaimportrandomclassGame:""" A generic Game base class. Initializes the number of attempts for the game and a play method, which is supposed to be implemented by subclasses. """def__init__(self,attempts):self.attempts=attemptsdefplay(self):raiseNotImplementedError("Subclasses must implement this method.")classGuessTheNumberGame(Game):""" A number guessing game. The player must guess a number between 1 and 100. This class inherits from Game. Represents a number guessing game where the player tries to guess a randomly chosen number between 1 and 100. The __init__ method initializes the number of attempts and generates a random number between 1 and 100. """def__init__(self,attempts=10):""" Initialize the game with a number of attempts and a randomly chosen number between 1 and 100. """super().__init__(attempts)self.correct_number=random.randint(1,100)defplay(self):""" Play the game. This method contains the main game loop. It prompts the player to input a guess and then calls the process_guess method to evaluate the guess. The loop continues until the player runs out of attempts. """whileself.attempts>0:guess=input("Guess a number between 1 and 100: ")ifguess.isdigit():self.process_guess(int(guess))else:print("That's not a valid number! Try again.")print("Sorry, you didn't guess the number. Better luck next time!")defprocess_guess(self,guess):""" Compares the player's guess with the correct number. If the guess is too high or too low, gives feedback to the player. If the guess is correct, it congratulates the player and ends the game by setting the remaining attempts to 0. After each guess, decrements the number of attempts and prints how many attempts are left. """ifguess>self.correct_number:print("Too high!")elifguess<self.correct_number:print("Too low!")else:print("Congratulations! You guessed correctly.")self.attempts=0# end the gameself.attempts-=1print(f"You have {self.attempts} attempts left.")# Run the gamegame=GuessTheNumberGame()game.play()
"""A Number Guessing Game"""import:py random;"""A generic Game base class.The obj keyword is used to define the class.The can keyword is used to define methods (functions) within the class.The self keyword is used to refer to the current instance of the class.Constructors are defined using the init method with parameters."""objGame{caninit(attempts:int){self.attempts=attempts;self.won=False;}canplay(){raiseNotImplementedError("Subclasses must implement this method.");}}"""A number guessing game. The player must guess a number between 1 and 100.This class inherits from Game. The super() function is used to call the parent class constructor."""objGuessTheNumberGame:Game:{caninit(attempts:int=10){super.init(attempts);self.correct_number=random.randint(1,100);}canplay(){whileself.attempts>0{guess=input("Guess a number between 1 and 100: ");ifguess.isdigit(){self.process_guess(int(guess));}else{print("That's not a valid number! Try again.");}}ifnotself.won{print("Sorry, you didn't guess the number. Better luck next time!");}}canprocess_guess(guess:int){ifguess>self.correct_number{print("Too high!");}elifguess<self.correct_number{print("Too low!");}else{print("Congratulations! You guessed correctly.");self.attempts=0;# end the gameself.won=True;}self.attempts-=1;print(f"You have {self.attempts} attempts left.");}}# Run the game"""Object instantiation and method invocation occur within the with entry { ... } block."""withentry{game=GuessTheNumberGame();game.play();}
"""A Number Guessing Game"""import:py random;"""A generic Game base class.Variables are initialized directly within the class definition using the has keyword, e.g., has attempts: int = 10.Default values are assigned directly within the class definition, e.g., has won: bool = False.Can keyword is used to define methods within the class definition, e.g., can play { ... }.But not like the guess_game1.jac, the play method is defined without parenthesis."""objGame{hasattempts:int,won:bool=False;canplay{raiseNotImplementedError("Subclasses must implement this method.");}}"""A number guessing game. The player must guess a number between 1 and 100."""objGuessTheNumberGame:Game:{hasattempts:int=10,correct_number:int=random.randint(1,100);canplay{whileself.attempts>0{guess=input("Guess a number between 1 and 100: ");ifguess.isdigit(){self.process_guess(int(guess));}else{print("That's not a valid number! Try again.");}}ifnotself.won{print("Sorry, you didn't guess the number. Better luck next time!");}}canprocess_guess(guess:int){ifguess>self.correct_number{print("Too high!");}elifguess<self.correct_number{print("Too low!");}else{print("Congratulations! You guessed correctly.");self.attempts=0;# end the gameself.won=True;}self.attempts-=1;print(f"You have {self.attempts} attempts left.");}}# Run the game"""Object instantiation and method invocation occur within the with entry { ... } block."""withentry{game=GuessTheNumberGame();game.play();}
"""A Number Guessing Game"""import:py random;"""A generic Game base class.In the following code |> is pipe forward operator, it assigns the lefthand side valuesas arguments of the right hand side function.i.e, "Hello" |> print is equivalent to print("Hello")"""objGame{hasattempts:int,won:bool=False;canplay{raise"Subclasses must implement this method."|>NotImplementedError;}}"""A number guessing game. The player must guess a number between 1 and 100."""objGuessTheNumberGame:Game:{hasattempts:int=10,correct_number:int=(1,100)|>random.randint;overridecanplay{whileself.attempts>0{guess="Guess a number between 1 and 100: "|>input;if|>guess.isdigit{guess|>int|>self.process_guess;}else{"That's not a valid number! Try again."|>print;}}ifnotself.won{"Sorry, you didn't guess the number. Better luck next time!"|>print;}}canprocess_guess(guess:int){ifguess>self.correct_number{"Too high!"|>print;}elifguess<self.correct_number{"Too low!"|>print;}else{"Congratulations! You guessed correctly."|>print;self.attempts=0;# end the gameself.won=True;}self.attempts-=1;f"You have {self.attempts} attempts left."|>print;}}# Run the gamewithentry{game=|>GuessTheNumberGame;|>game.play;}
"""A Number Guessing Game"""import:py random;"""A generic Game base class.Inside the Game class, we define a can play method that raises a NotImplementedError.This is way in jaclang to define abstract methods in base classes that must be implemented by subclasses.In this case it ensure that any subclass of Game must implement a play method."""objGame{hasattempts:int,won:bool=False;canplay;}"""A number guessing game. The player must guess a number between 1 and 100."""objGuessTheNumberGame:Game:{hascorrect_number:int=(1,100)|>random.randint;caninit;overridecanplay;canprocess_guess(guess:int);}"""The init method sets the number of attempts to 10.:ob:Game:can:play method is implemented to run the game. This another way in jaclang to add methods to a existing class.""":obj:Game:can:play{raise"Subclasses must implement this method."|>NotImplementedError;}:obj:GuessTheNumberGame:can:init{self.attempts=10;}:obj:GuessTheNumberGame:can:play{whileself.attempts>0{guess="Guess a number between 1 and 100: "|>input;if|>guess.isdigit{guess|>int|>self.process_guess;}else{"That's not a valid number! Try again."|>print;}}ifnotself.won{"Sorry, you didn't guess the number. Better luck next time!"|>print;}}:obj:GuessTheNumberGame:can:process_guess(guess:int){ifguess>self.correct_number{"Too high!"|>print;}elifguess<self.correct_number{"Too low!"|>print;}else{"Congratulations! You guessed correctly."|>print;self.attempts=0;# end the gameself.won=True;}self.attempts-=1;f"You have {self.attempts} attempts left."|>print;}# Run the gamewithentry{game=|>GuessTheNumberGame;|>game.play;}
"""A Number Guessing Game"""import:py random;"""In this code example, we implement a simple number guessing game using graph travesel."""walkerGuessGame{hascorrect_number:int=(1,100)|>random.randint;canstart_gamewith`rootentry;canprocess_guess(guess:int);}nodeturn{cancheckwithGuessGameentry;}:node:turn:can:check{guess="Guess a number between 1 and 100: "|>input;if|>guess.isdigit{guess|>int|>here.process_guess;}else{"That's not a valid number! Try again."|>print;}visit[-->];}:walker:GuessGame:can:start_game{end:`root|turn=here;fori=0toi<10byi+=1{end++>(end:=turn());}visit[-->];}:walker:GuessGame:can:process_guess(guess:int){ifguess>self.correct_number{"Too high!"|>print;}elifguess<self.correct_number{"Too low!"|>print;}else{"Congratulations! You guessed correctly."|>print;disengage;}}# # Run the gamewithentry{:>GuessGamespawnroot;}