How to fix IOError in raspberry pi? - python

Traceback (most recent call last):
File "RoomCheck.py", line 4, in <module>
from grove_rgb_lcd import *
File "build/bdist.linux-armv7l/egg/grove_rgb_lcd.py", line 33, in <module>
...skip
These errors are generated.
I've also attached the error capture:
Code:
from flask import Flask
from flask import render_template
from grovepi import *
from grove_rgb_lcd import *
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
app = Flask(__name__)
#app.route("/read/<port>")
def readGpio(port):
try:
GPIO.setup(int(port), GPIO.IN)
if GPIO.input(int(port)) == True:
AHour = 0
AMin = 0
BHour =0
BMin = 0
A_Check = 0
B_Check = 0
if port == 4:
if A_Check == 0:
A_Check = 1
setRGB(0,128,64)
setRGB(0,255,0)
setText("A goes out")
res = "A_Check is" + A_Check +"\n" + "B_Check is" +
B_Check +"\n" + "A : " + AHour + "H" + AMin + "M" +"\n" + "B : " + BHour + "H" + BMin + "M"
else:
A_Check = 0
setRGB(0,128,64)
setRGB(0,255,0)
setText("A cames in")
AHour = 0
AMin = 0
res = "A_Check is" + A_Check +"\n" + "B_Check is" + B_Check +"\n" + "A : " + AHour + "H" + AMin + "M" +"\n" + "B : " + BHour + "H" + BMin + "M"
elif port ==17:
AHour += 1
if AHour > 24:
AHour = 0
setRGB(0,128,64)
setRGB(0,255,0)
setText("A : " + AHour + "H" + AMin + "M")
res = "A_Check is" + A_Check +"\n" + "B_Check is" + B_Check +"\n" + "A : " + AHour + "H" + AMin + "M" +"\n" + "B : " + BHour + "H" + BMin + "M"
elif port ==27:
AMin += 5
if AMin>60:
AMin = 0
setRGB(0,128,64)
setRGB(0,255,0)
setText("A : " + AHour + "H" + AMin + "M")
res = "A_Check is" + A_Check +"\n" + "B_Check is" + B_Check +"\n" + "A : " + AHour + "H" + AMin + "M" +"\n" + "B : " + BHour + "H" + BMin + "M"
elif port ==23:
if B_Check == 0:
B_Check = 1
setRGB(0,128,64)
setRGB(0,255,0)
setText("B goes out")
res = "A_Check is" + A_Check +"\n" + "B_Check is" + B_Check +"\n" + "A : " + AHour + "H" + AMin + "M" +"\n" + "B : " + BHour + "H" + BMin + "M"
else:
B_Check = 0
setRGB(0,128,64)
setRGB(0,255,0)
setText("B cames in")
BHour = 0
BMin = 0
res = "A_Check is" + A_Check +"\n" + "B_Check is" + B_Check +"\n" + "A : " + AHour + "H" + AMin + "M" +"\n" + "B : " + BHour + "H" + BMin + "M"
elif port ==24:
BHour += 1
if BHour > 24:
BHour = 0
setRGB(0,128,64)
setRGB(0,255,0)
setText("B : " + BHour + "H" + BMin + "M")
res = "A_Check is" + A_Check +"\n" + "B_Check is" + B_Check +"\n" + "A : " + AHour + "H" + AMin + "M" +"\n" + "B : " + BHour + "H" + BMin + "M"
elif port ==25:
BMin += 5
if BMin>60:
BMin = 0
setRGB(0,128,64)
setRGB(0,255,0)
setText("B : " + BHour + "H" + BMin + "M")
res = "A_Check is" + A_Check +"\n" + "B_Check is" + B_Check +"\n" + "A : " + AHour + "H" + AMin + "M" +"\n" + "B : " + BHour + "H" + BMin + "M"
except:
res = "Read error from GPIO " + port + "."
templateData = {
'title' : 'Check our RoomMate',
'res' : res
}
return render_template('gpio.html', **templateData)
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8888, debug=True)

Related

Weird str right after execution

I've been playing around with some code and recently found this issue out, once this code runs it returns "None" right under the players name and health, I've been trying to figure out why and changed a lot of the code but the issue still remains, does anyone know why this might be? much appreciated!
import random
import math
import os
import time
def return_health(name, health, maxHealth, healthDashes):
dashConvert = int(maxHealth/healthDashes)
currentDashes = int(health/dashConvert)
remainingHealth = healthDashes - currentDashes
healthDisplay = '-' * currentDashes
remainingDisplay = ' ' * remainingHealth
percent = str(int((health/maxHealth)*100)) + "%"
print(name+" "+"|" + healthDisplay + remainingDisplay + "|")
print(" " + percent)
class Player():
def __init__(self, name, maxhealth, health, healthdashes, offense, jutsu1, jutsu2, jutsu3):
self.name = name
self.maxhealth = maxhealth
self.health = health
self.healthdashes = healthdashes
self.offense = offense
self.jutsu1 = jutsu1
self.jutsu2 = jutsu2
self.jutsu3 = jutsu3
class Jutsu():
def __init__(self, name, damage):
self.name = name
self.damage = damage
## Jutsu's
Rasengan = Jutsu("Rasengan", 15)
Rasenshuriken = Jutsu("Rasenshuriken", 30)
VermillionRasengan = Jutsu("Vermillion Rasengan", 50)
Chidori = Jutsu("Chidori", 15)
OnxyChidori = Jutsu("Onxy Chidori", 30)
SusanoArrow = Jutsu("Susano's Arrow", 50)
## Player's
Naruto = Player("Naruto Uzumaki", 100, 100, 20, 10, Rasengan, Rasenshuriken,
VermillionRasengan)
Sasuke = Player("Sasuke Uchiha", 100, 100, 20, 10, Chidori, OnxyChidori, SusanoArrow)
def fight(player1, player2):
os.system("clear")
while True:
if player1.health <= 0:
os.system("clear")
print(player1.name + " has been defeated.")
time.sleep(3)
break
elif player2.health <= 0:
os.system("clear")
print(player2.name + " has been defeated")
time.sleep(3)
else:
print(return_health(player1.name, player1.health, player1.maxhealth, player1.healthdashes))
print(return_health(player2.name, player2.health, player2.maxhealth, player2.healthdashes))
print(player1.name + "'s turn.'")
print()
print("Choose your move!")
print("1. Attack" + " : " + str(+player1.offense))
print("2. " + player1.jutsu1.name + " : " +
str(+player1.jutsu1.damage))
print("3. " + player1.jutsu2.name + " : " +
str(+player1.jutsu2.damage))
print("4. " + player1.jutsu3.name + " : " +
str(+player1.jutsu3.damage))
choice = input("> ")
os.system("clear")
if choice == "1":
print(player1.name + " has attacked " + player2.name +
" for " + str(player1.offense) + " damage.")
player2.health -= player1.offense
elif choice == "2":
print(player1.name + " attacked " + player2.name + " with " +
player1.jutsu1.name + " for " +
str(player1.jutsu1.damage) + " damage.")
player2.health -= player1.jutsu1.damage
elif choice == "3":
print(player1.name + " attacked " + player2.name + " with " +
player1.jutsu2.name + " for " +
str(player1.jutsu2.damage) + " damage.")
player2.health -= player1.jutsu2.damage
elif choice == "4":
print(player1.name + " attacked " + player2.name + " with " +
player1.jutsu3.name + " for " +
str(player1.jutsu3.damage) + " damage.")
player2.health -= player1.jutsu3.damage
time.sleep(2)
os.system("clear")
if player2.health <= 0:
os.system("clear")
print(player2.name + " has been defeated.")
time.sleep(3)
break
else:
print(player2.name + " : " + str(player2.health))
print(player1.name + " : " + str(player1.health))
print(player2.name + "'s turn.'")
print()
print("Choose your move!")
print("1. Attack" + " : " + str(+player2.offense))
print("2. " + player2.jutsu1.name + " : " +
str(+player2.jutsu1.damage))
print("3. " + player2.jutsu2.name + " : " +
str(+player2.jutsu2.damage))
print("4. " + player2.jutsu3.name + " : " +
str(+player2.jutsu3.damage))
choice = input("> ")
os.system("clear")
if choice == "1":
print(player2.name + " has attacked " + player1.name +
" for " + str(player2.offense) + " damage.")
player1.health -= player2.offense
elif choice == "2":
print(player2.name + " attacked " + player1.name +
" with " + player2.jutsu1.name + " for " +
str(player2.jutsu1.damage) + " damage.")
player1.health -= player2.jutsu1.damage
elif choice == "3":
print(player2.name + " attacked " + player1.name +
" with " + player2.jutsu2.name + " for " +
str(player2.jutsu2.damage) + " damage.")
player1.health -= player2.jutsu2.damage
elif choice == "4":
print(player2.name + " attacked " + player1.name +
" with " + player2.jutsu3.name + " for " +
str(player2.jutsu3.damage) + " damage.")
player1.health -= player2.jutsu3.damage
time.sleep(2)
os.system("clear")
fight(Naruto, Sasuke)
Consider the following line
print(return_health(player1.name, player1.health, player1.maxhealth, player1.healthdashes))
You are asking python to print the result of the return_health function. The return_health function doesn't actually return anything so the result of the function is None.
You don't need the print at the start of this line since the return_health function already prints the health information.
Also, it would be better Object Oriented Programming, to make this functionality part of the Player class.
Consider the below change
class Player():
def __init__(self, name, maxhealth, health, healthdashes, offense, jutsu1, jutsu2, jutsu3):
self.name = name
self.maxhealth = maxhealth
self.health = health
self.healthdashes = healthdashes
self.offense = offense
self.jutsu1 = jutsu1
self.jutsu2 = jutsu2
self.jutsu3 = jutsu3
def showhealth(self):
dashConvert = int(self.maxhealth/self.healthdashes)
currentDashes = int(self.health/dashConvert)
remainingHealth = self.healthdashes - currentDashes
healthDisplay = '-' * currentDashes
remainingDisplay = ' ' * remainingHealth
percent = str(int((self.health/self.maxhealth)*100)) + "%"
print(self.name+" "+"|" + healthDisplay + remainingDisplay + "|")
print(" " + percent)
Then when you want to output the health of the player you just call something like
player1.showhealth()
You could also have an "Attack" method for the class.
def attack(self, other_player, chosen_jutsu):
....
If player1 is attacking player 2, this would look like
player1.attack(player2, choice)
return_health returns nothing (None) and that's what you print, because you called print(return_health(...)).
If you expect the function to print stuff on its own (it currently does), better call it print_health and not return_health, and just call it without also printing its (empty) return value.

