Skip to content
Go back

Rock, Paper or Scissors: Game Logic with Python

Published:  at  08:52 PM

Get ready for a duel of wit, strategy, and… code! Who will win in this algorithmic battle of Rock, Paper, and Scissors? ⚔️

🔮 Problem Statement

Ana and Alejandro, two programming enthusiasts, have taken their rivalry to the ancient game of Rock, Paper, and Scissors. To automate the arduous task of determining the winner, we need your help.

The Challenge:

Write a function in Python that receives as input a series of Rock, Paper, and Scissors games and determines who has won overall.

Parameters:

Returns:

Examples:

>>> rock_paper_seasor([['r', 's'], ['s', 'r']])
'Tie'
>>> rock_paper_seasor([['r', 's']])
'Player 1'
>>> rock_paper_seasor([['s', 'r'], ['r', 'r']])
'Player 2'
>>> rock_paper_seasor([['p', 'p'], ['s', 's'], ['r', 's'], ['r', 'p']])
'Tie'

Additional Notes:

🧩 Step-by-Step Solution

The key to this solution lies in maintaining a score tracker that increases or decreases depending on who wins each game. Instead of making direct comparisons between the moves, we simplify the logic with nested conditionals that evaluate the winning combinations.

First, we initialize a variable called result to keep track of wins and losses. This variable will act as a thermometer of dominance in the game:

result = 0

Next, we iterate over each game in the games list. This for loop is the engine that drives the evaluation of each match:

for game in games:
    m1 = game[0]

Inside the loop, we assign the move of player 1 to the variable m1, which will serve as a reference point to determine the outcome of the game. We observe that we assume that player 1 always plays first.

Now comes the crucial part: evaluating who wins each game and updating the score. We use if and elif conditionals to check for possible winning combinations:

    if 's' in game and 'p' in game:
        result += -1 if m1 == 's' else 1
    elif 'p' in game and 'r' in game:
        result += -1 if m1 == 'p' else 1
    elif 'r' in game and 's' in game:
        result += -1 if m1 == 'r' else 1

In this block, we use the ternary operator condition ? value_if_true : value_if_false (in this case value_if_true if condition else value_if_false), a concise way to write an if-else in a single line. If player 1 wins the game (for example, playing scissors against paper), we subtract 1 from result. If player 2 wins, we add 1 to result.

Finally, after evaluating all the games, we determine the overall winner based on the value of result:

return 'Player 1' if result < 0 else 'Player 2' if result > 0 else 'Tie'

Here we use the ternary operator again. If result is negative, Player 1 has won. If it is positive, Player 2 has won. If it is zero, it is a tie.

Complete Solution:

def rock_paper_seasor(games):
	"level: medium; points: 6"
	result = 0
	for game in games:
		m1 = game[0]
		if 's' in game and 'p' in game:
			result += -1 if m1 == 's' else 1
		elif 'p' in game and 'r' in game:
			result += -1 if m1 == 'p' else 1
		elif 'r' in game and 's' in game:
			result += -1 if m1 == 'r' else 1
	return 'Player 1' if result < 0 else 'Player 2' if result > 0 else 'Tie'

🧠 Key Concepts

The proposed solution is based on fundamental pillars of programming. Iteration, through the for loop, allows us to process each game individually. Conditionals (if, elif) are essential to implement the game logic, determining the winner based on the moves. The ternary operator, for its part, offers a concise and elegant syntax to express simple decisions. Data structures, in this case, the list of lists games, are crucial to organize the input information efficiently.

The game logic is encapsulated in the move comparisons and the score update. Comparisons are used within the conditionals to determine if a move is winning or losing. Each of these concepts, although individually simple, are intertwined to create a robust and efficient solution.

Did you know that the time complexity of this function is O(n), where n is the number of games? This means that the execution time grows linearly with the number of games, making it efficient even for large datasets.

💫 Final Thoughts

This solution, although functional, can be further optimized. For example, we could use a dictionary to map the moves to numerical values, simplifying the comparisons. In addition, we could consider the possibility of extending the function to handle invalid inputs or to include other variants of the game, such as “Rock, Paper, Scissors, Lizard, Spock”.

If you enjoyed this analysis and want to delve deeper into the world of algorithms and problem solving, do not hesitate to explore other articles on our blog! Programming is an infinite universe of possibilities, and we invite you to discover it with us! 🚀



Next Post
Soft Drink Promotions: Calculate Your Free Bottles (Python)