2016-07-22 2 views
0

난 (빈 셀에 블랙 셀 백혈구 값 1, 2,캔버스 위젯을 클릭하여 배열 값과 tkinter 캔버스의 변경 사항을 조정하는 방법은 무엇입니까?

0을 가짐) 및가에 제 육각형의 좌표를 2 차원 배열을 취득 헥스 게임 인터페이스를 개발 스크린을 입력으로 사용하여 첫 번째

포인트를 기준으로 16 진수 테이블을 그립니다.

는 나는 (클릭 된 셀에 흰색 또는 검은 색의

돌을 재생을 의미) 1 또는 2 셀의 값을 변경하는 방식에서 마우스 왼쪽 버튼 클릭에 대한 작업을 트리거합니다. 셀을 클릭하여 배열의 프린트를 얻으면

보드의 클릭 된 셀의 값은 변경되지만 클릭 된 육각형의 색은 변경되지 않습니다.

여기는 클릭 트리거에서 그래픽이 변경되지 않는 한 올바르게 작동하는 정확한 코드입니다.

from tkinter import * 
class gui: 
    """ 
    This class is built to let the user have a better interaction with 
    game. 
    inputs => 
    canvas = Canvas(root) 
    board = board is the array of gamestate class which shows the game board. 
    start_points = This entry indicates an array of points which is the top 
    left coordinate of item of the graphical interface. 
    """ 
    def __init__(self, root, start_points, board): 
     self.canvas = Canvas(root, width=900, height=768) 
     self.board = board 
     self.start = [start_points[0], start_points[1], start_points[2], 
         start_points[3], start_points[4], start_points[5]] 
     self.temp = [] 
     for i in self.start: 
      self.temp.append(i) 
     self.initial_offset = 20 # Offset for each row and first item 
     self.hex_x = 40   # Offset for each hexagon in each row 
     self.hex_y = 40   # Offset from top of screen 
     self.hex_board = [] 
     self.array_to_hex(self.board) 
     self.bind() 
     self.canvas.pack(anchor='nw') 

    def hexagon(self, points, color): 
     """ 
     Creates a hexagon by getting a list of points and their assigned colors 
     according to the game board 
     """ 
     if color is 0: 
      hx = self.canvas.create_polygon(points[0], points[1], points[2], 
              points[3], points[4], points[5], 
             fill='#fe8b03', outline='black', width=2) 
     elif color is 1: 
      hx = self.canvas.create_polygon(points[0], points[1], points[2], 
              points[3], points[4], points[5], 
             fill='white', outline='black', width=2) 
     else: 
      hx = self.canvas.create_polygon(points[0], points[1], points[2], 
              points[3], points[4], points[5], 
             fill='#3e3f3a', outline='black', width=2) 
     return hx 

    def genrow(self, points, colors): 
     """ 
     By getting a list of points as the starting point of each row and a list of 
     colors as the dedicated color for each item in row, it generates a row of 
     hexagons by calling hexagon functions multiple times. 
     """ 
     row = [] 
     temp_array = [] 
     for i in range(len(colors)): 
      for point in points: 
       temp_points_x = point[0] + self.hex_x * i 
      temp_points_y = point[1] 
      temp_array.append([temp_points_x, temp_points_y]) 
     if colors[i] is 0: 
      hx = self.hexagon(temp_array, 0) 
     elif colors[i] is 1: 
      hx = self.hexagon(temp_array, 1) 
     else: 
      hx = self.hexagon(temp_array, 2) 
     row.append(hx) 
     temp_array = [] 
    return row 