My input in if statement is not working as expected

My input in my if statement is not working. I am using Python3 and the problem is at the first if statement in the defined function.
import random
random1 = random.randint(1, 11)
random2 = random.randint(1, 11)
correct = random1 * random2
list_of_correct = []
list_of_wrong = []
def ex():
proceed = input("Proceed?: ")
if proceed.lower == "yes":
ans = input("What is " + str(random1) + " * " + str(random2) + "?: ")
if int(ans) == correct:
print("Correct!")
list_of_correct.append(str(random1 + ":" + str(random2) + ":" + str(ans)))
print(ex())
else:
print("Incorrect!")
list_of_wrong.append(str(random1) + ":" + str(random2) + ":" + str(ans))
elif proceed.lower == "mfm":
print(list_of_correct)
print(list_of_wrong)
print(ex())
You compare a function proceed.lower against a string 'yes' - they are never the same.
You need to call the function:
if proceed.lower() == "yes":
to convert your input to lower case for your comparison.
print("".lower) # <built-in method lower of str object at 0x7fc134277508>
Fixed code
import random
random1 = random.randint(1, 11)
random2 = random.randint(1, 11)
correct = random1 * random2
list_of_correct = []
list_of_wrong = []
def ex():
proceed = input("Proceed?: ")
if proceed.lower() == "yes":
ans = input("What is " + str(random1) + " * " + str(random2) + "?: ")
if int(ans) == correct:
print("Correct!")
list_of_correct.append(str(random1 + ":" + str(random2) + ":" + str(ans)))
print(ex())
else:
print("Incorrect!")
list_of_wrong.append(str(random1) + ":" + str(random2) + ":" + str(ans))
elif proceed.lower() == "mfm":
print(list_of_correct)
print(list_of_wrong)
print(ex())

