Doesn't store entered value when runs second time - python

I made a rock, paper, scissors game.
It works fine, as I wanted to, but it doesn't store entered value when runs second time, how do I fix that.
See the while loop below where the program goes again if the user enters y.
import random
tools =["Rock","Scissors","Paper"]
r = "".join(tools[0])
s = "".join(tools[1])
p = "".join(tools[-1])
def computer_predicion():
computer_pred = random.choice(tools)
return computer_pred
computer = computer_predicion()
def my_predicion():
my_predicion = input("Choose (R)Rock,(S)Scissors,(P)Paper:")
if my_predicion == "R" or my_predicion == "r":
my_predicion = r
return my_predicion
elif my_predicion == "S" or my_predicion == "s":
my_predicion = s
return my_predicion
elif my_predicion == "P" or my_predicion == "p":
my_predicion = p
return my_predicion
else:
print("Debils ir?")
human=my_predicion()
def game():
message_win = ("You won!")
message_lose = ("You lost!")
message = "Computer:%s\nUser:%s"%(computer, human)
if computer == r and human == r :
print(message+"\nIt's draw")
elif computer == p and human == p:
print(message + "\nIt's draw")
elif computer == s and human == s:
print(message + "\nIt's draw")
elif computer == r and human == p:
print(message+'\n'+message_win)
elif computer == p and human == r:
print(message+'\n'+message_lose)
elif computer == r and human == s:
print(message+'\n'+message_lose)
elif computer == s and human == r:
print(message+'\n'+message_win)
elif computer == p and human == s:
print(message+'\n'+message_win)
elif computer == s and human == p:
print(message+'\n'+message_lose)
else:
pass
c = True
while c: //Here code runs second time if user inputs Y or y.
game()
h = input("Continue?(Y/N):")
if h == "Y" or h == "y":
my_predicion()
computer_predicion()
pass
elif h == "N" or h == "n":
c = False
else:
print("Wrong symbol!")

The value is not being stored in the second loop because
computer = computer_predicion()
human = my_predicion()
are displayed outside of the while loop
Here is your working code, I migrated the two variable assignment inside the while loop
import random
tools =["Rock","Scissors","Paper"]
r="".join(tools[0])
s="".join(tools[1])
p="".join(tools[-1])
def computer_predicion():
computer_pred = random.choice(tools)
return computer_pred
def my_predicion():
my_predicion = input("Choose (R)Rock,(S)Scissors,(P)Paper:")
if my_predicion=="R" or my_predicion =="r":
my_predicion = r
return my_predicion
elif my_predicion=="S" or my_predicion =="s":
my_predicion = s
return my_predicion
elif my_predicion=="P" or my_predicion =="p":
my_predicion = p
return my_predicion
else:
print("Debils ir?")
def game():
message_win = ("You won!")
message_lose = ("You lost!")
message = "Computer:%s\nUser:%s"%(computer,human)
if computer ==r and human==r :
print(message+"\nIt's draw")
elif computer == p and human == p:
print(message + "\nIt's draw")
elif computer == s and human == s:
print(message + "\nIt's draw")
elif computer == r and human==p:
print(message+'\n'+message_win)
elif computer == p and human==r:
print(message+'\n'+message_lose)
elif computer == r and human==s:
print(message+'\n'+message_lose)
elif computer == s and human==r:
print(message+'\n'+message_win)
elif computer == p and human == s:
print(message+'\n'+message_win)
elif computer == s and human==p:
print(message+'\n'+message_lose)
else:
pass
c=True
while c : #Here code runs second time if user inputs Y or y.
computer = computer_predicion()
human = my_predicion()
game()
h = input("Continue?(Y/N):")
if h=="Y" or h=="y":
pass
elif h=="N" or h=="n":
c=False
else:
print("Wrong symbol!")

Related

Python keyboard Input will be visible on the next input Statement

