import random
def game():
def display_instructions():
""" Will print out instructions for how to play tic-tac-toe"""
print("Hello, and welcome to TIC-TAC-TOE! Here's how you play: you will choose whether you want to be X or O. I will tell you who is going first. When it is your turn, you will choose any number from zero to eight. The number you choose corresponds to the space you will be putting your letter in. Be careful not to choose a space already occupied by a letter! You will have to enter a new number. Your goal is to beat ME. The first one to get to three-in-a-row, sideways, up-and-down, or diagonally, wins. May the best man win.")
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("LET'S BEGIN")
display_instructions()
def assign_x_o():
""" Allows the user to choose whether to be X or O """
player_letter = input("Would you like to be X or O?")
return player_letter
player_letter = assign_x_o()
def tell_letter():
""" Tells the user who will be X and who will be O """
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("You will be", player_letter.upper() + "!")
if player_letter.upper() == "X":
print("I will be O!")
else:
print("I will be X!")
tell_letter()
not_used = [0, 1, 2, 3, 4, 5, 6, 7, 8]
def computer_letter():
""" Assigns the computer letter to whatever the player letter is not """
if player_letter.upper() == "X":
comp_letter = "O"
else:
comp_letter = "X"
return comp_letter
comp_letter = computer_letter()
board_list = ["0","1","2","3","4","5","6","7","8"]
def display_board():
""" Prints the Tic-Tac-Toe board """
print(board_list[0] + "|" + board_list[1] + "|" + board_list[2])
print("-+-+-")
print(board_list[3] + "|" + board_list[4] + "|" + board_list[5])
print("-+-+-")
print(board_list[6] + "|" + board_list[7] + "|" + board_list[8])
display_board()
def ask_num():
""" Asks the user to input a number from 0-8, corresponding to the spot to which they would like to move """
user_turn = input("Which place would you like to move to? (Input a number, 0-8)")
return user_turn
def second_board(board_list):
""" Creates a second board with which to test possible moves for the computer """
new_board = []
for i in board_list:
new_board.append(i)
return new_board
def check_win(board_list, player_letter, comp_letter):
""" Checks to see if there are three of X or O in a row (up, down, and diagonal) """
if board_list[0] == board_list[1] == board_list[2]:
return True
if board_list[3] == board_list[4] == board_list[5]:
return True
if board_list[6] == board_list[7] == board_list[8]:
return True
if board_list[0] == board_list[3] == board_list[6]:
return True
if board_list[1] == board_list[4] == board_list[7]:
return True
if board_list[2] == board_list[5] == board_list[8]:
return True
if board_list[0] == board_list[4] == board_list[8]:
return True
if board_list[2] == board_list[4] == board_list[6]:
return True
return False
def test_moves(board_list, player_letter, comp_letter, i):
""" Tests possible moves for the computer on a duplicate tic tac toe board """
new_board = second_board(board_list)
new_board[i] = player_letter.upper()
return check_win(board_list, player_letter, comp_letter)
def win_in_one(board_list):
temp_board = board_list
print(not_used)
for i in not_used:
for i in range(0, 1):
temp_board[i] = comp_letter
if check_win(temp_board, player_letter, comp_letter) == True:
win = True
if win == True:
return i
else:
win = check_win(temp_board, player_letter, comp_letter) == False
return win
def lose_in_one(board_list):
temp_board = board_list
for i in not_used:
for i in range(0, 1):
temp_board[i] = player_letter
if check_win(temp_board, player_letter, comp_letter) == True:
lose = True
if lose == True:
temp_board[i] = comp_letter
return i
else:
lose = False
return lose
def computer_turn(board_list):
""" Chooses which index value to use based on available spaces; first checks open corners, then the center, then the remaining side spaces """
win_in_one(board_list)
lose_in_one(board_list)
for i in range(0, 8):
if board_list[i] != "X" and board_list[i] != "O" and test_moves(board_list, player_letter, comp_letter, i):
return i
for i in range(0, 8):
if board_list[i] != "X" and board_list[i] != "O" and test_moves(board_list, player_letter, comp_letter, i):
return i
for i in [0, 2, 6, 8]:
if board_list[i] != "X" and board_list[i] != "O":
return i
if board_list[4] != "X" and board_list[4] != "O":
return 4
for i in [1, 3, 5, 7]:
if board_list[i] != "X" and board_list[i] != "O":
return i
def draw_message():
""" Prints a message notifying the user that the game has ended in a tie """
print("This game has ended in a tie!")
play_again = input("Would you like to play again? (y/n) ")
if play_again.lower() == "y":
keep_playing()
else:
print("No worries. Let's play again soon!")
def keep_playing():
""" Calls the game function again if the user chooses to continue playing """
game()
def congrats():
""" Decides whether or not to congratulate the user or to tell them the computer won; also gives the option to play the game again """
if board_list[0] == board_list[1] == board_list[2] == player_letter.upper():
print("Congrats! You are the winner!")
play_again = input("Would you like to play again? (y/n) ")
if play_again.lower() == "y":
keep_playing()
else:
print("No worries. Let's play again soon!")
elif board_list[3] == board_list[4] == board_list[5] == player_letter.upper():
print("Congrats! You are the winner!")
play_again = input("Would you like to play again? (y/n) ")
if play_again.lower() == "y":
keep_playing()
else:
print("No worries. Let's play again soon!")
elif board_list[6] == board_list[7] == board_list[8] == player_letter.upper():
print("Congrats! You are the winner!")
play_again = input("Would you like to play again? (y/n) ")
if play_again.lower() == "y":
keep_playing()
else:
print("No worries. Let's play again soon!")
elif board_list[0] == board_list[3] == board_list[6] == player_letter.upper():
print("Congrats! You are the winner!")
play_again = input("Would you like to play again? (y/n) ")
if play_again.lower() == "y":
keep_playing()
else:
print("No worries. Let's play again soon!")
elif board_list[1] == board_list[4] == board_list[7] == player_letter.upper():
print("Congrats! You are the winner!")
play_again = input("Would you like to play again? (y/n) ")
if play_again.lower() == "y":
keep_playing()
else:
print("No worries. Let's play again soon!")
elif board_list[2] == board_list[5] == board_list[8] == player_letter.upper():
print("Congrats! You are the winner!")
play_again = input("Would you like to play again? (y/n) ")
if play_again.lower() == "y":
keep_playing()
else:
print("No worries. Let's play again soon!")
elif board_list[0] == board_list[4] == board_list[8] == player_letter.upper():
print("Congrats! You are the winner!")
play_again = input("Would you like to play again? (y/n) ")
if play_again.lower() == "y":
keep_playing()
else:
print("No worries. Let's play again soon!")
elif board_list[2] == board_list[4] == board_list[6] == player_letter.upper():
print("Congrats! You are the winner!")
play_again = input("Would you like to play again? (y/n) ")
if play_again.lower() == "y":
keep_playing()
else:
print("No worries. Let's play again soon!")
else:
print("Uh oh. Looks like I won! Better luck next time!")
play_again = input("Would you like to play again? (y/n) ")
if play_again.lower() == "y":
keep_playing()
else:
print("No worries. Let's play again soon!")
tf_list = ["True", "False"]
user_first = random.choice(tf_list)
def first_turn():
""" Uses user_first random choice to decide if the computer or user goes first, then prints who will start; if user starts, user will input a number and the board will be displayed; if computer starts, computer will take turn and display board"""
if user_first == "True":
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("You will start!")
user_turn = int(ask_num())
if board_list[user_turn] != "X" and board_list[user_turn] != "O":
board_list[user_turn] = player_letter.upper()
not_used.remove(user_turn)
print(not_used)
display_board()
else:
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("The computer will start!")
if board_list[computer_turn(board_list)] != "X" and board_list[computer_turn(board_list)] != "O":
board_list[computer_turn(board_list)] = comp_letter
not_used.remove(computer_turn(board_list))
display_board()
first_turn()
def next_turn(user_first):
""" While playing, the computer and user will alternate turns. Upon either of them achieving three-in-a-row or a draw occurring, the user will be asked if they want to play again."""
turns = 1
still_playing = True
while still_playing == True:
if user_first == "True":
user_first = "False"
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("It is the computer's turn.")
if board_list[computer_turn(board_list)] != "X" or "O":
board_list[computer_turn(board_list)] = comp_letter
turns += 1
not_used.remove(computer_turn(board_list))
display_board()
if check_win(board_list, player_letter, comp_letter):
congrats()
still_playing = False
elif check_win(board_list, player_letter, comp_letter) == False:
still_playing = True
if turns == 9:
draw_message()
still_playing = False
else:
next_turn(user_first)
else:
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("It is the user's turn.")
user_turn = int(ask_num())
if board_list[user_turn] != "X" or "O":
board_list[user_turn] = player_letter.upper()
turns += 1
not_used.remove(user_turn)
display_board()
user_first = "True"
else:
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print("INVALID MOVE. GO AGAIN.")
next_turn(user_first)
if check_win(board_list, player_letter, comp_letter):
congrats()
still_playing = False
elif check_win(board_list, player_letter, comp_letter) == False:
if turns == 9:
draw_message()
still_playing = False
else:
next_turn(user_first)
next_turn(user_first)
game()
Errors are popping up when the user takes their turn, and I don't know why. I'm trying to make the computer insert its letter if it can win in one move or block the user from winning. I know there is an issue with the win_in_one and lose_in_one functions, but I have done countless troubleshooting and have been unable to find a solution. If you could help me sort out my error or give suggestions to fix win_in_one and lose_in_one functions, it would be greatly appreciated.
You could use this compact Computer player function as your AI:
from random import sample
axes = [(0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)]
def isWin(board):
return any(board[a]+board[b]+board[c] in ["XXX","OOO"] for a,b,c in axes)
#level 3**3=Naive, 3**4=beginner, 3**5=intermediate, 3**6=good, 3**7=expert
def rating(position,play,board,level=3**6):
if board[position] != " " or level < 3: return 0
newBoard = board[:position]+[play]+board[position+1:]
if isWin(newBoard): return level*2
nextRatings = [rating(p,"XO"[play=="X"],newBoard,level/3) for p in range(9)]
return level-max(nextRatings,key=abs)
To make the computer play (with some randomness), use this line where computer is the letter that the computer plays ("X" or "O") and board is a list of board positions (indexed from 0 to 8) containing "X", "O" or a space character:
position = max(sample(range(9),9),key=lambda p:rating(p,computer,board))
Here is some sample code using the computer playing function:
while True:
board = [" "]*9
player,computer = sample("XOXO",2)
player = computer
print(player,computer)
while True:
for r in range(0,9,3):
print("("+") (".join(board[r:r+3])+")",list(range(r+1,r+4)))
available = [str(p+1) for p in range(9) if board[p] == " "]
if isWin(board) or not available : break
player = "XO"[player=="X"]
if player == computer:
position = max(sample(range(9),9),key=lambda p:rating(p,computer,board))
print(f"Computer plays {player} at {position+1}")
else:
while True:
position = input(f"Position to play for {player}: ")
if position not in available: print("Invalid position")
else : position = int(position)-1; break
board[position] = player
print( f"{player}'s WIN !!!\n" if isWin(board) else "DRAW.\n")
Related
I am a new learner on Python, I created a game to roll 3 dices randomly. I want to know how to go back to the "play" under "else". Please check my screenshot
import random
game = False
game1 = False
def roll():
money = 0
while game == False :
money += 1
key = input("Please hit 'y' to roll the 3 dicks: ")
if key == "y":
roll1 = random.randint(0,10)
roll2 = random.randint(0,10)
roll3 = random.randint(0,10)
print("Roll 1,2,3 are: ", roll1, roll2, roll3)
else:
print("Invalid input, try again")
return roll()
if roll1 == roll2 == roll3:
money +=1
print("You Win!")
print("Your award is ", money)
game == False
else:
play = input("Loss, try again? y or n? ")
if play == "y":
money -= 1
game == False
elif play == "n":
break
else:
??????????????????????
roll()
You can just put it inside a while loop there:
else:
while True: # you can
play = input("Loss, try again? y or n? ")
if play == "y":
money -= 1
game == False
elif play == "n":
break
else:
pass
I have written up a Tic Tac Toe game however there seems to be an error.
None of the players have won, nor there still exists "-" in board, the game just ends to a draw after some playing.
(Please see in def check(): last elif statement.)
Could you please help me what is wrong with the code?
(Sorry I am a beginner and please excuse the lack of my code)
Here is my code below:
import sys
board = [["-","-","-"],["-","-","-"],["-","-","-"]]
def print_board():
for x in board:
print(" ".join(x))
P1X = input("Hi Player 1. What is your name? ")
P2O = input("Hi Player 2. What is your name? ")
def play_again():
answer = input("It is a draw!. Do you want to play again? Y/N ").upper()
if answer == "Y":
play_game()
else:
sys.exit()
def check():
if board[0][0] == board[0][1] == board[0][2]:
check_win(0, 0)
elif board[0][0] == board[1][0] == board[2][0]:
check_win(0, 0)
elif board[0][0] == board[1][1] == board[2][2]:
check_win(0, 0)
elif board[0][1] == board[1][1] == board[2][1]:
check_win(1, 1)
elif board[0][2] == board[1][2] == board[2][2]:
check_win(2, 2)
elif board[1][0] == board[1][1] == board[1][2]:
check_win(1, 1)
elif board[2][0] == board[2][1] == board[2][2]:
check_win(2, 2)
elif board[0][2] == board[1][1] == board[2][0]:
check_win(1, 1)
elif "-" not in board:
print("It is a draw!")
play_again()
else:
pass
def check_win(row,col):
if board[row][col] == 'X':
print_board()
print("{0} has won the game. Game Over!".format(P1X))
play_again()
elif board[row][col] == "O":
print_board()
print("{0} has won the game. Game Over!".format(P2O))
play_again()
else:
pass
count = 0
def place(row, col):
if count == 0:
board[row][col] = "X"
else:
board[row][col] = "O"
def play_game():
global count
print("Please start the game {0}".format(P1X))
while count != 892:
row_input = int(input("Please select the row ")) -1
col_input = int(input("Please select the column ")) -1
place(row_input, col_input)
check()
print_board()
if count == 0:
count = 1
print("It is now {0}'s turn".format(P2O))
else:
count = 0
print("It is now {0}'s turn".format(P1X))
play_game()
Your program doesn't define check_win, so I am not sure how it works at all. Your problem, however, is that you use a list of rows as your board representation, presumably starting with each board element as '-' to indicate unplayed spaces.
Depending on the rest of your code you might find it easier to use a dictionary as the board representation, with two-element tuples as subscripts.
As the code is now that last test would need to be modified to test that no row contains a '-', which you could do with the test:
if not any('-' in row for row in board):
At present you are comparing lists with strings. That's never going to give you equality.
I'm making a 2-play Battleship game in python and have been struggling with this for a while now:
I apologise if the question is poorly worded but I was to know how I can make my game log the match score at the end of the three games with something like:
print('Match score is' + score + 'Player' + (whoever) + 'wins!)
I'm not entirely sure how to implement this myself I have a range for games in range(3), but I don't know how to log the final score.
Also, how can I change the symbol for player_two so that I am not using an 'X' for both players? I've tried changing the input_check() but I get more errors than I did before.
from random import randint
game_board = []
player_one = {
"name": "Player 1",
"wins": 0,
"lose": 0
}
player_two = {
"name": "Player 2",
"wins": 0,
"lose": 0
}
# Building our 5 x 5 board
def build_game_board(board):
for item in range(5):
board.append(["O"] * 5)
def show_board(board):
print("Find and sink the ship!")
for row in board:
print(" ".join(row))
# Defining ships locations
def load_game(board):
print("WELCOME TO BATTLESHIP!")
print("START")
del board[:]
build_game_board(board)
show_board(board)
ship_col = randint(1, len(board))
ship_row = randint(1, len(board[0]))
return {
'ship_col': ship_col,
'ship_row': ship_row,
}
ship_points = load_game(game_board)
# Players will alternate turns.
def player_turns(total_turns):
if total_turns % 2 == 0:
total_turns += 1
return player_one
else:
return player_two
# Allows new game to start
def play_again():
global ship_points
answer = input("Would you like to play again? ")
if answer == "yes" or answer == "y":
ship_points = load_game(game_board)
else:
print("Thanks for playing!")
exit()
# What will be done with players guesses
def input_check(ship_row, ship_col, player, board):
guess_col = 0
guess_row = 0
while True:
try:
guess_row = int(input("Guess Row:")) - 1
guess_col = int(input("Guess Col:")) - 1
except ValueError:
print("Enter a number only: ")
continue
else:
break
match = guess_row == ship_row - 1 and guess_col == ship_col - 1
not_on_game_board = (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4)
if match:
player["wins"] += 1
print("Congratulations! You sunk my battleship!")
print("Thanks for playing!")
play_again()
elif not match:
if not_on_game_board:
print("Oops, that's not even in the ocean.")
elif board[guess_row][guess_col] == "X":
print("You guessed that one already.")
else:
print("You missed my battleship!")
board[guess_row][guess_col] = "X"
show_board(game_board)
else:
return 0
def main():
begin = input('Type \'start\' to begin: ')
while (begin != str('start')):
begin = input('Type \'start\' to begin: ')
for games in range(3):
for turns in range(6):
if player_turns(turns) == player_one:
# print(ship_points)
print("Player One")
input_check(
ship_points['ship_row'],
ship_points['ship_col'],
player_one, game_board
)
elif player_turns(turns) == player_two:
print("Player Two")
input_check(
ship_points['ship_row'],
ship_points['ship_col'],
player_two, game_board
)
if turns == 5:
print("The game is a draw")
play_again()
if __name__ == "__main__":
main()
You can use style string formatting to print the log.
print('Match score is %d : %d(Player1 : Player2)' % (player_one["wins"], player_two["wins"]))
For more information about string formatting, check this link.
To change the symbol for Player 2, you can change the following code.
elif board[guess_row][guess_col] == "X" or board[guess_row][guess_col] == "Y":
print("You guessed that one already.")
else:
print("You missed my battleship!")
if player == player_one:
board[guess_row][guess_col] = "X"
else:
board[guess_row][guess_col] = "Y"
I'm making a 2-player battleship game in python. I've made it so that each 'game' allows a total of 6 turns (3 from each player), after which a message will appear saying 'The number of turns has ended'.
Once this happens, they will be asked to play again. If they answer 'yes' or 'y', the game should reload. However it doesn't. The board loads but the program then exits. I believe the issue lies with my play_again() function but I'm not quite sure what it is.
I want to make it so that the players can play as many games as they want until they decide to answer 'no' or 'n'. How do I go about implementing this?
from random import randint
game_board = []
player_one = {
"name": "Player 1",
"wins": 0,
}
player_two = {
"name": "Player 2",
"wins": 0,
}
colors = {"reset":"\033[00m",
"red":"\033[91m",
"blue":"\033[94m",
"cyan":"\033[96m"
}
# Building our 5 x 5 board
def build_game_board(board):
for item in range(5):
board.append(["O"] * 5)
def show_board(board):
for row in board:
print(" ".join(row))
# Defining ships locations
def load_game(board):
print("WELCOME TO BATTLESHIP!")
print("Find and sink the ship!")
del board[:]
build_game_board(board)
print(colors['blue'])
show_board(board)
print(colors['reset'])
ship_col = randint(1, len(board))
ship_row = randint(1, len(board[0]))
return {
'ship_col': ship_col,
'ship_row': ship_row,
}
ship_points = load_game(game_board)
# Players will alternate turns.
def player_turns(total_turns):
if total_turns % 2 == 0:
total_turns += 1
return player_one
return player_two
# Allows new game to start
def play_again():
positive = ["yes", "y"]
negative = ["no", "n"]
global ship_points
while True:
answer = input("Play again? [Y(es) / N(o)]: ").lower().strip()
if answer in positive:
ship_points = load_game(game_board)
break
elif answer in negative:
print("Thanks for playing!")
exit()
# What will be done with players guesses
def input_check(ship_row, ship_col, player, board):
guess_col = 0
guess_row = 0
while True:
try:
guess_row = int(input("Guess Row:")) - 1
guess_col = int(input("Guess Col:")) - 1
except ValueError:
print("Enter a number only: ")
continue
else:
break
match = guess_row == ship_row - 1 and guess_col == ship_col - 1
not_on_game_board = (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4)
if match:
player["wins"] += 1
print("Congratulations! You sunk my battleship!")
print('The current match score is %d : %d (Player1 : Player2)' % (player_one["wins"], player_two["wins"]))
print("Thanks for playing!")
play_again()
elif not match:
if not_on_game_board:
print("Oops, that's not even in the ocean.")
elif board[guess_row][guess_col] == "X" or board[guess_row][guess_col] == "Y":
print("You guessed that one already.")
else:
print("You missed my battleship!")
if player == player_one:
board[guess_row][guess_col] = "X"
else:
board[guess_row][guess_col] = "Y"
print(colors['cyan'])
show_board(game_board)
print(colors['reset'])
else:
return 0
def main():
begin = input('Type \'start\' to begin: ')
while (begin != str('start')):
begin = input('Type \'start\' to begin: ')
for turns in range(6):
if player_turns(turns) == player_one:
print(ship_points)
print("Player One")
input_check(
ship_points['ship_row'],
ship_points['ship_col'],
player_one, game_board
)
elif player_turns(turns) == player_two:
print("Player Two")
input_check(
ship_points['ship_row'],
ship_points['ship_col'],
player_two, game_board
)
if turns == 5:
print("The number of turns has ended.")
print(colors['red'])
show_board(game_board)
print(colors['reset'])
print('The current match score is %d : %d (Player1 : Player2)' % (player_one["wins"], player_two["wins"]))
play_again()
if __name__ == "__main__":
main()
It also worked for me when I added an invocation to main in your play_again() function:
# Allows new game to start
def play_again():
positive = ["yes", "y"]
negative = ["no", "n"]
global ship_points
while True:
answer = input("Play again? [Y(es) / N(o)]: ").lower().strip()
if answer in positive:
ship_points = load_game(game_board)
main()
break
elif answer in negative:
print("Thanks for playing!")
exit()
Try modifying main with:
turns = 0
while turns < 6:
# Process turn...
if turns == 5:
# Show endgame board
if play_again():
turns = -1
turns += 1
And have play_again return True on positive input ['y', 'yes'] and False otherwise.
The problem is that your play_again() call, upon receiving "Y" as answer, loads the board, but then simply returns. Where? Well, to the place it was called from - the for loop in main(). And unfortunately, it is the last iteration of said for loop, so the loop then ends and the program exits.
You should've put another loop around the for loop:
while True:
for turns in range(6):
...
Using python, I have to create a rock paper scissors game for school that the user plays against the computer. The computer's choice also has to be random. When i try to run this code its says that there is a syntax error but not where it is. Can anyone help?
import random
print("Welcome to rock paper scissors.")
player = False
while player == False:
print(" ")
print("Press 1 for Rock")
print("Press 2 for Paper")
print("Press 3 for Scissors")
User = int(input("Rock, Paper or Scissors?"))
Com = random.randrange(1,3)
if (User == 1) and (Com == 1):
player = False
print("Its a draw!")
elif (User == 2) and (Com == 1):
player = True
print("You win!")
elif (User == 3) and (Com == 1):
player = True
print("You lose!")
elif (User == 1) and (Com == 2):
player = True
print("You lose!")
elif (User == 2) and (Com == 2):
player = False
print("Its a draw!")
elif (User == 3) and (Com == 2):
player = True
print("You win!")
elif (User == 1) and (Com == 3):
player = True
print("You win!")
elif (User == 2) and (Com == 3):
player = True
print("You lose!")
elif (User == 3) and (Com == 3):
player = False
print("Its a draw! You both entered scissors.")
else:
print("Make sure to enter a number from 1 - 3")
Look here:
if (User == 1) and (Com == 1):
player = False
print("Its a draw!")
elif (User == 2) and (Com == 1):
player = True
print("You win!")
Your print statement with print("Its a draw!") does not belong to the if. You can't have anything 'loose' between if and elif.
Also your import is indented, but I believe this is formatting error.
It repairs your error but be aware that your naming conventions aren't saying much about the code.
Like #jedruniu said, you have incorrect indentation. I additionally took the liberty of cleaning up your code so it's less confusing:
import random
print("Welcome to rock paper scissors.")
draw = True
while draw:
print()
print("Press 1 for Rock")
print("Press 2 for Paper")
print("Press 3 for Scissors")
User = int(input("Rock, Paper or Scissors?"))
Com = random.randint(1,3)
if User == Com:
print("Its a draw!")
else:
draw = False #so it doesn't repeat
if (User == 2) and (Com == 1):
print("You win!")
elif (User == 3) and (Com == 1):
print("You lose!")
elif (User == 1) and (Com == 2):
print("You lose!")
elif (User == 3) and (Com == 2):
print("You win!")
elif (User == 1) and (Com == 3):
print("You win!")
elif (User == 2) and (Com == 3):
print("You lose!")
else:
print("Make sure to enter a number from 1 - 3")