Missing 1 required positional argument board game - python-3.x

I am trying to create the GUI code for my connect four boardgame but error's keep on coming up that I don't know how to correct. Can anyone help? The error:
TypeError: init() missing 1 required positional argument: 'buttns_list'
Code:
def __init__(self):
self.mw = tkinter.Tk()
self.mw.title = ("Connect Four")
self.rows = 6
self.cols = 7
self.buttons_2d_list = []
for i in range (self.rows):
self.rows = ['']*self.cols
self.buttons_2d_list.append(self.rows)
self.gboard = ConnectFourBoard()
p1 = HumanPlayer("X")
p2 = ComputerPlayer("O", self.buttns_list)
self.players_1st = (p1, p2)
self.currnt_player_index = 0
self.winner = False
def clicked_btn(self, x, y):
p = self.players_1st[self.currnt_player_index]
button = self.buttons_2d_list[x][y]
if button["text"] == "":
button["text"] = p.get_player_symbol()
self.gboard.MakeMove(x, y, p.get_player_symbol())
winner = self.gboard.CheckForWin()
is_full = self.gboard.FullBoard()
if winner == True:
win_message = ("Player %s is the winner!" %p.get_player_symbol())
messagebox.showinfo("Winner Info", win_messge)
self.mw.destroy()
exit()
elif is_full == True:
messagebox.showinfo("Winner Info", "The game is a draw")
self.mw.destroy()
exit()
else:
pass
if self.currnt_player_index == 1:
self.currnt_player_index = 0
else:
self.currnt_player_index += 1
p = self.players_1st[self.currnt_player_index]
p.play()
import random
class ComputerPlayer(Player):
def __init__(self, letter, buttns_list):
Player.__init__(self, letter)
self.buttons_2d_list = buttns_list
def play(self):
pass

