This is my first time coding. I'm doing it as ab elective module. I have to program an ai_player to go from playing randomly to winning and I'm stuck. Any advice would be appreciated. The game is Connect 4. i keep getting "object has no attribute" error.
import random
import time
def board():
for i in range(0, 8, 1):
for j in range(0, 10, 1):
board[i][j] = 0
return board
def move(board, valid_move):
start_time = time.time()
x = 0
while x == 0:
i = range(7, -1, -1)
j = range(0, 10, 1)
first_move = board[i][j]
board[7][4] = 1
if board[i-1][j] == 0: #above
first_move = [i, j]
x = 1
print " valid above"
return j
elif (board[i][j+1] == 0 and (i <= 7 and j <= 9)) or (board[i-1][j+1] == 0 and (i <= 7 and j <= 9)) or (board[i-1][j+1] == 0 and (i <= 7 and j <= 9)): #right
first_move = [i, (j+1)]
x = 1
print " valid right"
return (j+1)
elif board[i][j-1] == 0 or board[i-1][j-1] == 0 or board[i-1][j-1] == 0: #left
first_move = [i, (j-1)]
x = 1
print " valid left"
return (j-1)
else:
r = random.randint(0, 7)
c = random.randint(0, 9)
first_move = [r, c]
x = 1
print " random move"
return c
end_time = time.time() - start_time
print end_time
return first_move
File "F:/5. Fifth year/1st Semester/MPR 213 2016/Project 2016/attempts.py", line 20, in board
board[i][j] = 0
TypeError: 'function' object has no attribute '__getitem__'
It looks like you're trying to create a multidimensional list called board. This is not how you do that though, what you've actually done is created a function called board, and then you try to index that function, which fails since it's not a list.
To create board, use something like
board = [[0] * 10 for i in range(0, 8)]
This is my code and when i try to run it and use it by entering numbers into the entry fields, an attribute error occurs when i try to call on the entry variable. This is the message that appears:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1486, in call
return self.func(*args)
File "F:\HomeWork\Yr13\Extended Project\Notepad++\Python27\Programs\GUI{c} menu+check+gen+Nth.py", line 224, in OnGenButtonClick
n= str(Prime_Generation(Prime_Gen.entryVariable5.get(),Prime_Gen.entryVariable6.get()))
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1845, in getattr
return getattr(self.tk, attr)
AttributeError: entryVariable5
any help would be greatly appreciated.
i have stuck on this problem for three days and have tried getting around the problem by using different functions and names and the error still occurs
import Tkinter
from Tkinter import *
import math
def SoS(limit):
numbers = range(3, limit+1, 2)
half = (limit)//2
initial = 4
for step in xrange(3, limit+1, 2):
for i in xrange(initial, half, step):
numbers[i-1] = 0
initial += 2*(step+1)
if initial > half:
plist = [2] + filter(None, numbers)
return plist
break
def S(m):
sieve = [True] * m
for i in xrange(3,(int(m**0.5)+1),2):
if sieve[i]:
sieve[i*i::2*i]=[False]*((m-i*i-1)/(2*i)+1)
plist = [2] + [i for i in xrange(3,m,2) if sieve[i]]
return plist
def OTS(n):
n, correction = n-n%6+6, 2-(n%6>1)
sieve = [True] * (n/3)
for i in xrange(1,(int(n**0.5)/3)+1):
if sieve[i]:
k=3*i+1|1
sieve[ k*k/3 ::2*k] = [False] * ((n/6-k*k/6-1)/k+1)
sieve[k*(k-2*(i&1)+4)/3::2*k] = [False] * ((n/6-k*(k-2*(i&1)+4)/6-1)/k+1)
plist = [2,3] + [3*i+1|1 for i in xrange(1,n/3-correction) if sieve[i]]
return plist
def is_prime(num):
if num <= 3:
if num <= 1:
return False
return True
if not num % 2 or not num % 3:
return False
for i in xrange(5, int(num ** 0.5) + 1, 6):
if not num % i or not num % (i + 2):
return False
return True
def is_prime_multiple(Lower,Upper):
NumberList = dict()
if Lower%2 == 1:
for i in xrange(Lower, Upper,2):
NumberList[i] = is_prime(i)
else:
for i in xrange(Lower-1,Upper,2):
NumberList[i] = is_prime(i)
NumberList[1] = False
return [i for i in NumberList if NumberList[i] == True]
def Prime_Generation(L,U):
Lower = int(L)
Upper = int(U)
if Lower == 1:
if Upper < 92:
print SoS(Upper)
if Upper >= 92 and Upper < 2250:
print S(Upper)
if Upper >= 2250 :
print OTS(Upper)
else:
print sorted(is_prime_multiple(Lower,Upper))
def factors(n):
f = 3
fs = []
while n % 2 == 0:
fs.append(2)
n /= 2
while f*f <= n:
while n % f == 0:
fs.append(f)
n /= f
f += 2
if n > 1:
fs.append(n)
return fs
def Prime_Checker(N):
NStr = str(N)
N = int(N)
Nfs = factors(N)
for i in Nfs:
if i != N:
NfsStr = str(Nfs).strip('[]')
resultb = [NStr,' is not a prime. The prime factors of ',NStr,' are ',NfsStr]
return resultb.join()
else:
return N,' is a prime. The prime factors of ',N ,' are ',N
def PrimeFinderLamda(n,limit):
nums = range(3,limit,2)
for i in range(2, int(limit**0.5)):
nums = filter(lambda x: x == i or x % i, nums)
return [2]+nums
def NthPrime(N):
N = int(N)
Lower = 1
limit = N*N
if N == 1:
return 2
else:
return PrimeFinderLamda(N,limit)[N-1]
class Prime_app_tk(Tkinter.Tk):
def __init__(self,parent):
Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def Prime_Gen_Win(self):
Prime_Gen = Toplevel()
Prime_Gen.grid()
Prime_Gen.labelVariable3 = StringVar()
Title_label2 = Label(Prime_Gen,textvariable=Prime_Gen.labelVariable3,
relief = RAISED,fg="black",bg="white"
,font = "Arial")
Title_label2.grid(column=0,row=0,columnspan=4)
Prime_Gen.labelVariable3.set(u"Please enter the upper and lower limits of the prime number generation")
Prime_Gen.labelVariable4 = StringVar()
SubTitle_label1 = Label(Prime_Gen,textvariable=Prime_Gen.labelVariable4,fg="black",bg="white")
SubTitle_label1.grid(column=0,row=1,columnspan=4)
Prime_Gen.labelVariable4.set(u"(Please enter values no greater than 10 million)")
Prime_Gen.entryVariable5 = StringVar()
Prime_Gen.entry = Entry(Prime_Gen,textvariable=Prime_Gen.entryVariable5)
Prime_Gen.entry.grid(column=0,row=4)
Prime_Gen.entryVariable5.set(u"Lower.")
Prime_Gen.entryVariable6 = StringVar()
Prime_Gen.entry = Entry(Prime_Gen,textvariable=Prime_Gen.entryVariable6)
Prime_Gen.entry.grid(column=0,row=5)
Prime_Gen.entryVariable6.set(u"Upper.")
Genbutton = Button(Prime_Gen,text=u"Generate !",command=self.OnGenButtonClick #placing and aesthetics of button
,bg="yellow",relief=RAISED,padx=10,pady=10
,activebackground="red",activeforeground="white")
Genbutton.grid(column=0,row=6)
scrollbar = Scrollbar(Prime_Gen)
scrollbar.grid(column=1,row=8,sticky="ns")
Prime_Gen.Result_label = Text(Prime_Gen, yscrollcommand=scrollbar.set
,fg="blue",bg="white",wrap=WORD
,width=100,relief = SUNKEN)
Prime_Gen.Result_label.grid(column=0,row=8,columnspan=2)
scrollbar.config(command=Prime_Gen.Result_label.yview)
Prime_Gen.labelVariable = StringVar()
SubTitle_label = Label(Prime_Gen,textvariable=Prime_Gen.labelVariable,fg="black",bg="white")
SubTitle_label.grid(column=0,row=9,columnspan=4)
Prime_Gen.labelVariable.set(u"To see full list please click on the results\n and use the up and down arrows to scroll through the list")
Prime_Gen.grid_columnconfigure(0,weight=1)
Prime_Gen.resizable(True,True)
Prime_Gen.update()
Prime_Gen.geometry(Prime_Gen.geometry())
Prime_Gen.entry.focus_set()
Prime_Gen.entry.selection_range(0, Tkinter.END)
def OnGenButtonClick(Prime_Gen):
n= str(Prime_Generation(Prime_Gen.entryVariable5.get(),Prime_Gen.entryVariable6.get()))
Prime_Gen.Result_label.insert(END,"\nPrimes Found\n")
Prime_Gen.Result_label.insert(END,n)
Prime_Gen.entry.focus_set()
Prime_Gen.entry.selection_range(0, Tkinter.END)
def Prime_Check_Win(self):
Prime_Check = Toplevel()
Prime_Check.grid()
Prime_Check.labelVariable8 = StringVar()
Title_label3 = Label(Prime_Check,textvariable=Prime_Check.labelVariable8,
relief = RAISED,fg="black",bg="white"
,font = "Arial")
Title_label3.grid(column=0,row=0,columnspan=4)
Prime_Check.labelVariable8.set(u"Please enter a Number to be checked for primality")
Prime_Check.labelVariable9 = StringVar()
SubTitle_label3 = Label(Prime_Check,textvariable=Prime_Check.labelVariable9,fg="black",bg="white")
SubTitle_label3.grid(column=0,row=1,columnspan=4)
Prime_Check.labelVariable9.set(u"(Please enter values no greater than 10 million)")
Prime_Check.entryVariable = StringVar()
Prime_Check.entry = Entry(Prime_Check,textvariable=Prime_Check.entryVariable)
Prime_Check.entry.grid(column=0,row=2)
Prime_Check.entryVariable.set(u"Enter Number here.")
Checkbutton = Button(Prime_Check,text=u"Check !",command=self.OnCheckButtonClick
,bg="blue",fg="white",relief=RAISED,padx=10,pady=10
,activebackground="red",activeforeground="white")
Checkbutton.grid(column=0,row=4)
Prime_Check.labelVariable10 = StringVar()
Result_label2 = Message(Prime_Check,textvariable=Prime_Check.labelVariable10
,anchor="w",fg="blue",bg="white"
,width=500,relief = SUNKEN,padx=3,pady=3)
Result_label2.grid(column=0,row=5,columnspan=2,rowspan=100)
Prime_Check.labelVariable10.set(u"Hello")
Prime_Check.grid_columnconfigure(0,weight=1)
Prime_Check.resizable(True,False)
Prime_Check.update()
Prime_Check.geometry(Prime_Check.geometry())
Prime_Check.entry.focus_set()
Prime_Check.entry.selection_range(0, Tkinter.END)
def OnCheckButtonClick(Prime_Check):
Prime_Check.labelVariable10.set(Prime_Checker(Prime_Check.entryVariable.get())) #Had to call on prime gen and display results
Prime_Check.entry.focus_set()
Prime_Check.entry.selection_range(0, Tkinter.END)
def Nth_Prime_Win(self):
Nth_Prime = Toplevel()
Nth_Prime.grid()
Nth_Prime.labelVariable12 = StringVar()
Title_label = Label(Nth_Prime,textvariable=Nth_Prime.labelVariable12,
relief = RAISED,fg="black",bg="white"
,font = "Arial")
Title_label.grid(column=0,row=0,columnspan=4)
Nth_Prime.labelVariable12.set(u"Please enter the Nth prime you would like to find")
Nth_Prime.labelVariable13 = StringVar()
SubTitle_label = Label(Nth_Prime,textvariable=Nth_Prime.labelVariable13,fg="black",bg="white")
SubTitle_label.grid(column=0,row=1,columnspan=4)
Nth_Prime.labelVariable13.set(u"(Please enter values no greater than 664579")
Nth_Prime.entryVariable = StringVar()
Nth_Prime.entry = Entry(Nth_Prime,textvariable=Nth_Prime.entryVariable)
Nth_Prime.entry.grid(column=0,row=4)
Nth_Prime.entryVariable.set(u"Enter Number here.")
Genbutton = Button(Nth_Prime,text=u"Generate !",command=self.OnButtonNthClick
,bg="green",relief=RAISED,padx=10,pady=10
,activebackground="red",activeforeground="white")
Genbutton.grid(column=0,row=5)
Nth_Prime.labelVariable14 = StringVar()
Result_label = Message(Nth_Prime,textvariable=Nth_Prime.labelVariable14
,anchor="w",fg="blue",bg="white"
,width=1000,relief = SUNKEN,justify=LEFT,padx=3,pady=3)
Result_label.grid(column=0,row=6,columnspan=2,rowspan=100)
Nth_Prime.labelVariable14.set(u"Hello")
Nth_Prime.grid_columnconfigure(0,weight=1)
Nth_Prime.resizable(False,False)
Nth_Prime.update()
Nth_Prime.geometry(Nth_Prime.geometry())
Nth_Prime.entry.focus_set()
Nth_Prime.entry.selection_range(0, Tkinter.END)
def OnButtonNthClick(Nth_Prime):
Nth_Prime.labelVariable14.set(NthPrime(Nth_Prime.entryVariable.get()))
Nth_Prime.entry.focus_set()
Nth_Prime.entry.selection_range(0, Tkinter.END)
def initialize(self):
self.grid()
self.labelVariable1 = StringVar()
Title_label1 = Label(self,textvariable=self.labelVariable1,
relief = RAISED,fg="black",bg="white"
,font = "Arial")
Title_label1.grid(column=0,row=0,columnspan=4)
self.labelVariable1.set(u"Welcome to the Prime Program")
self.labelVariable2 = StringVar()
SubTitle_label = Label(self,textvariable=self.labelVariable2,fg="black",bg="white")
SubTitle_label.grid(column=0,row=1,columnspan=4)
self.labelVariable2.set(u"(Please select the function you would like to use)")
PrimeGenbutton = Button(self,text=u"Find Primes between 2 limits !",command=self.Prime_Gen_Win
,bg="yellow",relief=RAISED,padx=10,pady=10
,activebackground="red",activeforeground="white")
PrimeGenbutton.grid(column=0,row=3)
PrimeCheckbutton = Button(self,text=u"Check if a number is prime !",command=self.Prime_Check_Win
,bg="blue",fg="white",relief=RAISED,padx=14,pady=10
,activebackground="red",activeforeground="white")
PrimeCheckbutton.grid(column=0,row=4)
NthPrimebutton = Button(self,text=u"Find the Nth prime !",command=self.Nth_Prime_Win
,bg="green",relief=RAISED,padx=35,pady=10
,activebackground="red",activeforeground="white")
NthPrimebutton.grid(column=0,row=5)
self.grid_columnconfigure(0,weight=1)
self.resizable(False,False)
self.update()
self.geometry(self.geometry())
if __name__ == "__main__":
app = Prime_app_tk(None)
app.title('Prime Program')
app.mainloop()
There's no quick fix for your code. It attempts to be object-oriented, but is doing so incorrectly. You need to properly define your methods, and should also adhere to PEP8 naming conventions -- specifically, methods and functions should start with a lowercase, and classes should start with an uppercase. Because you don't follow PEP8, and because of the odd way you use Prime_Gen to mean different things at different times, your code is incredibly hard to understand.
The crux of the problem is that inside OnGenButtonClick, Prime_Gen is not what you think it is. It is an instance of Prime_app_tk rather than the value that you set the local variable Prime_Gen to in Prime_Gen_Win. Thus, any attributes you assigned to the original Prime_Gen don't exist in this other Prime_Gen.
The reason is that the button is defined like this:
Genbutton = Button(..., command=self.OnGenButtonClick, ...)
In this context, self is the instance of Prime_app_tk, so that becomes the parameter passed to OnGenButtonClick. Inside that function you call the parameter Prime_Gen, in spite of the universal convention to name it self. This causes confusion in your code, because you also have a local variable named Prime_Gen in the code that creates the toplevel window.