用python写一个4*4的16宫格下棋游戏,人机对战
时间: 2023-12-02 12:05:47 浏览: 124
好的,我可以为您提供一个简单的4*4的16宫格下棋游戏,支持人机对战。需要用到Python的tkinter模块来构建GUI界面。
以下是代码:
```python
import tkinter as tk
import random
class Game:
def __init__(self):
self.window = tk.Tk()
self.window.title('16宫格棋')
self.window.geometry('300x300')
self.window.resizable(width=False, height=False)
self.player = 'X'
self.computer = 'O'
self.board = [[None for i in range(4)] for j in range(4)]
self.buttons = [[None for i in range(4)] for j in range(4)]
self.font = ('Arial', 20)
self.winner = None
self.draw_board()
self.window.mainloop()
def draw_board(self):
for row in range(4):
for col in range(4):
button = tk.Button(self.window, text='', font=self.font, width=2, height=1,
command=lambda row=row, col=col: self.button_click(row, col))
button.grid(row=row, column=col)
self.buttons[row][col] = button
def button_click(self, row, col):
if self.board[row][col] is None:
self.buttons[row][col].config(text=self.player)
self.board[row][col] = self.player
self.check_winner()
if self.winner is None:
self.computer_move()
self.check_winner()
def computer_move(self):
empty_cells = []
for row in range(4):
for col in range(4):
if self.board[row][col] is None:
empty_cells.append((row, col))
if empty_cells:
row, col = random.choice(empty_cells)
self.buttons[row][col].config(text=self.computer)
self.board[row][col] = self.computer
def check_winner(self):
for row in range(4):
if self.board[row][0] == self.board[row][1] == self.board[row][2] == self.board[row][3]:
if self.board[row][0] is not None:
self.winner = self.board[row][0]
self.declare_winner()
return
for col in range(4):
if self.board[0][col] == self.board[1][col] == self.board[2][col] == self.board[3][col]:
if self.board[0][col] is not None:
self.winner = self.board[0][col]
self.declare_winner()
return
if self.board[0][0] == self.board[1][1] == self.board[2][2] == self.board[3][3]:
if self.board[0][0] is not None:
self.winner = self.board[0][0]
self.declare_winner()
return
if self.board[0][3] == self.board[1][2] == self.board[2][1] == self.board[3][0]:
if self.board[0][3] is not None:
self.winner = self.board[0][3]
self.declare_winner()
return
if all([self.board[row][col] is not None for row in range(4) for col in range(4)]):
self.winner = 'Draw'
self.declare_winner()
def declare_winner(self):
if self.winner == 'Draw':
message = '平局!'
else:
message = '胜利者: {}'.format(self.winner)
self.window.title(message)
for row in range(4):
for col in range(4):
self.buttons[row][col].config(state='disabled')
```
运行这个程序,将会弹出一个4*4的棋盘,您可以点击空白的棋格来放置自己的棋子,电脑会自动下一步。游戏会在有一方获胜或者平局时结束。
阅读全文