五子棋悔棋java代码,五子棋悔棋java代码

用JAVA实现五子棋悔棋代码

保存成.java文件直接运行编译

成都创新互联公司专注为客户提供全方位的互联网综合服务,包含不限于成都网站建设、成都做网站、平陆网络推广、微信小程序开发、平陆网络营销、平陆企业策划、平陆品牌公关、搜索引擎seo、人物专访、企业宣传片、企业代运营等,从售前售中售后,我们都将竭诚为您服务,您的肯定,是我们最大的嘉奖;成都创新互联公司为所有大学生创业者提供平陆建站搭建服务,24小时服务热线:18980820575,官方网址:www.cdcxhl.com

这是我回答的别人问题的答案地址

import java.util.*;

import java.io.*;

import java.awt.*;

import java.awt.event.*;

import java.applet.*;

import javax.swing.*;

class Gobang extends JFrame implements Runnable, ActionListener

{

final static int Player=1;

final static int AI =-1;

ClassLoader cl = this.getClass().getClassLoader();

Toolkit tk = Toolkit.getDefaultToolkit();

int length=14, game_state, winner, check, step;

int grid[][] = new int[length][length];

int locX, locY /* �囱�竚 */, count /* 硈囱计 */, x, y /* 既��竚 */, displace_x=0, displace_y=0 /* �簿秖 */, direction;

ArrayList steps = new ArrayList(); /* 疠魁囱˙ */

JPopupMenu control_menu = new JPopupMenu(); /* �龄匡虫�� */

JMenuItem[] command = new JMenuItem[4];

String[] command_str={"�囱", "�郎", "弄郎", "�秨"};

int[][] dir = { {-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1} };

boolean[] dir2 = new boolean[8];

boolean turn;

String message;

final JDialog dialog = new JDialog(this, "叫匡�", true);

Font font=new Font("new_font", Font.BOLD, 20);

Grid grids[][] = new Grid[length][length];

Image white= tk.getImage(cl.getResource("res/white.png"));

Image black= tk.getImage(cl.getResource("res/black.png"));

Image title= tk.getImage(cl.getResource("res/title.png"));

Image temp;

JPanel boardPanel, bigpanel;

JRadioButton[] choice = new JRadioButton[2];

final static int Start =0;

final static int Select =1;

final static int Playing =2;

final static int End =3;

final static int nil=-1; /* 礚よ� */

final static int oblique_1 =0; /* ���オ� */

final static int oblique_2 =1; /* オ���� */

final static int horizontal =2; /* 绢� */

final static int vertical=3; /* �� */

Gobang()

{

super("き�囱");

boardPanel = new JPanel();

boardPanel.setLayout(new GridLayout(length, length, 0, 0));

boardPanel.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);

for(int i=0; ilength; i++)

for(int j=0; jlength; j++)

{

grids[i][j] = new Grid(i, j);

boardPanel.add(grids[i][j]);

}

bigpanel = new JPanel();

bigpanel.add(boardPanel, BorderLayout.CENTER);

getContentPane().add(bigpanel, BorderLayout.SOUTH);

game_state=Start;

ThreadStart();

dialog.setSize(160, 100);

dialog.setResizable(false);

dialog.setLocationRelativeTo(null);

ButtonGroup choice_group = new ButtonGroup();

JPanel choice_menu = new JPanel();

choice[0] = new JRadioButton("堵�", new ImageIcon(black), true);

choice[1] = new JRadioButton("フ�", new ImageIcon(white));

for(int i=0; ichoice.length; i++)

{

choice_menu.add(choice[i]);

choice_group.add(choice[i]);

}

for(int i=0; icommand.length; i++)

{

command[i] =new JMenuItem(command_str[i]);

command[i].addActionListener(this);

control_menu.add(command[i]);

}

JButton select = new JButton("絋)");

JPanel select_menu = new JPanel();

select_menu.add(select);

select.addActionListener(this);

dialog.getContentPane().add(choice_menu, BorderLayout.NORTH);

dialog.getContentPane().add(select_menu, BorderLayout.CENTER);

setIconImage(title);

setResizable(false);

setSize(300, 335);

setVisible(true);

setLocationRelativeTo(null);

}

public static void main(String[] arg)