(im noob) I'm having a problem using the keyboard module, every time I use it all the input I enter will be visible on the next input statement.
while pamatoChooser:
pamatoChooser = True
pamatoScreen = True
piliCardo()
ownedChecker()
backUseNext()
inputChooser = keyboard.read_key()
if inputChooser == ("1"):
inputPamato = ('1')
break
elif inputChooser == ("b"):
# nothing here yet
pass
elif inputChooser == ("Esc"):
bMain = False
pamatoScreen = False
break
elif inputChooser == "n":
transition1()
johnnyLoop = True
while johnnyLoop:
piliJohnny()
ownedChecker()
backUseNext()
inputChoose1 = str(input("Choose your pamato: "))
if inputChooser == ('1'):
inputPamato = ('2')
pamatoChooser = False
break
elif inputChooser == ('b'):
transition2()
break

how to make a discord bot calculator

so i made some code for a discord bot calculator. it should respond to a command for example calculate 2+2. but well it doesnt work. (im a begginer so the code is probably trash)
if "calculate" in message.content or "Calculate" in message.content:
i = message.content.split("alculate ",1)[1]
number = 0
letter = 'd'
for ii in i:
try:
number == ii
except:
try:
if letter == "*":
number*=float(ii)
print
elif letter == "-":
number -= float(ii)
elif letter == "+":
number += float(ii)
elif letter == "/":
number/=float(ii)
if int(ii) != ii:
ii = letter
except:
try:
if ii == "*":
ii == letter
elif ii == "-":
ii == letter
elif ii == "+":
ii == letter
elif ii == "/":
ii == letter
except:
break
await message.channel.send(number)

Tic-Tac-Toe Game - Errors and AI

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")

Naughts and crosses in python: scoring not working

I realise that many other people have tried and failed to make naughts and crosses (by looking at the suggested question) but I'm assuming they don't have the same problem as me.
Here is my code:
import random, time, sys
raw3 = ["-", "-", "-"]
raw2 = ["-", "-", "-"]
raw1 = ["-", "-", "-"]
def draw():
str3 = ""
str2 = ""
str1 = ""
for i in raw3:
str3 = (str3 + i + " ")
for i in raw2:
str2 = (str2 + i + " ")
for i in raw1:
str1 = (str1 + i + " ")
str_board = str3+str("\n"*2)+str(str2)+str("\n"*2)+str(str1)
print(str_board)
def playerX_turn():
c_choice_in = input("Type the coordinates in the format y/x\n(e.g. 2/1)")
c_choice_list = list(c_choice_in)
c_choice_x = int(c_choice_list[0]); c_choice_y = int(c_choice_list[2])
print(c_choice_x, c_choice_y)
if c_choice_x == 3 and raw3[c_choice_y - 1] == "-":
raw3[c_choice_y - 1] = "X"
elif c_choice_x == 2 and raw2[c_choice_y - 1] == "-":
raw2[c_choice_y - 1] = "X"
elif c_choice_x == 1 and raw1[c_choice_y - 1] == "-":
raw1[c_choice_y - 1] = "X"
def playerO_turn():
c_choice_in = input("Type the coordinates in the format y/x\n(e.g. 2/1)")
c_choice_list = list(c_choice_in)
c_choice_x = int(c_choice_list[0]); c_choice_y = int(c_choice_list[2])
print(c_choice_x, c_choice_y)
if c_choice_x == 3 and raw3[c_choice_y - 1] == "-":
raw3[c_choice_y - 1] = "O"
elif c_choice_x == 2 and raw2[c_choice_y - 1] == "-":
raw2[c_choice_y - 1] = "O"
elif c_choice_x == 1 and raw1[c_choice_y - 1] == "-":
raw1[c_choice_y - 1] = "O"
def check4win():
winner = None
if winner == None or winner == False and raw3[0] == "X" or raw3[2] == "X" and raw2[1] == "X" and raw1[0] == "X" or raw1[2] == "X":
winner = "playerX"
column_checker = 0
for i in range(0,3):
if winner == None or winner == False and raw3[column_checker] == "X" and raw2[column_checker] == "X" and raw1[column_checker] == "X":
winner = "playerX"
else:
column_checker += 1
if winner == None or winner == False:
if raw3[0] == "X" and raw3[1] == "X" and raw3[2] == "X":
winner = "playerX"
elif raw2[0] == "X" and raw2[1] == "X" and raw2[2] == "X":
winner = "playerX"
elif raw1[0] == "X" and raw1[1] == "X" and raw1[2] == "X":
winner = "playerX"
### ### ### ###
if winner == None or winner == False and raw3[0] == "Y" or raw3[2] == "Y" and raw2[1] == "Y" and raw1[0] == "Y" or raw1[2] == "Y":
winner = "playerY"
column_checker = 0
for i in range(0,3):
if winner == None or winner == False and raw3[column_checker] == "Y" and raw2[column_checker] == "Y" and raw1[column_checker] == "Y":
winner = "playerY"
else:
column_checker += 1
if winner == None or winner == False:
if raw3[0] == "Y" and raw3[1] == "Y" and raw3[2] == "Y":
winner = "playerY"
elif raw2[0] == "Y" and raw2[1] == "Y" and raw2[2] == "Y":
winner = "playerY"
elif raw1[0] == "Y" and raw1[1] == "Y" and raw1[2] == "Y":
winner = "playerY"
### ### ### ###
if winner != None or winner != False:
if winner == "playerX":
print("X won the game!\n(Sorry, O!)")
elif winner == "playerY":
print("Y won the game!\n(Bad luck, X!)")
sys.exit()
def main():
game_over = False
while game_over == False:
playerX_turn()
draw()
check4win()
playerO_turn()
draw()
check4win()
main()
So my first problem is that this is an example of output from it:
>>>
Type the coordinates in the format y/x
(e.g. 2/1)1,1
1 1
- - -
- - -
X - -
X won the game!
(Sorry, O!)
>>>
Which clearly is not correct...
It's probably a stupid mistake somewhere but I'm too lazy to go looking through it properly, but I've had a brief look through the check4win() function, but to no avail.
Another (less important) thing is that I have a feeling this code could be made neater... Maybe something with main()?

