import random
import time
board = [0,1,2,
3,4,5,
6,7,8]
def show():
print (board[0],"|",board[1],"|",board[2])
print ("----------")
print (board[3],"|",board[4],"|",board[5])
print ("----------")
print (board[6],"|",board[7],"|",board[8])
def checkLine(char, spot1, spot2, spot3):
if board[spot1] == char and board[spot2] == char and board[spot3] ==char:
return True
def checkAll(char):
if checkLine(char, 0, 1, 2):
return True
if checkLine(char, 1, 4, 7):
return True
if checkLine(char, 2, 5, 8):
return True
if checkLine(char, 6, 7, 8):
return True
if checkLine(char, 3, 4, 5):
return True
if checkLine(char, 1, 2, 3):
return True
if checkLine(char, 2, 4, 6):
return True
if checkLine(char, 0, 4, 8):
return True
while True:
answer = input("Select a spot, any number 0 through 8:")
answer = int(answer)
time.sleep(1)
if board[answer] != 'x' and board[answer] !='o':
board[answer] = 'x'
if checkAll('x') == True:
print ("You win! Yay!")
break;
while True:
random.seed()
opponent = random.randint(0,8)
if board[opponent] != 'o' and board[opponent] != 'x':
board[opponent] = 'o'
if checkAll('o') == True:
print ("You loose! That's to bad.")
break;
break;
else:
print ("This spot is taken!")
show()
Restart my program?
Page 1 of 11 Replies - 242 Views - Last Post: 29 September 2012 - 05:23 PM
#1
Restart my program?
Posted 29 September 2012 - 12:50 PM
So, I've been programming a game for a while now... I've tried various types of codes for restarting my program.. Right now, I lost the code that helped me ask the person if they wanted to play again, but is there any way for me to program the code to make it ask you if you would like to play again? If so, thanks!
Replies To: Restart my program?
#2
Re: Restart my program?
Posted 29 September 2012 - 05:23 PM
Take all the code your currently have in while True and put it in a function called play. Then have another function like:
Honestly, your big problem is you don't know when to finish a game. Your play could look something like:
Note, global variable board is bad. Also, you need to reset it if you play again, anyway. Also,
Hope this helps.
def main():
random.seed() # only call this once
while True:
play()
# ask if they want to play again
# if no, break
print("Thanks for playing")
main()
Honestly, your big problem is you don't know when to finish a game. Your play could look something like:
def play():
board = [ str(i) for i in range(9) ]
available = 9
while True:
show(board)
playerTurn(board)
avaiable -= 1
if checkAll(board, 'x'):
print ("You win! Yay!")
break
if available>0:
computerTurn(board, available)
avaiable -= 1
if checkAll(board, 'o'):
print ("You loose! That's to bad.")
break
if available<1:
print ("Tie.")
break
show(board)
Note, global variable board is bad. Also, you need to reset it if you play again, anyway. Also,
Hope this helps.
This post has been edited by baavgai: 29 September 2012 - 05:23 PM
Page 1 of 1
|
|

New Topic/Question
Reply



MultiQuote




|