It's not clear to me from the rest of the code exactly what you should be passing here, but your init calls for a letter, which you do have, and a buttns_list, which you don't:
def __init__(self, letter, buttns_list):
So the error comes from this line:
p2 = ComputerPlayer("O")
Either:
1) Pass in a buttns_list if your ComputerPlayer class needs it
p2 = ComputerPlayer("O", self.buttons_2d_list)` # in GameGUI init
2) Get rid of it if this was added by mistake:
class ComputerPlayer(Player):
def __init__(self, letter):
Player.__init__(self, letter)

Related

How to find the shortest path

In the function of find_shortest_func, i think if now position isn't "T" which is also known as the terminal or exit, then i will try to find for direction and see if it is "T", if not, check if it is space and i can go there. Besides, tell the next state function now output and dic to tell the place where i visited. But some errors occur and I don't know why.
I think the problem may occur where I tried to deepcopy the output list
import copy
def set_symbol(symbol_name):
def set_symbol_decorator(func):
def wrapper(self, symbol):
setattr(self, symbol_name, symbol)
return wrapper
return set_symbol_decorator
class Maze:
space_symbol = " "
obstacle_symbol = "X"
path_symbol = "•"
output = []
dis = 0
def __init__(self, input_string):
self.maze = []
if input_string.endswith("txt"):
with open(input_string) as f:
count = 0
for line in f.readlines():
self.maze.append([])
for j in line:
if j != '\n':
self.maze[count].append(j)
count += 1
else:
count = 0
for i in input_string.split("\n"):
self.maze.append([])
for j in i:
self.maze[count].append(j)
count += 1
def __str__(self):
output_string = ""
for i in range(20):
for j in range(20):
output_string += self.maze[i][j]
output_string += "\n"
return output_string
#set_symbol("space_symbol")
def set_space_symbol(self, change):
pass
#set_symbol("obstacle_symbol")
def set_obstacle_symbol(self, change):
pass
#set_symbol("path_symbol")
def set_path_symbol(self, change):
pass
def find_shortest_func(self, position: tuple, d: dict, out: list, dis: int):
dic = copy.deepcopy(d)
output = copy.deepcopy(out)
dic[(position[0], position[1])] = 1
output.append((position[0], (position[1])))
dis += 1
if self.maze[position[0]][position[1]] != "T":
if position[0]+1 < 20 and self.maze[position[0]+1][position[1]] == self.space_symbol and (position[0]+1, position[1]) not in dic:
self.find_shortest_func(
(position[0]+1, position[1]), dic, output, dis)
if position[1]+1 < 20 and self.maze[position[0]][position[1]+1] == self.space_symbol and (position[0], position[1]+1) not in dic:
self.find_shortest_func(
(position[0], position[1]+1), dic, output, dis)
if position[0]-1 >= 0 and self.maze[position[0]-1][position[1]] == self.space_symbol and (position[0]-1, position[1]) not in dic:
self.find_shortest_func(
(position[0]-1, position[1]), dic, output, dis)
if position[1]-1 >= 0 and self.maze[position[0]][position[1]-1] == self.space_symbol and (position[0], position[1]-1) not in dic:
self.find_shortest_func(
(position[0], position[1]-1), dic, output, dis)
if self.maze[position[0]][position[1]] == "T":
if dis < self.dis:
self.output = copy.deepcopy(output)
self.dis = dis
return
def find_shortest_path(self):
d = dict()
output = []
dis = -1
self.find_shortest_func((1, 0), d, output, dis)
return self.output, self.dis

Python3 syntax in Lowest common ancestor

Classic problem of LCA in BT: Given a Binary Tree find the lowest common ancestor.
I found a Python2 solution but don't know how to fix it in Python3.
# This is Python2, but having error in Python3 such that
# parent += node if all(subs) else max(subs),
# TypeError: '>' not supported between instances of 'NoneType' and 'NoneType'`
# lca.py
class Solution:
def lowestCommonAncestor(self, root, p, q):
answer = []
stack = [[root, answer]]
while stack:
top = stack.pop()
(node, parent), subs = top[:2], top[2:]
if node in (None, p, q):
parent += node,
elif not subs:
stack += top, [node.right, top], [node.left, top]
else:
parent += node if all(subs) else max(subs), # this is the problem in Python3
return answer[0]
s = Solution()
root = tree.create_tree3()
p = tree.find(root, 6)
q = tree.find(root, 1)
print(f'p = {p}, q = {q}')
lca = s.lowestCommonAncestor(root, p, q)
print(f"lca = {lca}")
# tree.py
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def __repr__(self):
return str(self.val)
def find(root, val):
if root is None:
return None
if root.val == val:
return root
left = find(root.left, val)
right = find(root.right, val)
if left is not None:
return left
else:
return right
"""
3
5 1
6 2 0 8
7 4
"""
def create_tree3():
n3 = TreeNode(3)
n5 = TreeNode(5)
n1 = TreeNode(1)
n6 = TreeNode(6)
n2 = TreeNode(2)
n0 = TreeNode(0)
n8 = TreeNode(8)
n7 = TreeNode(7)
n4 = TreeNode(4)
n3.left, n3.right = n5, n1
n5.left, n5.right = n6, n2
n1.left, n1.right = n0, n8
n2.left, n2.right = n7, n4
return n3
I'm a newbie of Python3 and trying to fix this error in Python3, and I'm trying below, but not working.
class Solution:
def lowestCommonAncestor(self, root, p, q):
answer = []
stack = [[root, answer]]
while stack:
top = stack.pop()
(node, parent), subs = top[:2], top[2:]
if node in (None, p, q):
parent += node,
elif not subs:
stack += top, [node.right, top], [node.left, top]
else:
if subs[0] and subs[1]:
parent += node
else: # not sure how to fix the below part which is not working either
if subs[0] and not subs[1]:
parent += subs[0]
elif not subs[0] and subs[1]:
parent += subs[1]
elif not subs[0] and not subs[1]:
parent += None
return answer[0]

Switching between classes and passing results

I am trying to add different PlugLead's to the PlugBoard and extract the combination. In the first class I am extracting the one letter from the list should they match or return the input. e.g.
lead = PlugLead("AG")
assert(lead.encode("A") == "G")
class PlugLead:
def __init__(self, c):
self.c = c
def encode(self, l):
c0 = self.c[0]
c1 = self.c[1]
if len(l) == 1 and c0 == l:
return c1
elif len(l) == 1 and c1 == l:
return c0
else:
return l
class Plugboard:
def __init__(self):
self.__head = 0
self.leads = []
self.c = []
def add(self, item):
if self.__head >= 10:
print("leads already got 10 items")
elif item in self.leads:
print(f"leads already have this item: {item}")
else:
self.leads.append(item)
self.__head += 1
return self.leads
def encode(self)
lines = plugboard.leads
for word in lines:
word = word.split(",")
PlugLead.encode(word)
In the second class I am trying to add multiple combinations and then at the end pass the one letter to see what its match is in the Class PlugLead however am not able to switch between the two. In the class PlugLead I have a add function that allows the different combinations to be added up to 10 and then I would like to encode from this list the combination of the pairs. e.g.
plugboard = Plugboard()
plugboard.add(PlugLead("SZ"))
plugboard.add(PlugLead("GT"))
plugboard.add(PlugLead("DV"))
plugboard.add(PlugLead("KU"))
assert(plugboard.encode("K") == "U")
assert(plugboard.encode("A") == "A")
if you want to use PlugLead("{balabala}"),you need use __new__ to return a dict when you create an instance, not __init__.
you want a key-value pair in Plugboard, it should be a dict not list
fix some other typo and bugs.
code:
class PlugLead:
def __new__(self, c):
return {c[0]:c[1]}
class Plugboard:
def __init__(self):
self.__head = 0
self.leads = {}
def add(self, item):
if self.__head >= 10:
print("leads already got 10 items")
elif list(item.keys())[0] in self.leads.keys():
print(f"leads already have this item: {item}")
else:
self.leads.update(item)
self.__head += 1
return self.leads
def encode(self,key):
if key in self.leads:
return self.leads[key]
elif key in self.leads.values():
return list(self.leads.keys())[list(self.leads.values()).index(key)]
return key
plugboard = Plugboard()
plugboard.add(PlugLead("SZ"))
plugboard.add(PlugLead("GT"))
plugboard.add(PlugLead("DV"))
plugboard.add(PlugLead("KU"))
plugboard.add(PlugLead("KU"))
assert(plugboard.encode("K") == "U")
assert(plugboard.encode("U") == "K")
assert(plugboard.encode("A") == "A")
print(plugboard.encode("K"))
print(plugboard.encode("U"))
print(plugboard.encode("A"))
result:
leads already have this item: {'K': 'U'}
U
K
A