def array_to_hex(self, array): 
    """ 
    Simply gets the gameboard and generates the hexagons by their dedicated colors. 
    """ 
    for i in range(len(array)): 
     for point in self.temp: 
      point[0] += self.hex_x 
      point[1] += self.hex_y 
     for point in self.temp: 
      point[0] -= self.initial_offset 
     row = self.genrow(self.temp, self.board[i]) 
     self.temp.clear() 
     for k in self.start: 
      self.temp.append(k) 
     self.hex_board.append(row) 

    def bind(self): 
     """ 
     Binding triggers for the actions defined in the class. 
     """ 
     self.canvas.bind('<Motion>', self.mouse_motion) 
     self.canvas.bind('<1>', self.mouse_click) 

    def mouse_motion(self, event): 
     """ 
     Simply implements a hovering action for each item 
     """ 
     if self.canvas.find_withtag(CURRENT): 
      current_color = self.canvas.itemcget(CURRENT, 'fill') 
      self.canvas.itemconfig(CURRENT, fill="cyan") 
      self.canvas.update_idletasks() 
      self.canvas.after(150) 
      self.canvas.itemconfig(CURRENT, fill=current_color) 

    def mouse_click(self, event): 
     """ 
     This function changes the color of item (depending on the player turns) 
     to assigned color 
     """ 
     x, y = event.x, event.y 
     idd = self.canvas.find_overlapping(x, y, x, y) 
     idd = list(idd) 
     if len(idd) is not 0: 
      p = idd[0] 
      index = [[ix, iy] for ix, 
      row in enumerate(self.hex_board) for iy, 
      i in enumerate(row) if i == p][0] 
      self.board[index[0]][index[1]] = 1 
      for i in self.board: 
       print(i) 
      print('\n') 

row_item_offset = 40 
x_offset = 20 
y_offset = 40 
points1 = [[25, 10], [45, 25], [45, 50], [25, 65], [5, 50], [5, 25]] 
test_array = [[1, 0, 0, 0, 0, 0], 
       [0, 0, 2, 0, 0, 0], 
       [1, 1, 1, 2, 1, 2], 
       [0, 0, 0, 2, 0, 2], 
       [0, 1, 0, 0, 1, 2], 
       [0, 0, 0, 2, 0, 0]] 
root = Tk() 
hexagons = gui(root, points1, test_array) 
root.mainloop() 

나는 종류의 전체 항목을 새로 고치거나 전체 위젯을 삭제하는 방법을 잊지 사용하고 다시 재 포장에 대해 생각했다,하지만 난

그것을 구현하는 방법을 모르겠어요. mouse_click_trigger 메서드를 수정해야한다고 생각합니다. 샘플 코드로 누구나 제안 할 수 있습니까? 감사합니다.

답변

0

는 정말 이것이 당신이 찾고있는 무슨 희망 :

from tkinter import * 
root = Tk() 
root.geometry("600x600-400+50") 
root.title("Game") 

class App: 
    def __init__(self, master): 
     self.master = master 

     self.rbvar = IntVar() 

     self.stonerb = Radiobutton(self.master, text="Stone", 
            variable=self.rbvar, value=1, command=self.figurefunc) 
     self.stonerb.pack() 

     self.blackrb = Radiobutton(self.master, text="Black", 
            variable=self.rbvar, value=2, command=self.figurefunc) 
     self.blackrb.pack() 

     self.board = Canvas(self.master, bg='#b35900', width=500, height=500) 
     self.board.pack() 

     self.figure = self.board.create_polygon(0,0, 0,0, 0,0, 0,0, 0,0, 0,0) 

     self.stoneCoords = 60,200, 100,200, 120,230, 100,260, 60,260, 40,230 
     self.blackCoords = 440,200, 400,200, 380,230, 400,260, 440,260, 460,230 

    def figurefunc(self): 
     if self.rbvar.get() == 1: 
      self.board.coords(self.figure, self.stoneCoords) 
      self.board.itemconfig(self.figure, fill='#f2f2f2') 
     else: 
      self.board.coords(self.figure, self.blackCoords) 
      self.board.itemconfig(self.figure, fill='black') 


myapp = App(root) 

휴!

+0

좋습니다. 먼저 팁 주셔서 감사 드리며, 열심히 도와 드리겠습니다. 그러나 제가 의미하는 바는 이것입니다 : 육각형을 클릭합니다. self.board에서 해당 항목의 값을 변경 한 다음 새 배열을 기반으로 전체 보드를 다시 만듭니다. 클릭 된 항목이 흰색 또는 검은 색으로 바뀝니다. –

+0

self.board 배열은 프로그램의 다른 부분에서 self.board 배열을 사용하기 때문에이 방법으로 변경해야합니다. –

+0

이 방법을 통해, 당신은 언제든지 세상을 파괴하고 재창조 할 수 있습니다. 그러나 각 스크린을 하나의 프레임으로 만들 수 있기 때문에 부모 윈도우를 파괴하지 않고 할 수 있습니다. –

관련 문제