{

Gobang application = new Gobang();

application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

public void actionPerformed(ActionEvent event)

{

if( event.getSource().equals(command[0]) )

{

if(steps.size()!=0)

undo();

}

else if(event.getSource().equals(command[1]) )

Save();

else if(event.getSource().equals(command[2]) )

Load();

else if(event.getSource().equals(command[3]) )

ReStart();

else

{

if(choice[1].isSelected())

{

temp=white;

white=black;

black=temp;

}

dialog.dispose();

}

}

public void WinCheck()

{

check = turn? Player: AI;

direction=oblique_1;

WinCheck2();

}

public void WinCheck2()

{

count=1;

switch(direction)

{

case oblique_1: displace_x=1;

displace_y=-1;

direction=oblique_2;

break;

case oblique_2: displace_x=displace_y=1;

direction=horizontal;

break;

case horizontal: displace_x=1;

displace_y=0;

direction=vertical;

break;

case vertical: displace_x=0;

displace_y=1;

direction=nil;

break;

}

x=locX+displace_x;

y=locY+displace_y;

while(x=0 xlength y=0 ylength grid[x][y]==check)

{

count=count+1;

x=x+displace_x;

y=y+displace_y;

}

x=locX-displace_x;

y=locY-displace_y;

while(x=0 xlength y=0 ylength grid[x][y]==check)

{

count=count+1;

x=x-displace_x;

y=y-displace_y;

}

if(count=5)

{

game_state=End;

winner=check;

ThreadStart();

}

else if(direction!=nil)

WinCheck2();

}

public void ReStart()

{

for(int i=0; ilength; i++)

for(int j=0; jlength; j++)

grids[i][j].Initial();

winner=0;

steps.clear();

game_state=Playing;

}

public void gobangRandom()

{

displace_y=0;

do

{

displace_x=(int)(Math.random()*8);

x =locX+dir[displace_x][0];

y =locY+dir[displace_x][1];

if(!dir2[displace_x])

{

displace_y=displace_y+1;

dir2[displace_x]=true;

}

}while((x0 || x=length || y0 || y=length || grid[x][y]!=0) displace_y8);

for(int i=0; i8; i++)

dir2[i]=false;

if(x=0 xlength y=0 ylength grid[x][y]==0)

setMark(x, y);

else

gobangRandom2();

}

private void gobangRandom2()

{

do

{

x=(int)(Math.random()*length);

y=(int)(Math.random()*length);

}while(grid[x][y]!=0);

setMark(x, y);

}

private void gobangAI()

{

boolean play=true;

for(int i=2; i0; i--)

{

play=!play;

gobangAI4(play);

if(turn)

return;

}

for(int i=7; i=4; i--)

{

play=!play;

step=i/2;

gobangAI2(play);

if(turn)

return;

}

gobangAI5();

if(!turn)

gobangRandom();

}

private void gobangAI2(boolean player)

{

check = player? Player: AI;

for(int i=0; ilength; i++)

for(int j=0; jlength; j++)

{

if(turn)

break;

if(grid[i][j] == check)

{

count=1;

direction=oblique_1;

gobangAI3(i, j);

}

}

}

private void gobangAI3(int x, int y)

{

if(count==1)

{

locX=x;

locY=y;

}

switch(direction)

{

case oblique_1: displace_x=1;

displace_y=-1;

break;

case oblique_2: displace_x=displace_y=1;

break;

case horizontal: displace_x=1;

displace_y=0;

break;

case vertical: displace_x=0;

displace_y=1;

break;

}

x=x+displace_x;

y=y+displace_y;

if(x=0 xlength y=0 ylength grid[x][y]==check)

{

count=count+1;

if(count==step)

{

if(x+displace_x=0 x+displace_xlength y+displace_y=0 y+displace_ylength grid[x+displace_x][y+displace_y]==0)

{

if(x-step*displace_x0 || x-step*displace_x=length || y-step*displace_y0 || y-step*displace_y=length || !gobang_SpaceAI(x+displace_x, y+displace_y) || (grid[x-step*displace_x][y-step*displace_y]!=0 step3) ) /* 癸翴�猵 */

gobangAI3_2();

else

setMark2(x+displace_x, y+displace_y);

}

else

gobangAI3_2();

}

else

gobangAI3(x, y);

}

else

gobangAI3_2();

}

private void gobangAI3_2()

{

if(direction!=vertical)

{

count=1;

direction=direction+1;

gobangAI3(locX, locY);

}

}

private void gobangAI4(boolean player)

{

check = player? Player: AI;

for(int i=0; ilength; i++)

for(int j=0; jlength; j++)

{

if(turn)

break;

if(grid[i][j]==0)

{

direction=oblique_1;

locX=i;

locY=j;

gobangAI4();

}

}

}

private void gobangAI4()

{

count=0;

switch(direction)

{

case oblique_1: displace_x=1;

displace_y=-1;

direction=oblique_2;

break;

case oblique_2: displace_x=displace_y=1;

direction=horizontal;

break;

case horizontal: displace_x=1;

displace_y=0;

direction=vertical;

break;

case vertical: displace_x=0;

displace_y=1;

direction=nil;

break;

}

x=locX+displace_x;

y=locY+displace_y;

while(x=0 xlength y=0 ylength grid[x][y]==check)

{

count=count+1;

x=x+displace_x;

y=y+displace_y;

}

x=locX-displace_x;

y=locY-displace_y;

while(x=0 xlength y=0 ylength grid[x][y]==check)

{

count=count+1;

x=x-displace_x;

y=y-displace_y;

}

if(count=4)

setMark(locX, locY);

else if(direction!=nil)

gobangAI4();

}

private void gobangAI5()

{

for(int i=0; ilength; i++)

for(int j=0; jlength; j++)

{

if(turn)

break;

if(grid[i][j]==-1)

{

direction=oblique_1;

locX=i;

locY=j;

gobangAI5_2();

}

}

}

/* 璸衡硈絬�フ耞糷 */

private void gobangAI5_2()

{

count=0;

switch(direction)

{

case oblique_1: displace_x=1;

displace_y=-1;

direction=oblique_2;

break;

case oblique_2: displace_x=displace_y=1;

direction=horizontal;

break;

case horizontal: displace_x=1;

displace_y=0;

direction=vertical;

break;

case vertical: displace_x=0;

displace_y=1;

direction=nil;

break;

}

x=locX+displace_x;

y=locY+displace_y;

while(x=0 xlength y=0 ylength grid[x][y]==0 count4)

{

count=count+1;

x=x+displace_x;

y=y+displace_y;

}

x=locX-displace_x;

y=locY-displace_y;

if(count==4 x=0 xlength y=0 ylength grid[x][y]==0)

setMark(locX+displace_x, locY+displace_y);

else if(count1)

{

count = count==4? 3: count;

while(x=0 xlength y=0 ylength grid[x][y]==0 count4)

{

count=count+1;

x=x-displace_x;

y=y-displace_y;

}

if(count==4)

setMark(locX+displace_x, locY+displace_y);

else if(direction!=nil)

gobangAI5_2();

}

else if(direction!=nil)

gobangAI5_2();

}

private boolean gobang_SpaceAI(int x, int y) /* 璸衡逞缁�フ�竚 */

{

int space=0;

do

{

space=space+1;

x=x+displace_x;

y=y+displace_y;

}while(x=0 xlength y=0 ylength grid[x][y]==0 space4);

if(space+count=5) /* 逞缁�フ场だΤ硈絬ぇ�� */

return true;

else

{

space=0;

x=locX-displace_x;

y=locY-displace_y;

while(x=0 xlength y=0 ylength grid[x][y]==0 space4)

{

space=space+1;

x=x-displace_x;

y=y-displace_y;

}

if(space+count=5) /* 逞缁�フ场だΤ硈絬ぇ�� */

return true;

else

return false;

}

}

public void ThreadStart()

{

new Thread(this).start();

}

private void setMark(int x, int y)

{

steps.add(grids[x][y]);

grids[x][y].setValue(-1);

WinCheck();

turn=true;

}

/* 璸衡�ê�よ�Τ�隔 */

private void setMark2(int x, int y)

{

int space=0, temp_x=x, temp_y=y;

do

{

space=space+1;

temp_x=temp_x+displace_x;

temp_y=temp_y+displace_y;

}while(temp_x=0 temp_xlength temp_y=0 temp_ylength grid[temp_x][temp_y]==0 space4);

if(space+step=5)

setMark(x, y);

else

setMark(x-(step+1)*displace_x, y-(step+1)*displace_y); /* э�癸翴 */

}

public void run()

{

try

{

switch(game_state)

{

case Start: Thread.sleep(2000);

dialog.show();

game_state=Playing;

repaint();

break;

case End: repaint();

Thread.sleep(1500);

ReStart();

repaint();

break;

}

}

catch(InterruptedException ex)

{

}

}

public void paint(Graphics g)

{

super.paint(g);

switch(game_state)

{

case Start: g.drawString("2005.7 by Yu Lin Tao", 91, 240);

g.setFont(font);

g.setColor(Color.BLUE);

g.drawString("Gobang", 112, 120);

g.drawImage(title, 134, 135, this);

break;

case Playing:

case End:

g.drawString("�产: 筿福:", 105, 40);

g.drawImage(black, 132, 30, this);

g.drawImage(white, 182, 30, this);

if(winner!=0)

{

g.setFont(font);

g.setColor(Color.RED);

message = winner==1? "�墓�":"�块�";

g.drawString(message, 120, 185);

}

break;

}

}

public void undo()

{

if(steps.size()0)

{

for(int i=0; i2; i++)

{

((Grid)steps.get(steps.size()-1)).Initial();

steps.remove(steps.size()-1);

}

}

}

private void Save()

{

String str;

try

{

File file = new File("innings.men");

file.createNewFile();

BufferedWriter write = new BufferedWriter(new FileWriter(file));

for(int i=0; isteps.size(); i++)

{

str=(((Grid)steps.get(i)).getLocX())+","+(((Grid)steps.get(i)).getLocY())+","+(((Grid)steps.get(i)).getValue());

write.write(str);

write.newLine();

}

write.close();

}

catch(Exception ex)

{

}

}

private void Load()

{

try

{

String[] step_array;

String str;

File file = new File("innings.men");

if(!file.exists())

{

JOptionPane.showMessageDialog(null, "⊿Τ�郎");

return;

}

BufferedReader read = new BufferedReader(new FileReader(file));

ReStart();

while(read.ready())

{

str=read.readLine();

step_array=str.split(",");

grids[Integer.parseInt(step_array[0])][Integer.parseInt(step_array[1])].setValue(Integer.parseInt(step_array[2]));

steps.add(grids[Integer.parseInt(step_array[0])][Integer.parseInt(step_array[1])]);

}

}

catch(Exception ex)

{

}

}

private class Grid extends JPanel implements MouseListener

{

int x, y, value;

boolean selected;

public Grid(int x, int y)

{

this.x=x;

this.y=y;

addMouseListener(this);

}

public void mousePressed(MouseEvent event)

{

if(game_state==Playing)

{

int button=event.getButton();

if(button==MouseEvent.BUTTON1)

{

if(value==0)

{

steps.add(this);

setValue(1);

WinCheck();

turn=false;

if(game_state==Playing)

gobangAI();

}

}

else

control_menu.show(this, event.getX(), event.getY());

}

}

public void mouseEntered(MouseEvent event)

{

if(game_state==Playing)

setSelected(true);

}

public void mouseExited(MouseEvent event)

{

if(game_state==Playing)

setSelected(false);

}

public void mouseClicked(MouseEvent event)

{

}

public void mouseReleased(MouseEvent event)

{

}

public Dimension getPreferredSize()

{

return new Dimension(20, 20);

}

public Dimension getMinimumSize()

{

return getPreferredSize();

}

public int getLocX()

{

return x;

}

public int getLocY()

{

return y;

}

public int getValue()

{

return value;

}

public void Initial()

{

value=grid[x][y]=0;

selected=false;

repaint();

}

public void setValue(int new_value)

{

locX=x;

locY=y;

value=grid[x][y]=new_value;

repaint();

}

public void setSelected(boolean select)

{

selected=select;

repaint();

}

public void paintComponent(Graphics g)

{

super.paintComponent(g);

if(game_state!=Start game_state!=Select)

{

g.drawLine(0, 10, 19, 10);

g.drawLine(10, 0, 10, 19);

/* 礶娩絬 */

g.setColor(Color.BLUE);

if(x==0)

g.drawLine(0, 0, 19, 0);

else if(x==length-1)

g.drawLine(0, 19, 19, 19);

if(y==0)

g.drawLine(19, 0, 19, 19);

else if(y==length-1)

g.drawLine(0, 0, 0, 19);

if(selected)

setBackground(Color.WHITE);

else

setBackground(Color.LIGHT_GRAY);

}

//g.drawString(x+" "+y, 1, 10);

if(value!=0)

{

temp = value==1? black: white;

g.drawImage(temp, 4, 4, this);

}

}

}

}

