Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Tk_connect4.py
- # ZZZ might soon make quite a different game from this basic code
- from Tkinter import *
- import random
- main = Tk()
- c = Canvas(main, width=400, height=500)
- c.pack()
- for z in range(5):
- z*=100
- c.create_line(z+2, 2, z+2, 400+2)
- c.create_line(2, z+2, 400+2, z+2)
- grid = [
- "0", "1", "2", "3",
- "4", "5", "6", "7",
- "8", "9", "10", "11",
- "12", "13", "14", "15"
- ]
- # Klikk prosedyre
- def click(event):
- across = int(c.canvasx(event.x) / 100)
- down = int(c.canvasy(event.y) / 100)
- square = across + (down * 4)
- print across, down
- if grid[square] == "X" or grid[square] == "O":
- return
- if winner(grid):
- return
- grid[square] = "O"
- draw_shape("O", across, down)
- if winner(grid):
- return
- play_move()
- def o4xy(x, y):
- return x * 100 + 2, y * 100 + 2, (x+1) * 100 + 2, (y+1) * 100 + 2
- def draw_shape(shape, across, down):
- if shape == "O":
- c.create_oval(o4xy(across, down))
- else:
- c.create_line(o4xy(across, down))
- c.create_line(across * 100 + 2, (down+1) * 100 + 2,
- (across+1) * 100 + 2, down * 100 + 2)
- # Dette gjer at datamaskinen faktisk har ein hjerne, og ikkje bare velger tilfeldige ruter
- def winner(grid):
- for across in range(4):
- row = across * 4
- line = grid[row] + grid[row+1] + grid[row+2] + grid[row+3]
- if line == "XXXX" or line == "OOOO":
- return True
- for down in range(4):
- line = grid[down] + grid[down+4] + grid[down+8] + grid[down+12]
- if line == "XXXX" or line == "OOOO":
- return True
- line = grid[0] + grid[5] + grid[10] + grid[15]
- if line == "XXXX" or line == "OOOO":
- return True
- line = grid[3] + grid[6] + grid[9] + grid[12]
- if line == "XXXX" or line == "OOOO":
- return True
- # Finner ledige ruter
- def free_squares():
- output = []
- for position, square in enumerate(grid):
- if square != "X" and square != "O":
- output.append(position)
- return output
- def play_move():
- moves = free_squares()
- square = random.choice(moves)
- # Hvis et blokkerende trekk eksisterer kjører den det
- for possible in moves:
- new_grid = list(grid)
- new_grid[possible] = "O"
- if winner(new_grid):
- square = possible
- break
- # Hvis et vinnende trekk eksisterer kjører den det
- for possible in moves:
- new_grid = list(grid)
- new_grid[possible] = "X"
- if winner(new_grid):
- square = possible
- break
- down = square // 4
- across = square % 4
- grid[square] = "X"
- draw_shape("X", across, down)
- c.bind("<Double-Button-1>", click)
- mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement