I'm just wondering how I can make it so elif player_position == 1 will work. I want to check the value of the argument (pos) in function player_position() and execute code depending on its value. I've only been learning Python for about 1 month.
def player_position(pos):
position = pos
if position == goliath.spawn:
print('The Goliath Has Attacked!')
if goliath.accuracy == 1:
print('You Have Been Killed!')
else:
print('You Killed The Goliath!')
else:
print('Nothing Happens...')
def starting_room():
while True:
position_update = input('Enter A Direction: ')
if position_update == 'Forwards':
player_position(1)
elif position_update == 'Backwards':
player_position(3)
elif position_update == 'Left':
player_position(4)
elif position_update == 'Right':
player_position(2)
elif player_position == 1:
if position_update == 'Forwards':
print('Room 2')
elif position_update == 'Backwards':
player_position(0)
elif position_update == 'Left':
print('There Are Monsters In the Dark')
elif position_update == 'Right':
print('There Are Monsters In The Dark')
starting_room()
You're making a call to player_position, a function which does not return anything. Instead, assuming you want to keep track of the player's current position within your starting_room function, you'll want to keep track of the pos there.
Something like this: (note - you'll need to add more code to break out of the while loop - this code should allow you to keep track of the pos though)
def player_position(pos):
position = pos
if position == goliath.spawn:
print('The Goliath Has Attacked!')
if goliath.accuracy == 1:
print('You Have Been Killed!')
else:
print('You Killed The Goliath!')
else:
print('Nothing Happens...')
def starting_room():
pos = 0 #initialize the pos to 0
while True:
position_update = input('Enter A Direction: ')
if pos == 1: #check to see if current pos is 1
if position_update == 'Forwards':
print('Room 2')
#you may want to add "break" here to stop this while loop
elif position_update == 'Backwards':
pos = 0
elif position_update == 'Left':
print('There Are Monsters In the Dark')
elif position_update == 'Right':
print('There Are Monsters In The Dark')
elif position_update == 'Forwards':
pos = 1
elif position_update == 'Backwards':
pos = 3
elif position_update == 'Left':
pos = 4
elif position_update == 'Right':
pos = 2
player_position(pos) #call the player_position function with the current pos
starting_room()
Related
(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
I have a problem using the while loop. When I am inputting right answer for example, and the second one is wrong, the tryAgain input is showing. If I want to play again, it just looping in from the start and choosing a topic won't work. If I made it wrong, from the start, it will just loop on its own from inputting answers.
tryAgain = True
repeat = True
while tryAgain:
print("TOPICS: \n")
print("1. topic 1")
print("2. topic 2")
print("3. topic 3")
print("======================================")
num = int(input("PICK A NUMBER FOR THE TOPIC [1-3]: "))
if num > 3:
print("There is no given topic")
print("==========================")
tryAgain = True
else:
if num == 1:
reader = WordListCorpusReader('filename', ['textfile'])
with open('filename') as f:
text = [line.strip().upper() for line in f]
answer = []
while lives > 0:
while repeat:
index = 0
while index < 10:
answerlst = input(str(index + 1) + '. ').upper()
if answerlst in text: #condition if the inputted answer is on the file
if answerlst in answer: #check if the inputted answer is on the array
print("\nYou repeated your answer!")
repeat = True
continue
else:
answer.append(answerlst)
print("Correct!")
repeat = False
if answerlst == "ans1":
print("Points: 10")
points += 10
elif answerlst == "ans2":
print("Points: 20")
points += 20
elif answerlst == "ans3":
print("Points: 30")
points += 30
elif answerlst == "ans4":
print("Points: 40")
points += 40
elif answerlst == "ans5":
print("Points: 50")
points += 50
elif answerlst == "ans6":
print("Points: 60")
points += 60
elif answerlst == "ans7":
print("Points: 70")
points += 70
elif answerlst == "ans8":
print("Points: 80")
points += 80
elif answerlst == "ans9":
print("Points: 90")
points += 90
elif answerlst == "ans10":
print("Points: 100")
points += 100
if points == 550:
print("\nCONGRATULATIONS!!!! YOU GOT A PERFECT POINTS OF:", points)
break
else:
if answerlst == "ans1":
points += 10
elif answerlst == "ans2":
points += 20
elif answerlst == "ans":
points += 30
elif answerlst == "ans4":
points += 40
elif answerlst == "ans5":
points += 50
elif answerlst == "ans6":
points += 60
elif answerlst == "ans7":
points += 70
elif answerlst == "ans8":
points += 80
elif answerlst == "ans9":
points += 90
elif answerlst == "ans10":
points += 100
lives -= 1
if lives == 0:
print("\nGAME OVER!!!!!\n")
print("You just got a: ", points)
break
index +=1
playAgain = input("Do you want to play again? [Y] / [N]: ").upper()
if playAgain == 'Y':
answer.clear() #to clear the list
tryAgain = True
I just show the structure of my code in order to understand.
Congratulations, because now you've learned what spaghetti code is - it's just a mess, where you can't properly find errors. When such situation occurs, try to divide your problem into smaller parts (stages). Implement the stages as functions, and your code will become much easier.
For example I tried to rework your program like this. ATTENTION: I don't have your files, so this code probably won't work out of the box, I cannot test it. But just try to read it and understand the approaches.
After reworking this code I noticed that you never set lives to any number, but you should.
def input_topic():
while True:
print("TOPICS: \n")
print("1. topic 1")
print("2. topic 2")
print("3. topic 3")
print("======================================")
topic = int(input("PICK A NUMBER FOR THE TOPIC [1-3]: "))
if topic > 3:
print("There is no given topic")
print("==========================")
else:
return topic
def read_text(filename):
reader = WordListCorpusReader(filename, ['textfile'])
with open(filename) as f:
text = [line.strip().upper() for line in f]
return text
def input_answer_and_check(index, text, already_answered):
while True:
answerlst = input(str(index+1) + '. ').upper()
if answerlst in text:
if answerlst not in answer:
return True, answerlst
else:
print("\nYou repeated your answer!")
else:
return False, answerlst
def get_answer_points(answerlst)
if answerlst == "ans1":
return 10
elif answerlst == "ans2":
return 20
elif answerlst == "ans3":
return 30
elif answerlst == "ans4":
return 40
elif answerlst == "ans5":
return 50
elif answerlst == "ans6":
return 60
elif answerlst == "ans7":
return 70
elif answerlst == "ans8":
return 80
elif answerlst == "ans9":
return 90
elif answerlst == "ans10":
return 100
def ask_try_again():
playAgain = input("Do you want to play again? [Y] / [N]: ").upper()
return playAgain == 'Y'
while True:
topic = input_topic()
text = read_text('filename')
answer = []
lives_left = 5
index = 0
max_index = 10
total_points = 0
while lives_left > 0 and index < max_index and total_points < 550:
is_correct_answer, answerlst = input_answer_and_check(index, text, answer)
answer_points = get_answer_points(answerlst)
total_points += answer_points
if is_correct_answer:
answer.append(answerlst)
print("Correct!")
print(f"Points: {answer_points}")
else:
lives_left -= 1
index += 1
if lives_left == 0:
print("\nGAME OVER!!!!!\n")
print("You just got a: ", total_points)
elif total_points >= 550:
print("\nCONGRATULATIONS!!!! YOU GOT A PERFECT POINTS OF:", total_points)
if not ask_try_again():
break
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!")
This question already has an answer here:
Pygame Tic Tak Toe Logic? How Would I Do It
(1 answer)
Closed 1 year ago.
I've tried to make a tic tac toe game in Python. From what I make I feel that my code is working however it is really bad. Is there anyway to improve from this code?
class Board():
def __init__(self):
self.board = ["[]","[]","[]","[]","[]","[]","[]","[]","[]"]
def createboard(self):
board = ["[]","[]","[]","[]","[]","[]","[]","[]","[]"]
print(self.board[0],self.board[1],self.board[2])
print(self.board[3],self.board[4],self.board[5])
print(self.board[6],self.board[7],self.board[8])
def checkwin(self):
if self.board[0]=="[O]" and self.board[1]=="[O]" and self.board[2]=="[O]":
print("O Wins!")
#break
elif self.board[3]=="[O]"and self.board[4]=="[O]"and self.board[5]=="[O]":
print("O Wins!")
# break
elif self.board[6]=="[O]"and self.board[7]=="[O]"and self.board[8]=="[O]":
print("O Wins!")
# break
elif self.board[0]=="[O]"and self.board[3]=="[O]"and self.board[6]=="[O]":
print("O Wins!")
# break
elif self.board[1]=="[O]"and self.board[4]=="[O]"and self.board[7]=="[O]":
print("O Wins!")
# break
elif self.board[2]=="[O]"and self.board[5]=="[O]"and self.board[8]=="[O]":
print("O Wins!")
# break
elif self.board[0]=="[O]"and self.board[4]=="[O]"and self.board[8]=="[O]":
print("O Wins!")
# break
elif self.board[2]=="[O]"and self.board[4]=="[O]"and self.board[6]=="[O]":
print("O Wins!")
# break
elif self.board[0]=="[X]"and self.board[1]=="[X]"and self.board[2]=="[X]":
print("X Wins!")
# break
elif self.board[3]=="[X]"and self.board[4]=="[X]"and self.board[5]=="[X]":
print("X Wins!")
# break
elif self.board[6]=="[X]"and self.board[7]=="[X]"and self.board[8]=="[X]":
print("X Wins!")
# break
elif self.board[0]=="[X]"and self.board[3]=="[X]"and self.board[6]=="[X]":
print("X Wins!")
# break
elif self.board[1]=="[X]"and self.board[4]=="[X]"and self.board[7]=="[X]":
print("X Wins!")
# break
elif self.board[2]=="[X]"and self.board[5]=="[X]"and self.board[8]=="[X]":
print("X Wins!")
# break
elif self.board[0]=="[X]"and self.board[4]=="[X]"and self.board[8]=="[X]":
print("X Wins!")
# break
elif self.board[2]=="[X]"and self.board[4]=="[X]"and self.board[6]=="[X]":
print("O Wins!")
# break
def omove(self):
o = int(input("Its 'O's'move please insert 1-9"))
if o == 1:
self.board[0] = "[O]"
self.createboard()
elif o == 2:
self.board[1] = "[O]"
self.createboard()
elif o == 3:
self.board[2] = "[O]"
self.createboard()
elif o == 4:
self.board[3] = "[O]"
self.createboard()
elif o == 5:
self.board[4] = "[O]"
self.createboard()
elif o == 6:
self.board[5] = "[O]"
self.createboard()
elif o == 7:
self.board[6] = "[O]"
self.createboard()
elif o == 8:
self.board[7] = "[O]"
self.createboard()
elif o == 9:
self.board[8] = "[O]"
self.createboard()
else:
print('that column is out of range')
o = int(input("please insert 1-9"))
def xmove(self):
x = int(input("Its 'x's'move please insert 1-9"))
if x == 1:
self.board[0] = "[X]"
self.createboard()
elif x == 2:
self.board[1] = "[X]"
self.createboard()
elif x == 3:
self.board[2] = "[X]"
self.createboard()
elif x == 4:
self.board[3] = "[X]"
self.createboard()
elif x == 5:
self.board[4] = "[X]"
self.createboard()
elif x == 6:
self.board[5] = "[X]"
self.createboard()
elif x == 7:
self.board[6] = "[X]"
self.createboard()
elif x == 8:
self.board[7] = "[X]"
self.createboard()
elif x == 9:
self.board[8] = "[X]"
self.createboard()
else:
print('that column is out of range')
o = int(input("please insert 1-9"))
a = Board()
a.createboard()
a.omove()
a.checkwin()
a.xmove()
a.checkwin()
a.omove()
a.checkwin()
a.xmove()
a.checkwin()
a.omove()
a.checkwin()
a.xmove()
a.checkwin()
a.omove()
a.checkwin()
a.xmove()
a.checkwin()
a.omove()
a.checkwin()
I would love any kind of feedback to improve my skills in programming. What I thought about this is I think I used too much if condition maybe it can be swapped by another simple method and how can I even break when the game is finished ex: if X wins the game, the game is then closed
A big change would be to refactor the move functions to pass in the token you need and avoid the elifs with maths.
def move(self, token):
o = int(input(f"Its '{token}'s'move please insert 1-9"))
while not (0 < o <= 9):
print('that column is out of range')
o = int(input("please insert 1-9"))
self.board[o-1] = f"[{token}]"
self.createboard()
used via...
move("O")
move("X")
self.board = 9*['[]']
def createboard(self):
for i,j in enumerate(board, 1):
print(j)
if i%3 == 0: print('\n')
Have a look at python tutorial: https://docs.python.org/3/tutorial/
in these days i have been struggling with minimax algorithm and i can say i finally understood it ( thank to another post in stackoverflow). Therefore i opened my editor and i tried to implement it into a EXTREMELY simple ( do not blame me for code please :P) tic tac toe, just to give a try out. everything is working, but the computer move function always retrieve me -1. i'm not asking you to give me code, just the "why" it does that. i have searched throught the code many times, but found nothing . The code is probably really similar to another one i found on the web. here's my code :
# COMPUTER AI
def computer_move():
best_move = minimax_recurse(game_board,active_player, 0)
print "The best move is ", best_move
make_move(game_board,best_move, active_player)
print "COMPUTER MOVE DONE"
def minimax_recurse(game_board,player,depth):
winner = is_winner(game_board)
if winner == active_player :
return 1
elif winner is not active_player :
return -1
elif len(get_move_list(game_board)) == 0 :
return 0
if player == player1 :
other_player = player2
other_player = player1
if player == active_player :
alpha = -1
alpha = 1
movelist = get_move_list(game_board)
for move in movelist :
board2 = game_board
make_move(board2,move,player)
subalpha = minimax_recurse(board2, other_player, depth + 1)
if player == active_player :
if depth == 0 and alpha <= subalpha:
best_move = move
alpha = max(alpha,subalpha)
return alpha
else :
alpha = min(alpha,subalpha)
return alpha
# BOARD FUNCTIONS
game_board = ([1,2,3],[4,5,6],[7,8,9])
def print_board(board) :
for row in board :
print row
def make_move(game_board,player_move,active_player):
x = 0
y = 0
player_move = int(player_move)
if player_move == 1 :
x = 0
y = 0
elif player_move == 2 :
x = 0
y = 1
elif player_move == 3 :
x = 0
y = 2
elif player_move == 4 :
x = 1
y = 0
elif player_move == 5 :
x = 1
y = 1
elif player_move == 6 :
x = 1
y = 2
elif player_move == 7 :
x = 2
y = 0
elif player_move == 8 :
x = 2
y = 1
elif player_move == 9 :
x = 2
y = 2
elif player_move >= 10 :
print "value is too high"
skip = False
return board
if game_board[x][y] == "O" or game_board[x][y] == "X" :
print "move not avaiable"
return game_board
game_board[x][y] = active_player
return game_board
def is_winner(board):
for i in range (0,3) :
if board[i][0] == player1 and board[i][1] == player1 and board[i][2] == player1 :
return player1
if board[i][0] == player2 and board[i][1] == player2 and board[i][2] == player2 :
return player2
# checking for obliqual, that's quite bad and slow check but it works
if board[0][0] == player1 and board[1][1] == player1 and board[2][2] == player1 :
return player1
if board[0][0] == player2 and board[1][1] == player2 and board[2][2] == player2 :
return player2
if board[2][0] == player1 and board[1][1] == player1 and board[0][2] == player1 :
return player1
if board[2][0] == player2 and board[1][1] == player2 and board[0][2] == player2 :
return player2
return None
def get_move_list (game_board) :
move = [0]
for row in game_board :
for i in row :
if isinstance(i,int) == True :
move.append(i)
move.remove(0)
return move
# Main Loop
player1 = "X"
player2 = "O"
print_board(game_board)
while True :
active_player = player1
# this is for player move
print get_move_list(game_board)
player_move = int(raw_input("Please insert your move >>> "))
make_move(game_board,player_move,active_player)
print_board(game_board)
if is_winner(game_board) == player1 :
print "Player1 is the winner"
break
if is_winner(game_board) == player2 :
print "Player2 is the winner"
break
print get_move_list(game_board)
# computer time
active_player = player2
computer_move()
print_board(game_board)
if is_winner(game_board) == player1 :
print "Player1 is the winner"
break
if is_winner(game_board) == player2 :
print "Player2 is the winner"
break
Without debugging all your code, one thing that seems wrong is your use of "best_move" variable (global uninitialized) as both a holder for a move as well as holder for -1/0/+1 result of minimax_recurse. So it's being overwritten by your minmax algorithm. You need more variables, clearer initialization of them, and consistent usage.
The root cause of the -1 always returning is that winner is not active_player returns True when winner is None. You could use a variable to keep track of the other (inactive) player, or you could use the ternary operator: elif winner is (player1 if player2 == active_player else player2)
Though that's not the only issue:
if player == active_player :
alpha = -1
alpha = 1
That will always set alpha to 1. The lines directly above that have the same problem. The variable naming issue pointed out in the other answer is also true.