系统框图如下 java实现五子棋程序 可以实现人人对战 人机对战 简单功能 悔棋 认输

一、实验题目

五子棋游戏。

二、问题分析

五子棋是双人博弈棋类益智游戏,由围棋演变而来,属纯策略型。棋盘通常15*15,即15行,15列,共225个交叉点,即棋子落点;棋子由黑白两色组成,黑棋123颗,白棋122颗。游戏规则为黑先白后,谁先五子连成一条直线谁赢,其中直线可以是横的、纵的、45度、135度。

本次Java编程我的目的是现实人机对战,即游戏者一方是人,另一方计算机。这就要求程序不仅要具备五子棋的基本界面,还要编程指导计算机与人进行对弈。为了使程序尽可能智能,我采用了贪心策略、传统搜索算法、极大极小博弈树算法,对应游戏玩家的3个等级:简单、中等、困难。

三、功能设计

我的程序基本功能是实现人机对弈五子棋。人和电脑交替下棋,谁先五子连成一条直线谁就赢。下面是我程序的功能模块:

1.等级设置

核心功能是实现不同策略与算法的对比运用,纯贪心策略实现简单等级对手,直接搜索算法实现中等等级对手,极大极小博弈树算法实现困难等级对手。对应程序中的3选1单选按钮。

