写一个有窗口的五子棋程序,用python
时间: 2024-05-06 20:20:30 浏览: 5
抱歉,作为AI语言模型,我无法提供图形界面的编程代码。不过,你可以使用Python的Tkinter或PyQt等图形界面库来创建有窗口的五子棋程序。以下是一个使用Tkinter的简单五子棋游戏代码示例,仅供参考:
```
import tkinter as tk
from tkinter import messagebox
class Gobang(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.grid()
self.create_widgets()
self.board = [[' ' for i in range(15)] for j in range(15)]
self.color = 'black'
self.over = False
def create_widgets(self):
self.canvas = tk.Canvas(self, width=600, height=600, bg='#F7D6C4')
self.canvas.grid(row=0, column=0, rowspan=16, columnspan=16)
for i in range(15):
self.canvas.create_line(50, 50+i*40, 570, 50+i*40, width=2)
self.canvas.create_line(50+i*40, 50, 50+i*40, 570, width=2)
self.canvas.bind('<Button-1>', self.click_event)
self.reset_button = tk.Button(self, text='重新开始', command=self.reset_game)
self.reset_button.grid(row=16, column=0)
def click_event(self, event):
if self.over:
return
x, y = event.x, event.y
if x < 30 or x > 570 or y < 30 or y > 570:
return
row, col = (y-30)//40, (x-30)//40
if self.board[row][col] == ' ':
self.board[row][col] = self.color
self.draw_piece(row, col)
if self.check_win(row, col):
self.over = True
messagebox.showinfo('游戏结束', '恭喜{}赢了!'.format(self.color))
else:
self.color = 'white' if self.color == 'black' else 'black'
def draw_piece(self, row, col):
x, y = col*40+30, row*40+30
if self.color == 'black':
self.canvas.create_oval(x-18, y-18, x+18, y+18, fill='black')
else:
self.canvas.create_oval(x-18, y-18, x+18, y+18, fill='white')
def check_win(self, row, col):
if self.check_row(row) or self.check_col(col) or self.check_diag(row, col):
return True
return False
def check_row(self, row):
count = 0
for col in range(15):
if self.board[row][col] == self.color:
count += 1
if count == 5:
return True
else:
count = 0
return False
def check_col(self, col):
count = 0
for row in range(15):
if self.board[row][col] == self.color:
count += 1
if count == 5:
return True
else:
count = 0
return False
def check_diag(self, row, col):
count = 0
for i in range(-4, 5):
if row+i < 0 or row+i > 14 or col+i < 0 or col+i > 14:
continue
if self.board[row+i][col+i] == self.color:
count += 1
if count == 5:
return True
else:
count = 0
count = 0
for i in range(-4, 5):
if row+i < 0 or row+i > 14 or col-i < 0 or col-i > 14:
continue
if self.board[row+i][col-i] == self.color:
count += 1
if count == 5:
return True
else:
count = 0
return False
def reset_game(self):
self.board = [[' ' for i in range(15)] for j in range(15)]
self.color = 'black'
self.over = False
self.canvas.delete('all')
for i in range(15):
self.canvas.create_line(50, 50+i*40, 570, 50+i*40, width=2)
self.canvas.create_line(50+i*40, 50, 50+i*40, 570, width=2)
if __name__ == '__main__':
root = tk.Tk()
root.title('五子棋')
game = Gobang(root)
game.mainloop()
```