Python - Change Simple game code into classes with methods? - python

I'm trying to do a practice assignment to help learn python yet am stuck on this. It says to create a simple Die game which asks for user input to keep playing, along with displaying results. I also need to use classes. I have been able to create it without the classes yet become stuck when transferring it to classes.
import random
def RollDice():
die = random.randint(1,6)
die2 = random.randint(1,6)
faceValue = die + die2
if die == 1:
RollOne()
elif die == 2:
RollTwo()
elif die == 3:
RollThree()
elif die == 4:
RollFour()
elif die == 5:
RollFive()
elif die == 6:
RollSix()
if die2 == 1:
RollOne()
elif die2 == 2:
RollTwo()
elif die2 == 3:
RollThree()
elif die2 == 4:
RollFour()
elif die2 == 5:
RollFive()
elif die2 == 6:
RollSix()
return faceValue
def RollOne():
print(''' ------
| |
| o |
| |
------ ''')
return
def RollTwo():
print(''' ------
| o |
| |
| o |
------ ''')
return
def RollThree():
print(''' ------
| o |
| o |
| o |
------ ''')
return
def RollFour():
print(''' ------
| o o |
| |
| o o |
------ ''')
return
def RollFive():
print(''' ------
| o o |
| o |
| o o |
------ ''')
return
def RollSix():
print(''' ------
| o o |
| o o |
| o o |
------ ''')
return
x = 1
OverallRoll = RollDice()
print("Face value:", OverallRoll)
while x == 1:
play_again = input("Would you like to play again? Respond with 'Yes' to continue and anything else to quit.")
if play_again == 'Yes':
OverallRoll = RollDice()
print("Face value:", OverallRoll)
else:
quit()
Any tips on how to make it into classes with methods? Thank you!

import random
class Game:
DIE_ASCII_ART = {1: ''' ------
| |
| o |
| |
------ ''', 2: ''' ------
| o |
| |
| o |
------ '''} # Do this for all values from 1-6
#staticmethod
def _roll_dice() -> int:
die = random.randint(1, 6)
die2 = random.randint(1, 6)
print(Game.DIE_ASCII_ART[die])
print(Game.DIE_ASCII_ART[die2])
return die + die2
#staticmethod
def run() -> None:
running = True
while running:
play_again = input("Would you like to play again? Respond with 'Yes' to continue and anything else to quit.")
if play_again == 'Yes':
overall_roll = Game._roll_dice()
print("Face value:", overall_roll)
else:
running = False
if __name__ == '__main__':
Game.run()
A few other notes about your code:
You use PascalCase in your code while the convention for Python is snake_case.
You defined alot of functions and wrote alot of if statements when a simple dictonary was enough to solve the problem.
A few notes about my code:
The methods in the Game class are static because there isn't a need for instance variables in the code.
I added typing annotations for improved code quality.
I changed the game loop for using a number to a boolean because that is more readble in my opinion.
Refrences:
PEP8 style guide
type annotations

Related

If statement no longer recognizing input in while loop python