2.悔棋功能

模拟栈机制实现人悔棋,不限步长的悔棋。对应程序中的悔棋按钮。

3.棋面绘制

根据不同机计算机的屏幕分辨率,绘制逼真的棋盘。

4.图片引入

两张古典的人物图片,生动模拟对弈双方。人物图片旁的黑白棋钵图片显示黑白棋归属。

5.背景设置

支持用户选择背景,包括棋盘、棋盘边框、窗口边框,彰显个性。

6.音乐播放

下棋时有棋子落地的声音,一方胜利时有五子连成一片的声音。同时在设置背景时相应的改变整个对弈过程中的背景音乐。

7.时间显示

在棋盘正上方有一模拟文本框显示当前棋局用时。

8.其他小功能

支持和棋、认输、开启新游戏、退出游戏等操作。

四、数据结构与算法设计

数据结构部分

1.当前棋局的存储结构

我的五子棋程序选择通常用到的15行*15列棋盘,可以开二维数组PositionFlag = new int[15][15],PositionFlag[i][j]为0表示(i,j)点尚无棋,为1表示(i,j)点是人的棋子,为2表示(i,j)点是机器的棋子。之所以选择二维数组,主要原因有两点:

1.本程序需要频繁随机访问15*15的交叉点,对应查询该点状态以及改变该点状态,随机访问是数组的特点。

2.15*15=225开二维数组的内存需求相对现在内存为2G及以上的计算机完全可以接受,且数组实现简单、操作方便。

基于以上两点,尽管创建动态的顺序表—链表可能可以节省少量内存(可以只存当前有棋的点,原数组对应位置为0的点可以不存),但选择数组的优势完全在上述两点体现了出来。

2.实现悔棋操作的数据结构

由于每次悔棋只需回退当前几步,后进先出原则,这正是栈这种典型数据结构的设计思想,于是我选择栈。我自己先写了用自定义数组模拟的栈,但由于是学Java语言且由于悔棋的存储空间需要随当前步数增大而增大(由于每局最多下225步,即最多要悔225步,所以自己开个225的数组完全可以避免存储空间自增长的问题且内存完全可以接受,之所以不用自定义数组而用ArrayList类主要是为了尝试Java中STL的用法),所有我最终改为用Java类库中的ArrayList类。

确定用ArrayList类实现栈机制后就必须考虑每个ArrayList单元具体存储什么。刚开始我存储的是当前的棋局,即整个局面,而每个局面对应一个二维数组,这样是很占用内存的。试想一下,在最坏情况下,225个ArrayList单元,每个单元存放一个15*15的二维数组,尽管225*15*15在Java的内存管理机制下不会爆栈,但也是极不划算的。之所以说不划算,是因为有更好的解决方案。由于每次悔棋只是在回退倒数一步,多步悔棋只需循环回退,所以可以只存储当前棋局最后一步的下法,对应一个二维点,完全可以自定义一个二维坐标类chessOneStep。

算法设计部分

Java语言是面向对象的语言。我在进行五子棋游戏编程是总共传创建了11个自定义的类。在编写程序的过程中,我有一个明显的体验就是面向对象编程就是一项有关对象设计和对象接口技术,很多关键的技术就是如何设计自定义的对象。

下面我先概括给出我的所有类的作用:

1.mainFrame类:主框架类,我应用程序的入口;

2.chessPositon类:主控类,这个类是我程序的核心类,负责控制双方的下棋,以及调用其他的类完成当前棋局的显示绘制;

3.chessPanel类:面板类,调用其他底层类完成当前棋局的显示绘制;

4.chessBoard类:棋盘绘制类,负责棋盘的绘制;

5.chessImage类:文件类,包含各种资源(背景图片、背景音乐)以及静态全局变量(public static Type);

6.chessButton类:组件类,定义各种组件,包括按钮、单选按钮、文本框等;

7.chessMusic类:音乐类,负责调用Java库类完成背景音乐、下棋音乐、取胜音乐等的播放;

8.chessPiece类:棋局类,定义棋局二维数组数据结构并完成相关操作;

9.chessList类:栈类,完成悔棋等操作;

10. chessOneStep类:棋子类,定义每步坐标以及下在该处获得的估价值;

11.myCompare类:排序类,完成chessOneStep类的自定义排序

详细设计

1.mainFrame类

作为我的五子棋程序的主类,mainFrame类主要实例化相关的对象,如chessbutton,chessborad等,从而完成框架的创建。更重要的是实例化chessposition,这是本程序的核心类,控制游戏双方行棋过程完成人机互动下棋,然后将MyChessPosition与鼠标响应addMouseListener()关联起来。

2.chessMusic类

一个好的游戏必须给人一种身临其境的感觉,而声音是营造这种氛围的重要因素。参照网上各游戏运行商的音乐配置,我选择相关逼真的声音。包括背景音乐、下棋棋子落到棋盘发出的声音以及一方胜出的配乐。所有这些功能的实现,依赖于自定义的chessMusic类,采用AudioInputStream配合Clip的方式完成音乐播放的软硬件工作,然后定义两个接口chessmusic(String Name)和Stop(),前者完成播放功能,后者完成关闭当前音乐功能。因为音频文件相对较大,而我的程序提供在不同背景乐之间切换的功能,所以在打开另一个音频文件之前必须关闭前一个正在播放的音频文件,防止出现溢出。