Python - 'int' object is not callable

I'm writing a singly linked list that counts the number of words that get imported from a test file.
I initialized count inside of my class.
I defined the print function, that prints out each of the nodes, after they are sorted.
I defined a count class to iterate through the list and count up all the occurences of a word fed to it.
I want to pass in every node into count to count how many times it appears in my text file. When I try to do that I end up with 'int' object is not callable. Here is my code
class Linked_List:
def __init__(self):
self.head = None
self.count = 1
def print(self):
p = self.head
head = Linked_List_node(p.data)
while p is not None:
print(p.data, '-', self.count(p.data)) # This is where the error appears
p = p.next
def count(self, x):
# loop thru list for all x, if find x add 1 to count. Assign final count to that word.
with open('cleaned_test.txt', 'r') as f:
for line in f:
for word in line.split():
if word == x:
self.count += 1
def insert(self, x):
""""""
p = self.head
q = None
done = False
while not done:
if self.head == x:
done = True
elif p == None:
head = Linked_List_node(x)
q.next = head
done = True
elif x == p.data:
#head = Linked_List_node(x)
#head.counter += 1
done = True
elif x < p.data:
if self.head == p:
head = Linked_List_node(x)
head.next = p
self.head = head
done = True
else:
head = Linked_List_node(x)
head.next = p
q.next = head
done = True
q = p
if p is not None:
p = p.next
class Linked_List_node:
def __init__(self, value):
self.data = value
self.next = None
Relevant part from your code is:
class Linked_List:
def __init__(self):
# ...
self.count = 1
def count(self, x):
# ...
The self.count = 1 assignment overwrites the value of self.count for every Linked_List object that's created, so it refers to 1 instead of the method you defined on the class. Rename either the variable or the function.

How can I get tuple values (from a class) in my main function?

I am using multiprocesssing in Python 3.5.
#Multiprocessing
def main():
p1 = multiprocessing.Process(name="p1", target=datac)
p2 = multiprocessing.Process(name="p2", target=test)
p2.start()
p1.start()
if __name__ == "__main__":
main()
There are two processes=>
1.test
2.datac
Test:
def test():
#a=0
while 1:
#if 'gaze_point' in gaze_data_callback(gaze_data):
# data = gaze_data_callback['gaze_point']
# if s == 0:
# x = data[0] * 1920
# y = data[1] * 1080
# return [x, y]
#a+=1
for x in range(0, 10):
print("We're on time %d" % (x))
print('Waiting..')
#time.sleep(5)
Datac:
def datac():
while 1:
tmp = eye.__new__(eye)
tmp.__init__()
print(tmp)
This is the class:
class eye(object):
def gaze_data_callback(gaze_data):
left_3d = gaze_data['left_gaze_point_in_user_coordinate_system']
right_3d = gaze_data['right_gaze_point_in_user_coordinate_system']
#Get the gaze point of both eyes
gaze_point = ((left_3d), (right_3d))
gaze_point = tuple(mean(gaze_point, axis=0))
print("3d gaze:",gaze_point)
my_eyetracker.subscribe_to(tr.EYETRACKER_GAZE_DATA, gaze_data_callback, as_dictionary=True)
time.sleep(5)
my_eyetracker.unsubscribe_from(tr.EYETRACKER_GAZE_DATA, gaze_data_callback)
return (gaze_point)
I want to print the gaze point but it is not being printed. I am getting the object location

Resources