I am writing a hangman game in python and I have variable called userguess and the user will type in what letter they want to use to guess. However, when the while loop begins it's second repeat, the if statement no longer recognizes the userguess and immediately concludes it to be an incorrect guess. I hope you don't mind the amount of code I am using as an example.
movieletters contains the hiddenword split into letters
defaultletters represents the blanks that have to be filled in by the user
I have tried using exception handlers by creating boolean variables but this hasn't done what I needed it to do.
userguess = input("Guess a letter: ")
while True:
for letter in movieletters:
for defaultletter in defaultletters:
if userguess == letter:
print("You guessed correctly")
score += 1
guessedletters.append(userguess)
print(score, "/", totalletters)
print(guessedletters)
print(movie)
if score == totalletters:
print("\n")
print("*************************************************************************************************")
print(movie)
print("*************************************************************************************************")
print("\n")
print("You guessed all the letters correctly and uncovered the word!")
playagain = input("Would you like to play again? Type y for yes and n for no: ")
if playagain == "y":
main()
else:
quit()
userguess = input("Guess a letter: ")
continue
elif userguess != letter:
incorrectlyguessed += 1
print("INCORRECT!")
print(str(incorrectlyguessed) + "/" + str(tally))
if incorrectlyguessed == 1:
print("""
__________""")
elif incorrectlyguessed == 2:
print("""
|
|
|
|
|__________ """)
elif incorrectlyguessed == 3:
print("""
-----------
|
|
|
|
|__________ """)
elif incorrectlyguessed == 4:
print("""
-----------
| |
|
|
|
|__________ """)
elif incorrectlyguessed == 5:
print("""
-----------
| |
| 0
|
|
|__________ """)
elif incorrectlyguessed == 6:
print("""
-----------
| |
| 0
| |
|
|__________ """)
elif incorrectlyguessed == 7:
print("""
-----------
| |
| 0
| \|/
|
|__________ """)
elif incorrectlyguessed == 8:
print("""
-----------
| |
| 0
| \|/
| |
|__________ """)
elif incorrectlyguessed == 9:
print("""
-----------
| |
| 0
| \|/
| |
|________/_\ """)
if incorrectlyguessed == tally:
print("GAME OVER!")
print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
print(movie)
print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
playagain = input("Would you like to play again? Type y for yes and n for no: ")
if playagain == "y":
main()
else:
quit()
userguess = input("Guess a letter: ")
continue
I expect the output to show that the character is recognized as one of the letters in the hidden word in the while loop's second phase. This also effects all of the while loop's phases except for the first one.
Here's an example of the current output:
Output
if the movie was cars then movieletters would be ['c', 'a', 'r', 's']
defaultletters would be _ _ _ _
The problem is that it always matches with the first letter in the list of movieletters.
use if userguess in movieletters to check whether it matches or not
userguess = input("Guess a letter: ")
if userguess in movieletters:
print("You guessed correctly")
score += 1
guessedletters.append(userguess)
print(score, "/", totalletters)
print(guessedletters)
print(movie)
if score == totalletters:
print("\n")
print("*************************************************************************************************")
print(movie)
print("*************************************************************************************************")
print("\n")
print("You guessed all the letters correctly and uncovered the word!")
playagain = input("Would you like to play again? Type y for yes and n for no: ")
if playagain == "y":
main()
else:
quit()
userguess = input("Guess a letter: ")
continue
else :
incorrectlyguessed += 1
print("INCORRECT!")
print(str(incorrectlyguessed) + "/" + str(tally))
if incorrectlyguessed == 1:
print("""
__________""")
elif incorrectlyguessed == 2:
print("""
|
|
|
|
|__________ """)
elif incorrectlyguessed == 3:
print("""
-----------
|
|
|
|
|__________ """)
elif incorrectlyguessed == 4:
print("""
-----------
| |
|
|
|
|__________ """)
elif incorrectlyguessed == 5:
print("""
-----------
| |
| 0
|
|
|__________ """)
elif incorrectlyguessed == 6:
print("""
-----------
| |
| 0
| |
|
|__________ """)
elif incorrectlyguessed == 7:
print("""
-----------
| |
| 0
| \|/
|
|__________ """)
elif incorrectlyguessed == 8:
print("""
-----------
| |
| 0
| \|/
| |
|__________ """)
elif incorrectlyguessed == 9:
print("""
-----------
| |
| 0
| \|/
| |
|________/_\ """)
if incorrectlyguessed == tally:
print("GAME OVER!")
print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
print(movie)
print("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")
playagain = input("Would you like to play again? Type y for yes and n for no: ")
if playagain == "y":
main()
else:
quit()
userguess = input("Guess a letter: ")
continue

How to compare user inputted string to a character(single letter) of a word in a list?