3.chessImage类

适当的动画或图片能给游戏玩家带来美的体验。所以我的五子棋程序界面在不失和谐的前提下引入了尽可能多的图片,包括对弈双方、棋钵等。图片引入的具体工作通过语句import javax.imageio.ImageIO完成。同时,由于图片要在用到它的类中被访问,为了避免频繁调用函数,我直接将图片相关联的对象定义为public static,表明是公用的、静态的。进一步引申开去,我将程序中用到的静态全局变量都定义在chessImage类中。具体如下:

public static Date begin;//每局开始时间

public static Date cur;//每局结束时间

public static chessOneStep LineLeft;//结束端点1

public static chessOneStep LineRight;//结束端点2

public static boolean IsGameOver;//是否只有一方获胜

public static int ColorOfBackGround[][]= {{255, 227, 132},{0,255,127},{218,165,32}};//背景颜色

public static int ColorOfWindows[][]= {{ 60,179,113},{245,245,245},{122,122,122}};//背景颜色

public static int WitchMatch;//背景搭配

public static String MusicOfBackGround;//背景音乐

public static int CurrentStep;//记录当前步数

public static int Rank;//设置难度等级

public static boolean IsSurrender;//判断是否认输

public static boolean IsTie;//判断是否认输

public static String Message;//输出提示信息

public static Image IconImage;// 图标

public static Image blackBoard;//白棋盘

public static Image whiteBoard;//黑棋盘

public static Image blackChess;// 白棋棋子图片

public static Image whiteChess;// 白棋棋子图片

public static Image RightPlayer;//白棋棋罐图片

public static Image LeftPlayer;//白棋玩家头像图片

public static String path = "src/";// 图片的保存路径

4.chessButton类

这个是程序的组件类。定义了各种功能键,完善程序功能,营造逼真的人机对战游戏效果。分为3类:效果。。

(1)、按钮组件

本程序有5个按钮,支持和棋、认输、新游戏、退出、悔棋等。认输和和棋按钮终止当前的棋局,给出相应的提示信息;退出按钮调用系统System.exit(0)的函数正常返回;悔棋按钮调用后面要介绍的chessList类实现悔棋;新游戏按钮则刷新当前棋局准备下一轮,要将记录当前棋局的二维数组全部置0,刷新当前棋局开始时间等。

(2)、单选按钮组件

游戏界面支持设置个性化界面,包括背景颜色与背景音乐,跟重要的一点是设置难度(简单、中等、困难)。单选按钮只能多选一。背景颜色主要是存储相关颜色搭配方案的RGB颜色,开2维数组,即对应RGB3原色数组的一维数组,然后通过改变WitchMatch全局变量的值来有用户自己选择颜色搭配,不同的颜色搭配对应不同的背景音乐表达一致的主题。难度设置主要是改变计算机的下棋算法,不同难度通过Rank判断进入不同的程序分支,实现不同智能等级的计算机下棋水平。

(3)、文本框

在不同的单选按钮前添加相应的文本框,提示用户可以实现的功能。同时我用颜色模拟出显示当前棋局耗用时间的文本框。

不论按钮还是单选按钮都要关联相应的消息,把相应功能的实现放在消息响应处理函数理。这些主要是实现Java库提供的消息响应接口里的方法。

5.chessPiece类

主要完成当前棋面的存储,存储棋面的数据结构为二维数组int[][] PositionFlag;然后定义获取、设置某点以及整个棋面的状态的方法。

(1)、SetPositionFlag(int x, int y, int flag)//设置(x,y)处的状态为flag

(2)、GetPositionFlag(int x, int y)//获取(x,y)处的状态

(3)、SetAllFlag(int [][]NewFlag)//设置当前整个棋面的状态为NewFlag

(4)、GetAllFlag()//获取当前整个棋面的状态

(5)、DrawChessPiece(Graphics g)//绘制当前局面的棋子

由于本类比较重要,所以附上了代码,见源代码1。

6.chessBoard类

功能为绘制棋盘线。由于围棋的棋盘比较复杂,横线、竖线较多,且为了使棋盘美观,还要自定义窗口边框、棋盘边框、对弈双方边框等,对线宽、线型也有一定要求。有时要单像素线条,有时要多像素线条。对于多像素线条,我主要用了2种方法。

方法一:

在需要绘制多像素线条处首先绘制一条单像素线,然后根据线宽要求上下平移适当像素达到绘制多像素的目的。这样的方法适合绘制水平线或竖直线,绘制其他斜率的线条容易造成走样。在没有想到比较好的反走样编程思想后我选择了调用Java库中已经封装好的函数。

方法二:

为了克服方法一绘制非水平或竖直线时造成的走样,同时也为了更进一步学习Java语言,我猜想肯定会有类似OpenGL中设置线宽的画刷,于是上网百度找到了相应的画刷Stroke类。通过Java库实现绘制不同线宽的直线,达到了反走样效果。

7.chessOneStep类

这个类是为了配合chessList类实现悔棋以及在计算机下棋算法实现返回有效状态点而设计的。主要数据成员为

private  int  x,y,weight;//其中x,y表示点坐标,weight表示将棋下到该点获得的估价值。

主要方法如下:

(1)、GetX()//获得当前对象的x坐标

(2)、GetY()//获得当前对象的y坐标

(3)、GetWeight()//获得当前对象的(x,y)处的估价值

8.chessList类

程序支持悔棋功能,为了实现悔棋,自定义了chessList类。这个类主要通过引入java.util.ArrayList和java.util.List实现集合的数据类型。然后自定义一些方法,如下:

(1)、AddStep(chessOneStep OneStep)//添加一步棋到List中

(2)、GetSize()//获得当前List的大小

(3)、ClearList()//清空List

(4)、RemoveLast()//删去List中的最后元素

由于每次删除当前List中的最后一个元素,实现后进先出,所以可以模拟栈的功能实现悔棋。

9.myCompare类

