What's the best way to stop a for loop when an element is pressed?
Anonymous in /c/coding_help
599
report
Hi everyone, I've been working on a simple rock, paper, scissors project that asks the user how many rounds they want to play, and it does a simple for loop to do the rounds.<br><br>I want to know how to be able to stop this for loop if, for example, the user clicks a button "Stop game" without having to wait for the for loop to finish all the rounds.<br><br>I'm using Tkinter for this.<br><br>My idea is to put a boolean in a tkinter variable, add an if to the loop, and change the boolean when the button is pressed.<br><br>I could also be totally wrong because I am very new to coding, and I'd appreciate any suggestions on doing this.<br><br>Here is a simple example on how my code is working now.<br><br>```python<br>import tkinter as tk<br>from random import choice<br>from tkinter import messagebox<br><br>class RockPaperScissors:<br> def __init__(self):<br> self.window = tk.Tk()<br> self.rounds_label = tk.Label(self.window, text="Rounds")<br> self.rounds_label.pack()<br> self.rounds_entry = tk.Entry(self.window)<br> self.rounds_entry.pack()<br> self $('[Play').pack()<br> self.game_button = tk.Button(self.window, text="Stop game", command=self.stop)<br> self.game_button.pack()<br><br> self.playing = tk.BooleanVar()<br> self.playing.set(True)<br><br> def play(self):<br> if self.playing.get():<br> number_of_rounds = int(self.rounds_entry.get())<br> for x in range(number_of_rounds):<br> user_choice = input(f'Round {x+1}:\nEnter a choice (rock, paper,sicssors): ').lower()<br> while user_choice not in ['rock', 'paper', 'scissors']:<br> user_choice = input(f'Round {x+1}:\nEnter a choice (rock, paper,sicssors): ').lower()<br> possible_choices = ['rock', 'paper', 'scissors']<br> computer_choice = choice(possible_choices)<br> print(f'\nYou chose {user_choice}, computer chose {computer_choice}.\n')<br> if user_choice == computer_choice:<br> print(f'Both players selected {user_choice}. It\'s a tie!')<br> elif user_choice == 'rock':<br> if computer_choice == 'scissors':<br> print('Rock smashes scissors! You win!')<br> else:<br> print('Paper covers rock! You lose.')<br> elif user_choice == 'paper':<br> if computer_choice == 'rock':<br> print('Paper covers rock! You win!')<br> else:<br> print('Scissors cuts paper! You lose.')<br> elif user_choice == 'scissors':<br> if computer_choice == 'paper':<br> print('Scissors cuts paper! You win!')<br> else:<br> print('Rock smashes scissors! You lose.')<br> self.playing.set(False)<br> else:<br> messagebox.showinfo("Game has been stopped", "Game has been stopped")<br> <br> def stop(self):<br> self.playing.set(False)<br><br> def run(self):<br> self.window.mainloop()<br><br>if __name__ == "__main__":<br> game = RockPaperScissors()<br> game.run()<br>```<br><br>Thank you.
Comments (13) 23703 👁️