I'm trying to create a hangman game with python. I know there is still a lot to complete but I'm trying to figure out the main component of the game which is how to compare the user inputted string (one letter) with the letters in one of the three randomly selected words.
import random
print("Welcome to hangman,guess the five letter word")
words =["china", "ducks", "glass"]
correct_word = (random.choice(words))
guess = input(str("Enter your guess:"))
guess_left = 10
guess_subtract = 1
if guess == "":
guess_left = guess_left - guess_subtract
print("you have" + guess_left + "guesses left")
I think you need a skeleton and then spend some time to improve the game.
import random
print "Welcome to hangman, guess the five letter word"
words = ["china", "ducks", "glass"]
correct_word = (random.choice(words))
trials = 10
for trial in range(trials):
guess = str(raw_input("Enter character: "))
if (len(guess) > 1):
print "You are not allowed to enter more than one character at time"
continue
if guess in correct_word:
print "Well done! '" + guess + "' is in the list!"
else:
print "Sorry " + guess + " does not included..."
Your next step could be print out something like c_i__ as well as the number of trials left. Have fun :)
When you finish with the implementation, take some time and re-implement it using functions.
I've completed this project yesterday; (to anyone else reading this question) take inspiration if needed.
import random
stages = ['''
+---+
| |
O |
/|\ |
/ \ |
|
=========
''', '''
+---+
| |
O |
/|\ |
/ |
|
=========
''', '''
+---+
| |
O |
/|\ |
|
|
=========
''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========
''', '''
+---+
| |
O |
|
|
|
=========
''', '''
+---+
| |
|
|
|
|
=========
''']
#used to choose random word
random_lst=['addition','adequate','adjacent','adjusted','advanced','advisory','advocate','affected','aircraft','alliance','although','aluminum','analysis','announce','anything','anywhere','apparent','appendix','approach','approval','argument','artistic','assembly']
chosen_word = random.choice(random_lst)
#used to create display list + guess var
print("Welcome to hangman! ")
print("--------------------")
print("you have 6 lives." )
print(" ")
print (stages[-1])
display = []
for letters in chosen_word:
display += "_"
print(display)
print(" ")
#used to check if guess is equal to letter, and replace pos in display if yes.
lives = 6
game_over = False
#use the var guesses to store guesses and print at every guess to let player know what letters they tried already.
guesses = ""
while not game_over:
guess = input("Guess a letter. ")
print(" ")
guesses += (guess + " , ")
for pos in range(len(chosen_word)):
letter = chosen_word[pos
if letter == guess:]
display[pos] = letter
print("√")
print("- - -")
print(" ")
if display.count("_") == 0:
print("Game over. ")
game_over = True
elif guess not in chosen_word:
lives -= 1
print(f"Wrong letter. {lives} lives left. ")
print("- - - - - - - - - - - - - - - - - - -")
print(" ")
if lives == 0:
print (stages[0])
elif lives == 1:
print (stages[1])
elif lives == 2:
print (stages[2])
elif lives == 3:
print(stages[3])
elif lives == 4:
print(stages[4])
elif lives == 5:
print(stages[5])
elif lives == 6:
print(stages[6])
elif lives == 0:
game_over = True
print("Game over. ")
print(f"letters chosen: {guesses}")
print(" ")
print(display)
print(" ")
if lives == 0 or display.count("_") == 0:
break
if lives == 0:
print("Game over. You lose.")
elif lives > 0:
print("Congrats, you win! ")
What you can do is treat the string like an array/list.
So if you use loops:
x = ""#let's assume this is the users input
for i in range(len(y)): #y is the string your checking against
if x == y[i]:
from here what I'm thinking is that if they are equal it would add that letter to a string
Let's say the string is "Today was fun" then would have an array like this, [""."" and so on but you'd have to find a way to factor in spaces and apostrophes. So if the letter is == to that part of the string
#this is a continuation of the code, so under if
thearray[theposition] == the letter
But looking a your code your game is diffrent from the regular one so, also consider using a while look
gamewon = False
number of trials = 10
while gamewon == False and number of trials > 0:
#the whole checking process
if x == guess:
gamewon == True
print ........# this is if your doing word for word else use
the code above
else:
number of trials = number of trials - 1
I think that's it I know its a bit all over the place but you can always ask for help and I'll explain plus I was referring to your code things i thought you could fix
First you should accept both a and A by using guess = guess.lower(). The you have to search the string for the character guessed and find the positions.
guess = guess.lower()
# Find the position(s) of the character guessed
pos = [idx for idx,ch in enumerate(correct_word) if ch == guess]
if pos:
print('Letter Found')
guess_left -= 1
Another way to understand the for-loop is:
pos = []
for idx,ch in enumerate(correct_word):
if ch == guess:
pos.append(idx)

Hangman 2 for Invent with Python

