#python
#python
Вопрос:
Я новичок в программировании, поэтому пытаюсь создать игру «Камень, ножницы, бумага». Я почти завершил игру, но когда пользователь и компьютер вводят одинаковое число, я хочу, чтобы программа повторялась до тех пор, пока один из игроков не выиграет. Как я могу это сделать? Любая помощь приветствуется. Вот мой код.
game = input("Want to play Rock Paper Scissors? (Y/N) ")
if game == "Y":
print("1 = Rock, 2 = Paper, 3 = Scissors")
print('')
user = int(input("You have one chance of beating me. Input a number. "))
print('')
import random
computer = random.randint(1,3)
if user == 1 and computer == 1:
print("Must play again! We both played Rock!")
elif user == 1 and computer == 2:
print("You lose! You played Rock and I played Paper!")
elif user == 1 and computer == 3:
print("You win! You played Rock and I played Scissors!")
elif user == 2 and computer == 1:
print("You win! You played Paper and I played Rock!")
elif user == 2 and computer == 2:
print("Must play again! We both played Paper!")
elif user == 2 and computer == 3:
print("You lose! You played Paper and I played Scissors!")
elif user == 3 and computer == 1:
print("You lose! You played Scissors and I played Rock!")
elif user == 3 and computer == 2:
print("You win! You played Scissors and I played Paper!")
elif user == 3 and computer == 3:
print("Must play again! We both played Scissors!")
else:
print("Not a number.")
else:
print("Fine. Bye.")
Комментарии:
1. Поместите этот код в
while True
2. Что это дает?
3. Бесконечный цикл .
Ответ №1:
Вы могли бы поместить весь if-elif-блок в цикл while, который будет повторяться до тех пор, пока у вас не будет победителя. Чтобы определить, есть ли победитель, используйте логическую переменную.
winner = False
while not winner:
if ...... ## Your if-elif-block
elif user == 1 and computer == 2:
print("You lose! You played Rock and I played Paper!")
winner = True
## Your remaining if-elif-block
Вы помещаете команду winner=True
только в командные блоки условий, в которых есть победитель. Итак, цикл будет продолжаться до тех пор, пока вы не выполните одно из этих условий.
Вы также могли бы использовать более продвинутую переменную победителя (0 для ничьей, 1 для игрока, 2 для компьютера), чтобы использовать значение в прощальном сообщении.
Ответ №2:
Одним из способов было бы использовать цикл while, прерывающийся при выполнении условия.
while True:
if (condition):
print("")
break
...
Оператор while повторяет цикл до тех пор, пока не будет выполнено одно из условий. Оператор break заставляет программу выйти из цикла и перейти к следующему исполняемому оператору.
Ответ №3:
(чтобы узнать больше, загуглите что-нибудь в кавычках 🙂
использование «цикла while» для создания «игрового цикла». Я научился этому при создании небольших игр на Python. Кроме того, вы хотите научиться использовать «классы», поскольку логику и код можно улучшить, используя «концепции ООП».T-код был протестирован и работает.
import random
#Create a "function" that meets the requirements of a "game loop"
def gameloop():
game = input("Want to play Rock Paper Scissors? (Y/N) ")
if game == "Y":
#Create a "while loop" to host the logic of the game.
#Each If statement will enable one "rule" of the game logic.
#game logic could be redesigned as an "Event".
#You can add a game "Event System" to your future project backlog
winner = False
while not winner:
print("1 = Rock, 2 = Paper, 3 = Scissors")
print('')
user = int(
input("You have one chance of beating me. Input a number. "))
print('')
computer = random.randint(1, 3)
if user == 1 and computer == 2:
print("You lose! You played Rock and I played Paper!")
winner = True
elif user == 1 and computer == 3:
print("You win! You played Rock and I played Scissors!")
winner = True
elif user == 2 and computer == 1:
print("You win! You played Paper and I played Rock!")
winner = True
elif user == 2 and computer == 3:
print("You lose! You played Paper and I played Scissors!")
winner = True
elif user == 3 and computer == 1:
print("You lose! You played Scissors and I played Rock!")
winner = True
elif user == 3 and computer == 2:
print("You win! You played Scissors and I played Paper!")
winner = True
elif user == 1 and computer == 1:
print("Must play again! We both played Rock!")
elif user == 2 and computer == 2:
print("Must play again! We both played Paper!")
elif user == 3 and computer == 3:
print("Must play again! We both played Scissors!")
else:
print("Not a number.")
else:
print("game....over?")
gameloop()
Я тоже нашел время, чтобы создать пример класса ООП! его можно было бы оптимизировать многими способами. Тем не менее, я надеюсь, что это покажет вам следующий уровень изучения! Я также надеюсь, что это поможет вам разобраться во всех сумасшедших шаблонах проектирования и методах программирования игр, которые вы можете применить по мере обучения.
import random
# we can create a player class to be used as an "interface" as we design the games logic
# this will let us scale the features be build in our game
# in this case i will leave it to you to add Wins to the scoreboard to help you learn
class player:
# your games requerment wants your players to make a choice from 1-3
choice = 0
# your games may requerment a player to be defined as the winner
win = 0
# your games may requerment a player to be defined as the losser
loss = 0
class game:
# by using classes and OOP we can scale the data and logic of your game
# here we create instances of the class player and define new objects based on your "requerments"
# your "requerments" where to have one Computer as a player, and one user as a player
computer = player()
user = player()
# this "function" will create a Scoreboard feature that can be called in the 'game loop' or in a future "event" of the game.
# Like a "Game Stats stage" at the end of the game
def Scoreboard(self, computer, user):
Computer = computer.loss
User = user.loss
print(" ============= FINAL RESULTS: SCOREBOARD!! ====== ")
print(" ")
print("Computer losses: ", Computer)
print("Player losses: ", User)
print(" ")
# Create a "function" that meets the requirements of a "game loop"
def main_loop(self, computer, user):
gameinput = input("Want to play Rock Paper Scissors? (Y/N) ")
if gameinput == "Y":
# Create a "while loop" to host the logic of the game.
# Each If statement will enable one "rule" of the game logic.
# game logic could be redesigned as an "Event".
# You can add a game "Event System" to your future project backlog
winner = False
while not winner:
print("1 = Rock, 2 = Paper, 3 = Scissors")
print('')
# we create 'Player1' as the user
Player1 = user
# we change the 'Player1' 'choice' to the user input
Player1.choice = int(
input("You have one chance of beating me. Input a number. "))
print('')
# we pull in to the game the computer player and call them 'Player1'
Player2 = computer
# we change the 'Player2' 'choice' to a random number
Player2.choice = random.randint(1, 3)
if user.choice == 1 and computer.choice == 2:
print("You lose! You played Rock and I played Paper!")
winner = True
user.loss = 1
elif user.choice == 1 and computer.choice == 3:
print("You win! You played Rock and I played Scissors!")
winner = True
computer.loss = 1
elif user.choice == 2 and computer.choice == 1:
print("You win! You played Paper and I played Rock!")
winner = True
computer.loss = 1
elif user.choice == 2 and computer.choice == 3:
print("You lose! You played Paper and I played Scissors!")
winner = True
user.loss = 1
elif user.choice == 3 and computer.choice == 1:
print("You lose! You played Scissors and I played Rock!")
winner = True
user.loss = 1
elif user.choice == 3 and computer.choice == 2:
print("You win! You played Scissors and I played Paper!")
winner = True
computer.loss = 1
elif user.choice == 1 and computer.choice == 1:
print("Must play again! We both played Rock!")
elif user.choice == 2 and computer.choice == 2:
print("Must play again! We both played Paper!")
elif user.choice == 3 and computer.choice == 3:
print("Must play again! We both played Scissors!")
else:
print("Not a number.")
# by returning "self" you call the same 'instances' of game that you will define below
return self.Scoreboard(user, computer)
else:
print("game....over?")
# define Instance of game as "test_game"
test_game = game()
# run game loop
test_game.main_loop()