I'm a self-taught programmer starting out with Python and my latest project is this game: It runs in the console, displays an equation, takes the user's answer, and increases your score if it's correct. Every level has 5 questions, and the operands get bigger each level. At the end of each level. It asks if you want to continue or quit.
I managed to get it down to 41 SLOC but I want to know if there are ways I don't know about to make it even shorter.
# ---- IMPORTS ----
from random import randint, choice
from re import search
from subprocess import run
# ---- VARIABLES ----
multis = [ -1, 1 ] # "Multipliers"
ops = [ "+", "-", "*", "/" ] # "Operators"
score = 0
level = 1
# ---- FUNCTIONS ----
def setQuestion():
global answer
global userInput
# Set the two operands and operator.
oper1 = randint( (level * 5), (level * 10) ) * choice( multis ) # "Operand 1"
oper2 = randint( 1, abs(oper1) ) * choice( multis ) # "Operand 2"
opsCheck = randint( 0, 3 )
# If the operator is division, subtract the modulus from {oper1} so that
# the quotient is an integer.
if( opsCheck == 3 ):
if( oper1 < 0 ):
oper1 -= ( abs(oper1) % oper2 ) * -1
else:
oper1 -= oper1 % oper2
# Display the question and get the answer.
userInput = input( (" {} {} {} = ?\n A: ").format(oper1, ops[opsCheck], oper2) )
# Set global {answer} to the solution.
answer = eval( ("{}{}{}").format(oper1, ops[opsCheck], oper2) )
def runLevel():
global score
# Each level has 5 questions
for i in range( 5 ):
# Clear the screen each level (Unix-Like).
run( "clear", shell = True )
# Print the header and run the question.
print( ("\t---- LEVEL {}: ----\n").format(level) )
setQuestion()
# If correct, increase score. If not, display correct answer.
if( int(userInput) == answer ):
print( "\n Correct!" )
score += 1
else: print( ("\n Incorrect. Sorry.\n The answer was {}.").format(answer) )
# Wait for user input to move on to the next question.
input( "\n (Press any key to advance)" )
# ---- MAIN ----
# Program will run continuously
while( True ):
# Go through one level
runLevel()
# Clear and display "Level Complete" Screen and player score.
run( "clear", shell = True )
print( ("\t--- LEVEL {} COMPLETE! ---").format(level) )
userInput = input( ("\n Your score is {}\n Continue? (y/n) ").format(score) )
# If user enters "y" or "Y", increase global {level} by one and restart.
if( search("y|Y", userInput) ):
level += 1
continue
# If user does not enter "y" or "Y", clear screen and terminate.
run( "clear", shell = True )
exit()
```
oper1 -= -(abs(oper1) % oper2) if (oper1 < 0) else (oper1 % oper2)after theif( opsCheck == 3 ):line? these kind of if-else statements can be written in a single line. But it is pretty ugly... \$\endgroup\$