So I'm working on inventwithpython, and I'm on the hangman 2 chapter. But when the game starts, it's already at the 7th strike hangman picture. I'm not sure where the problem is. Here is my code:
import random
HANGMANPICS = ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''', '''
+---+
| |
O |
/| |
|
|
=========''', '''
+---+
| |
O |
/|\ |
|
|
=========''', '''
+---+
| |
O |
/|\ |
/ |
|
=========''', '''
+---+
| |
O |
/|\ |
/ \ |
|
=========''', '''
+----+
| |
[O |
/|\ |
/ \ |
|
==========''', '''
+----+
| |
[O] |
/|\ |
/ \ |
|
==========''']
words = 'ant baboon badger bat bear beaver camel cat clam cobra cougar coyote crow deer dog donkey duck eagle ferret fox frog goat goose hawk lion lizard llama mole monkey moose mouse mule newt otter owl panda parrot pigeon python rabbit ram rat raven rhino salmon seal shark sheep skunk sloth snake spider stork swan tiger toad trout turkey turtle weasel whale wolf wombat zebra'.split()
def getRandomWord(wordList):
# This function returns a random string from the passed list of strings.
wordIndex = random.randint(0, len(wordList) - 1)
return wordList[wordIndex]
def displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord):
print(HANGMANPICS[len(HANGMANPICS) -1])
print()
print('Missed letters:', end=' ')
for letter in missedLetters:
print(letter, end=' ')
print()
blanks = '_' * len(secretWord)
for i in range(len(secretWord)): # replace blanks with correctly guessed letters
if secretWord[i] in correctLetters:
blanks = blanks[:i] + secretWord[i] + blanks[i+1:]
for letter in blanks: # show the secret word with spaces in between each letter
print(letter, end=' ')
print()
def getGuess(alreadyGuessed):
# Returns the letter the player entered. This function makes sure the player entered a single letter, and not something else.
while True:
print('Guess a letter.')
guess = input()
guess = guess.lower()
if len(guess) != 1:
print('Please enter a single letter.')
elif guess in alreadyGuessed:
print('You have already guessed that letter. Choose again.')
elif guess not in 'abcdefghijklmnopqrstuvwxyz':
print('Please enter a LETTER.')
else:
return guess
def playAgain():
# This function returns True if the player wants to play again, otherwise it returns False.
print('Do you want to play again? (yes or no)')
return input().lower().startswith('y')
print('H A N G M A N')
missedLetters = ''
correctLetters = ''
secretWord = getRandomWord(words)
gameIsDone = False
while True:
displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord)
# Let the player type in a letter.
guess = getGuess(missedLetters + correctLetters)
if guess in secretWord:
correctLetters = correctLetters + guess
# Check if the player has won
foundAllLetters = True
for i in range(len(secretWord)):
if secretWord[i] not in correctLetters:
foundAllLetters = False
break
if foundAllLetters:
print('Yes! The secret word is "' + secretWord + '"! You have won!')
gameIsDone = True
else:
missedLetters = missedLetters + guess
# Check if player has guessed too many times and lost
if len(missedLetters) == len(HANGMANPICS) - 1:
displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord)
print('You have run out of guesses!\nAfter ' + str(len(missedLetters)) + ' missed guesses and ' + str(len(correctLetters)) + ' correct guesses, the word was "' + secretWord + '"')
gameIsDone = True
# Ask the player if they want to play again (but only if the game is done).
if gameIsDone:
if playAgain():
missedLetters = ''
correctLetters = ''
gameIsDone = False
secretWord = getRandomWord(words)
else:
break
(To explain more about my problem:) So when you start the game, the hangman image should be the first picture in HANGMANPICS, but instead, it's the last picture in HANGMANPICS. I do have a feeling the problem in on print(HANGMANPICS[len(HANGMANPICS) -1]) but may not be there either. All help would be appreciated!
Yes, that's the problem. You specifically tell it to print the last element of the file. Instead, use the length of the missed letters list.
print(HANGMANPICS[len(missedLetters)])
With that change, it seems to work pretty well.

Python Hangman code

For my Computing Science controlled assessment I have been asked to create a Hangman game with Python. However, in creating the game, there has been an error message that specifies something not in my code.
Traceback (most recent call last):
File "Z:\Documents\hangman.py", line 40, in <module>
generated_word = random.choice(random)
File "Q:\Pywpygam.001\Python3.2.3\lib\random.py", line 249, in choice
i = self._randbelow(len(seq))
TypeError: object of type 'module' has no len()
I don't see anything wrong in the code and it doesn't specify what's wrong. Here is my code:
import time
print('Lets play hangman')
print("""
_______
| |
| O
| |
| \- -/
| |
| / \\
| / \\
____|____
\n""")
print("""
you get 7 lives to guess the letters in the word. if you guess
incorrectly more of the hangman will appear and you lose a life. when you have
used your 7 lives, the man will have hung and you will have lost. If you guess a
correct letter, it will be show and if you guess the word without using the 7
turns, you win!
\n""")
easy_words = ['string', 'loop', 'python', 'print', 'run']
medium_words = ['module', 'input', 'logic', 'output']
hard_words = ['graphics window', 'variable', 'iteration', 'modules']
random_words = ['string', 'loop', 'python', 'print', 'run', 'graphics window', 'variable', 'iteration', 'modules', 'module', 'input', 'logic', 'output ']
time.sleep(2)
print ("What level would you like to play at? Easy, Medium or Hard or Random?")
level_of_difficulty = input()
time.sleep(2)
print ("The program is now generating your word...")
if level_of_difficulty == 'Easy':
generated_word = random.choice(easy_words)
elif level_of_difficulty == 'Medium':
generated_word = random.choice(medium_words)
elif level_of_difficulty == 'Hard':
generated_word = random.choice(hard_words)
elif level_of_difficulty == 'Random':
generated_word = random.choice(random_words)
else:
generated_word = random.choice(random_words)
guessed = ''
lives = 7
while lives > 0:
missed = 0
print()
for letter in generated_word:
if letter in guessed:
print (letter,end=' ')
else:
print ('_',end=' ')
missed = missed + 1
if missed == 0:
print ('\n\nYou win!')
quit()
break
guess=input("please guess a letter:")
guessed = guessed + guess
if guess not in generated_word:
print ('\n that letter is not in this word, your lives have been decreased by 1.')
print ('please try another letter.')
lives = lives - 1
missed = missed + 1
print('your new lives value is')
print(lives)
if lives < 7:
print(''' _______
| | ''')
if lives < 6:
print(' | O ')
if lives < 5:
print(' | | ')
if lives < 4:
print(' | \- -/ ')
if lives < 3:
print(' | | ')
if lives < 2:
print(' | / \\ ')
if lives < 1:
print(' | / \\ ')
if lives == 0:
print('___|___ ')
print('GAME OVER! You have run out of lives and lost the game')
print('the secret word was')
print(generated_word)
quit()
What I am trying to do is make it so the generated word is displayed in the window with a _, and when the letter is guessed correctly, the appropriate _ is filled with the letter.
Any ideas will be appreciated!
I think these lines are wrong:
generated_word = random.choice(random)
You are passing the module "random" as parameter. I think you should pass the variable "random_words"?
I see what I did wrong, thanks for pointing out the
generated_word = random.choice(random)
bit, but I also saw that on the
while lives > 0:
missed = 0
print()
for letter in generated_word:
if letter in guessed:
I have made a spelling mistake.
Thanks everyone!

After providing move in python code for tic tac toe, letter is not drawn on board

not able to proceed further after providing move number in Python code for tic tac toe. It asks for next move then cell number is provided but makeMove() method is not getting executed. It will ask again next move till dont press enter key twice. Please help me to resolve this code.
#Tic Tac Toe
import random
def drawBoard(board):
# This function prints out the board that it was passed.
# "board" is a list of 10 strings representing the board (ignore index 0)
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
print(' | |')
print('-----------')
print(' | |')
print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])
print(' | |')
def inputPlayerLetter():
# Lets the player type which letter they want to be.
#
letter = ''
while not (letter == 'X' or letter == 'O'):
#print('Do you want to be X or O?')
#letter = input().upper()
letter = (raw_input("Do you want to be X or O? ")).upper()
print "Received input is : ", letter.upper()
#
if letter == 'X':
return ['X', 'O']
else:
return ['O', 'X']
def whoGoesFirst():
# Randomly choose the player who goes first.
if random.randint(0, 1) == 0:
return 'computer'
else:
return 'player'
def playAgain():
print('Do you want to play again? (yes or no)')
return raw_input().lower().startswith('y')
def makeMove(board, letter, move):
board[move] = letter
def isWinner(bo, le):
#
#
return ((bo[7] == le and bo[8] == le and bo[9] == le) or # across the top
(bo[4] == le and bo[5] == le and bo[6] == le) or # across the middle
(bo[1] == le and bo[2] == le and bo[3] == le) or # across the bottom
(bo[7] == le and bo[4] == le and bo[1] == le) or # down the left side
(bo[8] == le and bo[5] == le and bo[2] == le) or # down the middle
(bo[9] == le and bo[6] == le and bo[3] == le) or # down the right side
(bo[7] == le and bo[5] == le and bo[3] == le) or # diagonal
(bo[9] == le and bo[5] == le and bo[1] == le)) # diagonal
def getBoardCopy(board):
# Make a duplicate of the board list and return it the duplicate.
dupeBoard = []
for i in board:
dupeBoard.append(i)
return dupeBoard
def isSpaceFree(board, move):
# Return true if the passed move is free on the passed board.
return board[move] == ' '
def getPlayerMove(board):
# Let the player type in their move.
move = ' '
while move not in '1 2 3 4 5 6 7 8 9'.split() or not isSpaceFree(board, int(move)):
print('What is your next move? (1-9)')
move = raw_input()
return int(move)
def chooseRandomMoveFromList(board, movesList):
# Returns a valid move from the passed list on the passed board.
# Returns None if there is no valid move.
possibleMoves = []
for i in movesList:
if isSpaceFree(board, i):
possibleMoves.append(i)
if len(possibleMoves) != 0:
return random.choice(possibleMoves)
else:
return None
def getComputerMove(board, computerLetter):
# Given a board and the computer's letter, determine where to move and return that move.
if computerLetter == 'X':
playerLetter = 'O'
else:
playerLetter = 'X'
# Here is our algorithm for our Tic Tac Toe AI:
# First, check if we can win in the next move
for i in range(1, 10):
copy = getBoardCopy(board)
if isSpaceFree(copy, i):
makeMove(copy, computerLetter, i)
if isWinner(copy, computerLetter):
return i
# Check if the player could win on their next move, and block them.
for i in range(1, 10):
copy = getBoardCopy(board)
if isSpaceFree(copy, i):
makeMove(copy, playerLetter, i)
if isWinner(copy, playerLetter):
return i
# Try to take one of the corners, if they are free.
move = chooseRandomMoveFromList(board, [1, 3, 7, 9])
if move != None:
return move
# Try to take the center, if it is free.
if isSpaceFree(board, 5):
return 5
# Move on one of the sides.
return chooseRandomMoveFromList(board, [2, 4, 6, 8])
def isBoardFull(board):
# Return True if every space on the board has been taken. Otherwise return False.
for i in range(1, 10):
if isSpaceFree(board, i):
return False
return True
print('Welcome to Tic Tac Toe!')
while True:
# Reset the board
theBoard = [' '] * 10
playerLetter, computerLetter = inputPlayerLetter()
turn = whoGoesFirst()
print('The ' + turn + ' will go first.')
gameIsPlaying = True
while gameIsPlaying:
if turn == 'player':
#
drawBoard(theBoard)
move = getPlayerMove(theBoard)
if isWinner(theBoard, playerLetter):
drawBoard(theBoard)
print('Hooray! You have won the game!')
gameIsPlaying = False
else:
if isBoardFull(theBoard):
drawBoard(theBoard)
print('The game is a tie!')
break
else:
turn = 'computer'
else:
#
move = getComputerMove(theBoard, computerLetter)
makeMove(theBoard, computerLetter, move)
if isWinner(theBoard, computerLetter):
drawBoard(theBoard)
print('The computer has beaten you! You lose.')
gameIsPlaying = False
else:
if isBoardFull(theBoard):
drawBoard(theBoard)
print('The game is a tie!')
break
else:
turn = 'player'
if not playAgain():
break
Output :
Welcome to Tic Tac Toe!
Do you want to be X or O? x
Received input is : X
The computer will go first.
| |
O | |
| |
| |
| |
| |
| |
| |
| |
What is your next move? (1-9)
5
| |
O | |
| |
| |
| |
| |
| |
O | |
| |
What is your next move? (1-9)
5
| |
O | |
| |
| |
O | |
| |
| |
O | |
| |
The computer has beaten you! You lose.
Do you want to play again? (yes or no)
Replace input() call with raw_input() in getPlayerMove function.
Your code doesn't work, because input() is an equivalent to eval(raw_input()). If user puts a number then input returns an integer value. That means move not in '1 2 3 4 5 6 7 8 9'.split() is always False

Categories

Resources