由于在计算机下棋的极大极小博弈树算法中需要对自定义对象chessOneStep按weight进行排序,所以引入了myCompare类,通过实现Comparator接口中的compare方法完成自定义对象排序。

10.chessPanel类

程序的自定义面板类,主要负责完成当前框架内容的显示。这是一个重要的与框架和图形显示密切相关的类。主要数据成员为

private chessboard MyChessBoard;//当前显示棋盘

private chesspiece MyChessPiece;//当前显示整个棋面的状态

主要方法如下:

(1)、chesspanel(chessboard MyChessBoard1, chesspiece MyChessPiece1)//构造函数,分别用MyChessBoard1和MyChessPiece1初始化MyChessBoard和MyChessPiece

(2)display(chessboard MyChessBoard1, chesspiece MyChessPiece1)//自定义显示回调函数,调用repaint()完成重新绘制游戏界面

(3)、paintComponent(Graphics g)//核心方法,调用各种函数完成具体的绘制工作

11.chessPositon类

程序算法核心类,总的功能是控制人和计算机轮流下棋,以及调用chessPanel类中的display(chessboard , chesspiece )方法完成界面的实时刷新。关于chessPositon类,我在此将重点介绍。chessPosition类的主要数据成员如下:

private static chessboard MyChessBoard;//当前显示棋盘

public static chesspiece MyChessPiece;//当前显示整个棋面的状态

private static chesspanel Mychesspanel;////当前显示面板

public static chesslist MyChessList=new chesslist();//当前下棋集合,用于悔棋

final private static int INF = (1  30); // 表示正无穷大的常量,用于极大极小博弈数搜索算法

public static boolean CanGo;//控制当前下棋一方

类的设计集中体现在成员方法的设计上。实现人机对战,只有语言是远远不够的,还要加入算法,用算法引导计算机下棋。下面介绍该类的方法成员:

(1)、chessposition(chesspanel , chessboard ,chesspiece ) //带有参数的构造函数

(2)、chessposition()

不带参数的构造函数

(3)、mouseClicked(MouseEvent event)

鼠标响应函数,负责人的下棋,根据鼠标点击的位置转换得到所在棋盘的相对位置。如果该位置不合法,即超出棋盘有效范围,点击无响应;如果该位置上已有棋,弹出消息框给出提示。这二者都要求重新给出下棋位置,即当前鼠标响应无效…直到点击到棋盘有效区域。

(4)、IsOver(int[][] Array,int x,int y)

判断当前int[][]Array对应的棋局是否结束,即一方五子连成一条直线。此处有两种思路,一种对当前棋面上的所有棋子都进行一次判断,具体为水平方向、竖直方向、与水平线成45度方向、与水平线成135度方向,只要有一个方向五子连成一条直线就说明有一方获胜,游戏结束;另一种思路为只在当前下棋的4个方向进行判断,我的程序采用的是第二种,所以IsOver方法除了int[][]Array参数外,还有x,y参数,(x,y)表示当前下棋的坐标点。

(5)display()

通过调用自定义面板类的显示回调函数用于重新显示游戏界面,达到每下一步棋及时更新游戏界面的目的。

(6)、GetValue(int flag, int num)

估值函数,根据经验把棋局分成只有1颗棋相连,2颗棋相连且两端被封死,2颗棋相连且一端封死另一端活的,2颗棋相连且两端都是活的,同理3颗棋、4颗棋也各自可分3种情况。不同的情况对应不同的估价值。估价值的设定是决定计算机一方是否智能的一个关键因素。

(7)、GetPredictValue(int flag, int num)

对未连成一片但通过再下一颗子就能连成一片的局面进行估值,这在双方下棋的有限步骤内是能产生重要影响的。如果每局棋仅考虑当前一步,是不可取的。

(8)、Evaluate(int[][] Array, int x, int y)

根据棋面具体情况以及预先设定的估值函数,对某个点对应的局面进行评估。由于每次双方只能下一颗棋,所以可以每次取当前局面的所有点中对应估值最大值点的估值作为整个局面的估值。

(9)、GetGreedNext()

计算机下棋方法1,对应难度等级为简单,采用贪心思想。每次下棋前在求得最有利点下棋,而是否最有利只是通过一步评估。算法伪码描述为:

Max取负无穷大

for(行i从0到15)

{

For(列j从0到15)

{

If((i,j)对应的位置无棋)

{

a.假设放上一颗由人控制的棋,求估价值;

b.假设放上一颗由计算机控制的棋,求估价值;

c.取二者中较大值作为(i,j)处的估价值tmp;

d.取tmp与Max较大值赋值给Max.

}

}

}

最终Max对应的点就是当前整个局面中最大的估值点。至于上述为什么要考虑双方都在该点下棋的情况呢?主要原因为下五子棋是个攻防兼备的过程,不仅要考虑自己对自己最有利,还要考虑对对手最不利,通俗来讲就是在自己赢的时候不能让对手先赢。

(10)、GetSearchNext(int LookLength)

derectSearch(int [][]Array,boolean who,int deepth)

计算机下棋方法2:直接搜索法,对应难度等级为中等。

每步棋最多有225个不同下法,若采用直接搜索法则对应的孩子节点有225个(在下棋过程中会逐渐减少),即每层有最多225个节点待扩展,这就决定了直接搜索进行不超过2次—主要原因有两点:

a.采用深度优先搜索需要递归,递归中状态过多可能会爆栈,我们知道递归是用栈机制来实现的;采用宽度优先搜索又需要存储为扩展的节点,这对内存容量要求很高。

b.不管深搜还是广搜,在时间复杂度为O(N^m)的情况下都是不能接受的。其中N为当前棋局的待扩展节点,最大225;m为搜索的深度。

综上所述,在采用直接搜索法时搜索深度不能太深,严格来说是应该控制在2层以内,在计算机运算速度在10^7次每秒的情况下,理论和实验都表明超过2层就会变得很慢且这种趋势成指数级增长。

直接搜索算法伪代码为

GetSearch(boolean flag,int deep)