function with operators as parameter

i just started coding for fun and i'm trying to build a calculator that uses userinput. 2 numbers and one operator. I'm realy realy new to coding and currently limited to very simple use of if statements and while/for loops and i just started looking into functions. I have been trying to put this code into a function for a while but i can't find a solution to use the string "operator" as an actual operator in the function.
there must be a way to make all of this shorter.
if used_op == "+":
print("> " + str(number_1) + " + " + str(number_2) + " = " + str(number_1 + number_2) + " <")
elif used_op == "-":
print("> " + str(number_1) + " - " + str(number_2) + " = " + str(number_1 - number_2) + " <")
elif used_op == "*":
print("> " + str(number_1) + " * " + str(number_2) + " = " + str(number_1 * number_2) + " <")
elif used_op == "/":
print("> " + str(number_1) + " / " + str(number_2) + " = " + str(number_1 / number_2) + " <")
elif used_op == "%":
print("> " + str(number_1) + " % " + str(number_2) + " = " + str(number_1 % number_2) + " <")
elif used_op == "**":
print("> " + str(number_1) + " ** " + str(number_2) + " = " + str(number_1 ** number_2) + " <")
elif used_op == "//":
print("> " + str(number_1) + " // " + str(number_2) + " = " + str(number_1 // number_2) + " <")
What I tried is something like this:
def solve(op):
print("> " + str(number_1) + op + str(number_2) + " = " + str(
number_1 + **op** + number_2) + " <")
solve(used_op)
I tried to find a solution for this on the internet for a while but i had no luck so far.
You can use a dictionary and the operator module to do what you want:
import operator
# this will act like a sort of case statement or switch
operations = {
'>': operator.gt,
'<': operator.lt,
'=': operator.eq,
'+': operator.add,
'-': operator.sub,
'/': operator.div,
'*': operator.mul,
'**': operator.pow,
'//': operator.floordiv,
... # so on and so forth
}
def calculate(num1, num2, op):
# operation is a function that is grabbed from the dictionary
operation = operations.get(op)
if not operation:
raise KeyError("Operation %s not supported"%op)
# Call the operation with your inputs
num3 = operation(num1, num2)
print('%3.2f %s %3.2f = %3.2f' % (num1, op, num2, num3))
calculate(1,2, '+')
# 1.00 + 2.00 = 3.00
Simply evaluate your mathematical expression and python will do the rest of the job for you.
This can of course be done with the in-built eval() function.
Here are some examples how you can use it:
>>> eval("1+1")
2
>>> A = 2
>>> eval("A * 3")
6
The function that you're trying to write, could look something like this
def solve(a, b, op):
expression = str(a) + op + str(b)
print("> " + expression + "=" + str(eval(expression)))
solve(1, 2, "+") # > 1+2=3
solve(10, 10, "*") # > 10*10=100
solve(4, 2, "/") # > 4/2=2.0
solve(5, 10, "-") # > 5-10=-5

I'm getting a type error and I'm not sure why

I am using Python 2.5. I am not sure what's going wrong. I've tried this a million different ways and I am so confused.
Here is my code:
import math
quad_function = "(a * x^2) + b * x + c"
print "A quadratic function is:" + quad_function
a_input = raw_input("Is 'a' given?")
b_input = raw_input("Is 'b' given?")
c_input = raw_input("Is 'c' given?")
x_input = raw_input("Are any of the solutions given?")
if a_input == "yes":
a = int(raw_input("What is 'a'?"))
if b_input == "yes":
b = int(raw_input("What is 'b'?"))
if c_input == "yes":
c = int(raw_input("What is 'c'?"))
if x_input == "one":
x_1 = int(raw_input("What is the first solution?"))
if x_input == "both":
x_1 = int(raw_input("What is the first solution"))
x_2 = int(raw_input("What is the second solution"))
print 'The quadratic function is:' + str(a) + 'x^2' + '+' + str(b) + 'x' + "+" + str(c)
d = b ** 2 - 4*a*c
if d > 1:
num_roots = 2
if d == 1:
num_roots = 1
if d < 1:
num_roots = 0
print "There are " + str(num_roots) + " roots"
if x_input == "no" and d > 2 and a_input == 'yes' and b_input == 'yes' and c_input == 'yes':
x1 = float(((-b) + math.sqrt(d))/(2*a))
x2 = float(((-b) - math.sqrt(d))/(2*a))
print "The two solutions are: " + str(x1) * "and " + str(x2)
You've used an asterisk where you intended to use a plus sign. Replace
print "The two solutions are: " + str(x1) * "and " + str(x2)
with
print "The two solutions are: " + str(x1) + "and " + str(x2)

Expected an indented block in Python game

I'm writing a program to play Connect Four with Python and I'm not sure how to resolve the "expected an indented block" error that is being thrown at me in certain areas. Any time I try running a [row][col] section, it throws the error up. I'm using some example code to help me develop my own and here's what I'm using:
import random
def winner(board):
"""This function accepts the Connect 4 board as a parameter.
If there is no winner, the function will return the empty string "".
If the user has won, it will return 'X', and if the computer has
won it will return 'O'."""
# Check rows for winner
for row in range(6):
for col in range(3):
if (board[row][col] == board[row][col + 1] == board[row][col + 2] ==\
board[row][col + 3]) and (board[row][col] != " "):
return board[row][col]
# Check columns for winner
for col in range(6):
for row in range(3):
if (board[row][col] == board[row + 1][col] == board[row + 2][col] ==\
board[row + 3][col]) and (board[row][col] != " "):
return board[row][col]
# Check diagonal (top-left to bottom-right) for winner
for row in range(3):
for col in range(4):
if (board[row][col] == board[row + 1][col + 1] == board[row + 2][col + 2] ==\
board[row + 3][col + 3]) and (board[row][col] != " "):
return board[row][col]
# Check diagonal (bottom-left to top-right) for winner
for row in range(5, 2, -1):
for col in range(3):
if (board[row][col] == board[row - 1][col + 1] == board[row - 2][col + 2] ==\
board[row - 3][col + 3]) and (board[row][col] != " "):
return board[row][col]
# No winner: return the empty string
return ""
def display_board(board):
print " 1 2 3 4 5 6 7"
print "1: " + board[0][0] + " | " + board[0][1] + " | " + board[0][2] + " | " + board[0][3] + " | " + board[0][4] + " | " + board[0][5] + " | " + board[0][6] + " | " + board[0][7]
print " ---+---+---+---+---+---+---"
print "2: " + board[1][0] + " | " + board[1][1] + " | " + board[1][2] + " | " + board[1][3] + " | " + board[1][4] + " | " + board[1][5] + " | " + board [1][6] + " | " + board [1][7]
print " ---+---+---+---+---+---+---+"
print "3: " + board[2][0] + " | " + board[2][1] + " | " + board[2][2] + " | " + board[2][3] + " | " + board [2][4] + " | " + board [2][5] + " | " + board [2][6] + " | " + board [2][7]
print " ---+---+---+---+---+---+---+"
print "4: " + board[3][0] + " | " + board[3][1] + " | " + board[3][2] + " | " + board[3][3] + " | " + board [3][4] + " | " + board [3][5] + " | " + board [3][6] + " | " + board [3][7]
print " ---+---+---+---+---+---+---+"
print "5: " + board[4][0] + " | " + board[4][1] + " | " + board[4][2] + " | " + board[4][3] + " | " + board [4][4] + " | " + board [4][5] + " | " + board [4][6] + " | " + board [4][7]
print " ---+---+---+---+---+---+---+"
print "6: " + board[5][0] + " | " + board[5][1] + " | " + board[5][2] + " | " + board[5][3] + " | " + board [5][4] + " | " + board [5][5] + " | " + board [5][6] + " | " + board [5][7]
print
def make_user_move(board):
try:
valid_move = False
while not valid_move:
col = input("What col would you like to move to (1-7):")
for row in range (6,0,-1):
if (1 <= row <= 6) and (1 <= col <= 7) and (board[row-1][col-1] == " "):
board[row-1][col-1] = 'X'
valid_move = True
break
else:
print "Sorry, invalid square. Please try again!\n"
except NameError:
print "Only numbers are allowed."
except IndexError:
print "You can only select columns from (1-7), and rows from (1-6)."
def make_computer_move(board):
# Code needed here...
valid_move = False
while not valid_move:
row = random.randint(0,5)
col = random.randint(0, 6)
for row in range (5,0,-1):
if board[row][col] == " ":
board[row][col] = "O"
valid_move = True
break
def main():
free_cells = 42
users_turn = True
count = 1
ttt_board = [ [ " ", " ", " ", " ", " ", " "," ", " "], [ " ", " ", " ", " ", " "," ", " ", " "], [ " ", " ", " ", " ", " ", " ", " ", " "], [ " ", " ", " ", " ", " ", " ", " ", " "], [ " ", " ", " ", " ", " ", " ", " ", " "], [ " ", " ", " ", " ", " ", " ", " ", " "] ]
print "\nHALL OF FAME \n"
try:
hall_of_fame = open("HallOfFame.txt", 'r')
for name in hall_of_fame:
print str(count) + ".", name
print
count += 1
hall_of_fame.close()
except IOError:
print "No Human Has Ever Beat Me.. mwah-ha-ha-ha!\n"
choice = raw_input("Would you like to go first? (y or n): ")
if (choice == 'y' or choice=='Y'):
users_turn = True
elif (choice == 'n' or choice =='N') :
users_turn = False
else:
print 'invalid input'
while not winner(ttt_board) and (free_cells > 0):
display_board(ttt_board)
if users_turn:
make_user_move(ttt_board)
users_turn = not users_turn
else:
make_computer_move(ttt_board)
users_turn = not users_turn
free_cells -= 1
display_board(ttt_board)
if (winner(ttt_board) == 'X'):
print "You Won!"
print "Your name will now be added to the Hall of Fame!"
hall_of_fame = open("HallOfFame.txt", 'a')
name = raw_input("Enter your name: ")
hall_of_fame.write(name+ '\n')
print "Your name has been added to the Hall of Fame!"
hall_of_fame.close()
print "\nGAME OVER"
elif (winner(ttt_board) == 'O'):
print "The Computer Won!"
print "\nGAME OVER"
else:
print "Stalemate!"
print "\nGAME OVER \n"
#start the game
main()
It looks like you are not indenting your for loops:
for row in range(6):
for col in range(3):
if (board[row][col] == board[row][col + 1] == board[row][col + 2] ==\
board[row][col + 3]) and (board[row][col] != " "):
return board[row][col]
The : denotes the need for an indent on the next line.
There are a LOT of places where the indentation is just plain missing for inexplicable reasons. As #davidism mentions, indentation in python is used to indicate nesting levels; so this code is completely unusable in its current state.
Here's my attempt to GUESS what your code was MEANT to do, so you can get an idea of all the places where whitespace matters, but it is just missing in your code.
import random
def winner(board):
for row in range(6):
for col in range(3):
if (board[row][col] == board[row][col + 1] == board[row][col + 2] == \
board[row][col + 3]) and (board[row][col] != " "):
return board[row][col] # Check columns for winner
for col in range(6):
for row in range(3):
if (board[row][col] == board[row + 1][col] == board[row + 2][col] == \
board[row + 3][col]) and (board[row][col] != " "):
return board[row][col]
# Check diagonal (top-left to bottom-right) for winner
for row in range(3):
for col in range(4):
if (board[row][col] == board[row + 1][col + 1] == board[row + 2][col + 2] == \
board[row + 3][col + 3]) and (board[row][col] != " "):
return board[row][col]
# Check diagonal (bottom-left to top-right) for winner
for row in range(5, 2, -1):
for col in range(3):
if (board[row][col] == board[row - 1][col + 1] == board[row - 2][col + 2] == \
board[row - 3][col + 3]) and (board[row][col] != " "):
return board[row][col]
# No winner: return the empty string
return ""
def display_board(board):
print " 1 2 3 4 5 6 7"
print "1: " + board[0][0] + " | " + board[0][1] + " | " + board[0][2] + " | " + board[0][3] + " | " + board[0][
4] + " | " + board[0][5] + " | " + board[0][6] + " | " + board[0][7]
print " ---+---+---+---+---+---+---"
print "2: " + board[1][0] + " | " + board[1][1] + " | " + board[1][2] + " | " + board[1][3] + " | " + board[1][
4] + " | " + board[1][5] + " | " + board[1][6] + " | " + board[1][7]
print " ---+---+---+---+---+---+---+"
print "3: " + board[2][0] + " | " + board[2][1] + " | " + board[2][2] + " | " + board[2][3] + " | " + board[2][
4] + " | " + board[2][5] + " | " + board[2][6] + " | " + board[2][7]
print " ---+---+---+---+---+---+---+"
print "4: " + board[3][0] + " | " + board[3][1] + " | " + board[3][2] + " | " + board[3][3] + " | " + board[3][
4] + " | " + board[3][5] + " | " + board[3][6] + " | " + board[3][7]
print " ---+---+---+---+---+---+---+"
print "5: " + board[4][0] + " | " + board[4][1] + " | " + board[4][2] + " | " + board[4][3] + " | " + board[4][
4] + " | " + board[4][5] + " | " + board[4][6] + " | " + board[4][7]
print " ---+---+---+---+---+---+---+"
print "6: " + board[5][0] + " | " + board[5][1] + " | " + board[5][2] + " | " + board[5][3] + " | " + board[5][
4] + " | " + board[5][5] + " | " + board[5][6] + " | " + board[5][7]
print
def make_user_move(board):
try:
valid_move = False
while not valid_move:
col = input("What col would you like to move to (1-7):")
for row in range(6, 0, -1):
if (1 <= row <= 6) and (1 <= col <= 7) and (board[row - 1][col - 1] == " "):
board[row - 1][col - 1] = 'X'
valid_move = True
break
else:
print "Sorry, invalid square. Please try again!\n"
except NameError:
print "Only numbers are allowed."
except IndexError:
print "You can only select columns from (1-7), and rows from (1-6)."
def make_computer_move(board):
# Code needed here...
valid_move = False
while not valid_move:
row = random.randint(0, 5)
col = random.randint(0, 6)
for row in range(5, 0, -1):
if board[row][col] == " ":
board[row][col] = "O"
valid_move = True
break
def main():
free_cells = 42
users_turn = True
count = 1
ttt_board = [[" ", " ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " ", " "],
[" ", " ", " ", " ", " ", " ", " ", " "], [" ", " ", " ", " ", " ", " ", " ", " "]]
print "\nHALL OF FAME \n"
try:
hall_of_fame = open("HallOfFame.txt", 'r')
for name in hall_of_fame:
print str(count) + ".", name
print
count += 1
hall_of_fame.close()
except IOError:
print "No Human Has Ever Beat Me.. mwah-ha-ha-ha!\n"
choice = raw_input("Would you like to go first? (y or n): ")
if (choice == 'y' or choice == 'Y'):
users_turn = True
elif (choice == 'n' or choice == 'N'):
users_turn = False
else:
print 'invalid input'
while not winner(ttt_board) and (free_cells > 0):
display_board(ttt_board)
if users_turn:
make_user_move(ttt_board)
users_turn = not users_turn
else:
make_computer_move(ttt_board)
users_turn = not users_turn
free_cells -= 1
display_board(ttt_board)
if (winner(ttt_board) == 'X'):
print "You Won!"
print "Your name will now be added to the Hall of Fame!"
hall_of_fame = open("HallOfFame.txt", 'a')
name = raw_input("Enter your name: ")
hall_of_fame.write(name + '\n')
print "Your name has been added to the Hall of Fame!"
hall_of_fame.close()
print "\nGAME OVER"
elif (winner(ttt_board) == 'O'):
print "The Computer Won!"
print "\nGAME OVER"
else:
print "Stalemate!"
print "\nGAME OVER \n"
# start the game
main()

Categories

Resources