Where exactly does a python function's return value go?

My Rock Paper Scissors code doesn't work and I'm assuming it's because I'm using the return value incorrectly. What should I do?
EDIT, so I've stored the return like this
def results (x, y):
if (x == "R" or x == "rock" or x == "r" or x == "Rock" or x == "ROCK") and (y == "S" or y == "s" or y == "Scissors" or y == "SCISSORS" or y == "scissors"):
winner = 1
return winner
But how do I get "winner" to print outside of the function?
OLD
player1 = input ("Player 1: Please enter either Rock, Paper or Scissors:")
player2 = input ("Player 2: Please enter either Rock, Paper or Scissors:")
def results (x, y):
if (x == "R" or x == "rock" or x == "r" or x == "Rock" or x == "ROCK") and (y == "S" or y == "s" or y == "Scissors" or y == "SCISSORS" or y == "scissors"):
return 1
else:
if (x == "rock" or x == "r" or x =="R" or x == "Rock" or x == "ROCK") and (y == "P" or y == "p" or y == "paper" or y == "Paper" or y == "PAPER"):
return 2
else:
if (x == "rock" or x =="R" or x == "r" or x == "Rock" or x == "ROCK") and (y == "rock" or y =="R" or y == "r" or y =="Rock" or y == "ROCK"):
return 0
else:
print ("Sorry, I didn't understand your input")
results (player1, player2)
if results == 1:
print ("Player 1 wins!")
else:
if results == 2:
print("Player 2 wins!")
else:
if results == 0:
print("It was a tie!")
The return value isn't automatically stored anywhere. You need to store it manually:
result = results(player1, player2)
if result == 1:
...
If you look up at the top of your code, you'll see you already did the right thing with the input function:
player1 = input ("Player 1: Please enter either Rock, Paper or Scissors:")
Functions you define yourself should be handled the same way.
In response to the edit: Creating a local variable inside results won't help. The code that calls the function needs to store the return value. (People have designed languages that work the way you're trying to get it to work. The result is a huge headache with unrelated parts of the program stomping over each other's data.)

Categories