{

如果deep等于0,返回当前棋局估值;

for(行i从0到15)

{

For(列j从0到15)

{

If((i,j)对应的位置无棋)

{

如果轮到计算机下棋,置标志位为2

GetSearch(!flag,deep-1);

如果轮到人下棋,置标志位为1;

GetSearch(!flag,deep-1);

}

}

}

}

(11)、GetMinMaxsearchNext(int LookLength)

MinMaxsearch(int [][]Array,boolean who, int deepth)

计算机下棋算法3:极大极小博弈树法,对应难度等级为困难。五子棋是个博弈游戏,当前在寻找对自己最有利的下棋点时要尽可能保证对对手最不利,这种思想可以用极大极小博弈树

五子棋java代码请帮忙加一个悔棋功能,急呀急呀

用栈,把每一步操作都记录下来。悔棋把最后一步从栈中拿出来,然后还原回去

JAVA高手接招————— 五子棋双人对弈程序

新建一个chess类,其中代码如下

package work;

import java.awt.Color;

public class Chess {

public static final int diamter=30;

private int x;//在网格中的索引,0~15

private int y;//在网格中的索引,0~15

private Color color;

public Color getColor() {

return color;

}

public void setColor(Color color) {

this.color = color;

}

public int getX() {

return x;

}

public void setX(int x) {

this.x = x;

}

public int getY() {

return y;

}

public void setY(int y) {

this.y = y;

}

public Chess(int x, int y, Color color) {

super();

this.x = x;

this.y = y;

this.color = color;

}

}

然后在同一个包中新建FirstFrame类。代码如下

package work;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.JFrame;

import javax.swing.JMenu;

import javax.swing.JMenuBar;

import javax.swing.JMenuItem;

//主函数

public class FirstFrame{

public static void main(String[] args) {

FirstFrame1 f=new FirstFrame1();

f.setVisible(true);

}

}

//窗体函数

class FirstFrame1 extends JFrame implements ActionListener{

JMenuBar menuBar;

JMenu sysMenu;

JMenuItem startMenuItem;

JMenuItem backMenuItem;

JMenuItem exitMenuItem;

DrawPanel myPanel=new DrawPanel();

public FirstFrame1(){

super("娃哈哈");

add(myPanel);

menuBar=new JMenuBar();

setJMenuBar(menuBar);

sysMenu=new JMenu("系统(s)");

sysMenu.setMnemonic('s');

menuBar.add(sysMenu);

startMenuItem=new JMenuItem("开始");

backMenuItem=new JMenuItem("悔棋");

exitMenuItem=new JMenuItem("退出");

sysMenu.add(startMenuItem);

sysMenu.add(backMenuItem);

sysMenu.addSeparator();

sysMenu.add(exitMenuItem);

startMenuItem.addActionListener(this);

backMenuItem.addActionListener(this);

exitMenuItem.addActionListener(this);

super.setSize(600,650);

super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

public void actionPerformed(ActionEvent e){

Object obj=e.getSource();

if(obj==startMenuItem){

myPanel.start(); //DrawPanel p=new DrawPanel();是错的;

}else if(obj==backMenuItem){

myPanel.back();

}else{

System.exit(0);

}

}

}

最后新建一个DrawPanel类代码如下

package work;

import java.awt.Color;

import java.awt.Cursor;

import java.awt.Graphics;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.MouseEvent;

import java.awt.event.MouseListener;

import java.awt.event.MouseMotionListener;

import javax.swing.JFrame;

import javax.swing.JMenu;

import javax.swing.JMenuBar;

import javax.swing.JMenuItem;

import javax.swing.JOptionPane;

import javax.swing.JPanel;

import sun.awt.geom.AreaOp.AddOp;

//画柄;

class DrawPanel extends JPanel implements MouseListener,MouseMotionListener{

final int MARGIN_TOP=60;

final int MARGIN_LEFT=30;

final int CELL_WIDTH=35;

final int COLS=15;

final int ROWS=15;

Chess[] chessList=new Chess[(COLS+1)*(ROWS+1)];

int chessCount=0;

boolean isBlack=true;

boolean gameOver=false;

public DrawPanel(){ //构造函数

Color color=new Color(200,250,200);

setBackground(color);

this.addMouseMotionListener(this);

this.addMouseListener(this);

}

public void start(){

for(int i=0;ichessList.length;i++)

chessList[i]=null;

isBlack=true;

gameOver=false;

chessCount=0;

repaint();

}

public void back(){

if (chessCount==0||gameOver==true)

return;

chessList[chessCount-1]=null;

chessCount--;

isBlack=!isBlack;

repaint();

}

@Override

protected void paintComponent(Graphics g) { //方法重写

// TODO Auto-generated method stub

super.paintComponent(g);

for(int i=0;i=ROWS;i++){

g.drawLine(MARGIN_LEFT, MARGIN_TOP+i*CELL_WIDTH, MARGIN_LEFT+COLS*CELL_WIDTH, MARGIN_TOP+i*CELL_WIDTH);

}

for(int i=0;i=COLS;i++){

g.drawLine(MARGIN_LEFT+i*CELL_WIDTH, MARGIN_TOP, MARGIN_LEFT+i*CELL_WIDTH, MARGIN_TOP+ROWS*CELL_WIDTH);

}

for(int i=0;ichessCount;i++){ //绘制棋子数组

Chess chess=chessList[i];

int xPos=MARGIN_LEFT+CELL_WIDTH*chess.getX()-Chess.diamter/2;

int yPos=MARGIN_TOP+CELL_WIDTH*chess.getY()-Chess.diamter/2;

g.setColor(chess.getColor());

g.fillOval(xPos,yPos, Chess.diamter, Chess.diamter);

if(i==chessCount-1){

g.setColor(Color.red);

g.drawRect(xPos, yPos, Chess.diamter, Chess.diamter);

}

}

if(isBlack)

g.setColor(Color.black);

else

g.setColor(Color.white);

g.fillOval(8*CELL_WIDTH, CELL_WIDTH/2,Chess.diamter, Chess.diamter);

String colorStr=isBlack==false?"白方下":"黑方下";

g.setColor(Color.blue);

g.drawString(colorStr+" 第"+chessCount/2+"步", 9*CELL_WIDTH, CELL_WIDTH);

}

public void mouseClicked(MouseEvent e) {}

public void mouseEntered(MouseEvent e) {}

public void mouseExited(MouseEvent e) {}

public void mouseReleased(MouseEvent e) {}

public void mouseDragged(MouseEvent e) {}

public void mouseMoved(MouseEvent e) {

// TODO Auto-generated method stub

super.setCursor(new Cursor(Cursor.HAND_CURSOR));

int x=(e.getX()-MARGIN_LEFT+Chess.diamter/2)/CELL_WIDTH;

int y=(e.getY()-MARGIN_TOP+Chess.diamter/2)/CELL_WIDTH;

if(x0||y0||xCOLS||yROWS) //超出棋盘边界

super.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));

if(findChess(x,y)) //下过的地方不能再下

super.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));

if(gameOver)

super.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));

}

public void mousePressed(MouseEvent e) {

int x=(e.getX()-MARGIN_LEFT+Chess.diamter/2)/CELL_WIDTH;

int y=(e.getY()-MARGIN_TOP+Chess.diamter/2)/CELL_WIDTH;

if(x0||y0||xCOLS||yROWS) //超出棋盘边界

return;

Color color=Color.black;

if(!isBlack) // 变颜色

color=Color.white;

if(findChess(x,y)) //下过的地方不能再下

return;

if(gameOver)

return;

chessList[chessCount]=new Chess(x,y,color);

repaint(); //重绘

isBlack=!isBlack;

chessCount++;

String colorStr=color==Color.white?"白方":"黑方";

int[] count={0,0,0,0};

for(int i=x-1;i=0;i--){

if(findChess(i,y,color)){

count[0]++;

}

else

break;

}

for(int i=x+1;i=COLS;i++){

if(findChess(i,y,color)){

count[0]++;

}

else

break;

}

for(int i=y-1;i=0;i--){

if(findChess(x,i,color)){

count[1]++;

}

else

break;

}

for(int i=y+1;i=ROWS;i++){

if(findChess(x,i,color)){

count[2]++;

}

else

break;

}

for(int i=x+1,j=y+1;i=COLSj=ROWS;i++,j++){

if(findChess(i,j,color)){

count[3]++;

}

else

break;

}

for(int i=x-1,j=y-1;i=0j=0;i--,j--){

if(findChess(i,j,color)){

count[3]++;

}

else

break;

}

for(int i=x+1,j=y-1;i=COLSj=0;i++,j--){

if(findChess(i,j,color)){

count[3]++;

}

else

break;

}

for(int i=x-1,j=y+1;i=0j=ROWS;i--,j++){

if(findChess(i,j,color)){

count[3]++;

}

else

break;

}

for(int i=0;i4;i++){

if(count[i]=4){

gameOver=true;

JOptionPane.showMessageDialog(this, "恭喜"+colorStr+"胜利");

return;

}

}

System.out.println(e.getX()+","+e.getY());

}

public boolean findChess(int x,int y){

for(int i=0;ichessCount;i++){

if(chessList[i].getX()==x chessList[i].getY()==y)

return true;

}

return false;

}

public boolean findChess(int x,int y,Color color){

for(int i=0;ichessCount;i++){

if(chessList[i].getX()==x chessList[i].getY()==y chessList[i].getColor()==color)

return true;

}

return false;

}

}

如果不行就hi我

JAVA五子棋中如何实现重新开始和悔棋的功能

一般来说是不应该像你这样写的,应该是把要画的步骤写在组件的被覆写的paintComponent函数里,然后在你响应事件的函数里直接掉用该组件的repaint()函数即可。repaint函数是会去掉该组件的paintComponent()函数的。至于你这么写为啥不行,这个我也不清楚,据我猜测,repaint函数要做的事情是刷新组件,并且重新去画一遍,不过这个步骤不一定是立即完成,可能有延迟。总之在你画那些棋子之后,它又干了一些事情,导致你画的棋子没了(但这不会影响到它自己想去画的东西,即paintComponent()函数里的东西),另外不要忘了,覆写paintComponent时,第一行要写,super.paintComponent(g),这是去画它原来有的东西(比如加上去的按钮,文本框之类的东西)

例如下面:

12345678910111213141516171819202122232425262728293031323334353637class PanelM extends JPanel{ ImageIcon icon = new ImageIcon("app.gif"); JLabel jl = new JLabel(icon, SwingConstants.CENTER); int x, y; private ListInteger listX = new ArrayListInteger(); private ListInteger listY = new ArrayListInteger(); public PanelM() { add(jl); addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent m) { x = m.getX(); y = m.getY(); listX.add(x); listY.add(y); repaint(); } }); } public void paintComponent(Graphics g) { super.paintComponent(g); for (int i = 0; i listX.size(); i++) { g.fillOval(listX.get(i), listY.get(i), 20, 20); } }}

java单机版五子棋添加悔棋模块

每下一步棋,你就把这一步的信息,(位置,谁下的,黑或者白,封装成一个对象A) 放入一个栈中,点击上一步,把栈里的数据拿出了,你获取到一个A对象,根据A对象,把五子棋的数据,还原,应该是用一个二维数组保存五子棋的数据的吧,然后重绘UI,流程应该是这么做,你需要根据A对象来还原到以前的状态,所以A对象应该保存能还原到以前状态的完整的信息。这里的细节需要多想想。然后就是 栈的用法了,理解这种数据结构,以及这里为什么要用栈,多想想就好了

本文题目:五子棋悔棋java代码,五子棋悔棋java代码
标题链接:https://www.cdcxhl.com/article30/dsiegso.html

成都网站建设公司_创新互联,为您提供静态网站域名注册网站维护网站收录关键词优化企业网站制作

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

营销型网站建设