- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package game;
- import javax.swing.*;
- import java.awt.*;
- import java.awt.event.*;
- class ChessPanel extends JPanel{
- private int space=20;
- //网格距离
- private int grids=30;
- //网格数.
- private int radios=space/2;
- //棋的半径。
- private int[][] chesses=new int[grids+1][grids+1];
- private int currcolor=1;
- private JMenuBar chessmenubar=new JMenuBar();
- private JMenu optmenu=new JMenu("文件");
- private JMenuItem startmenuitem=new JMenuItem("开始");
- private JMenuItem exitmenuitem=new JMenuItem("退出");
- private ActionListener starthandeler=new ActionListener(){
- public void actionPerformed(ActionEvent e){
- cleargrids();
- currcolor=1;
- repaint();
- }
- };
- private ActionListener exithandeler=new ActionListener(){
- public void actionPerformed(ActionEvent e){
- System.exit(0);
- }
- };
- private MouseListener playchesshaneler=new MouseAdapter(){
- public void MouseClicked(MouseEvent e){
- int x=e.getX();
- int y=e.getY();
- if(x<grids*space && x>=0 && y<grids*space && y>=0){
- if(chesses[round(x)][round(y)]==0){
- chesses[round(x)][round(y)]=currcolor;
- currcolor=currcolor==1?2:1;
- repaint();
- }
- }
- }
- };
- public int round(float a){
- float f=a/space;
- return Math.round(f);
- }
- public ChessPanel(int space,int grids){
- this.space=space;
- this.grids=grids;
- this.radios=space/2;
- setBackground(Color.YELLOW);
- setSize(space*grids,space*grids);
- startmenuitem.addActionListener(starthandeler);
- exitmenuitem.addActionListener(exithandeler);
- addMouseListener(playchesshaneler);
- chessmenubar.add(optmenu);
- optmenu.add(startmenuitem);
- optmenu.add(exitmenuitem);
- }
- public JMenuBar getMenuBar(){
- return chessmenubar;
- }
- private void drawchess(Graphics g,int x,int y,int color){
- g.setColor(color==1?Color.WHITE:Color.BLACK);
- g.fillOval(x*space-radios, y*space-radios, radios*2, radios*2);
- }
- public void drawGirds(Graphics g){
- g.setColor(Color.DARK_GRAY);
- for(int i=0;i<=grids;i++){
- g.drawLine(0, i*space, grids*space, i*space);
- g.drawLine(i*space, 0, i*space, grids*space);
- }
- }
- public void cleargrids(){
- for(int i=0;i<grids;i++)
- for(int j=0;j<=grids;j++)
- chesses[i][j]=0;
- }
- public void paintComponent(Graphics g){
- super.paintComponent(g);
- drawGirds(g);
- for(int i=0;i<=grids;i++)
- for(int j=0;j<=grids;j++)
- if(chesses[i][j]!=0)
- drawchess(g,i,j,chesses[i][j]);
- }
- }
- public class ChessPlayer extends JFrame{
- private ChessPanel chesspanel=new ChessPanel(20,30);
- public ChessPlayer(String title){
- super(title);
- Container contentpane=getContentPane();
- contentpane.add(chesspanel);
- setJMenuBar(chesspanel.getMenuBar());
- setSize(600,600);
- setVisible(true);
- setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- }
- public static void main(String args[]){
- new ChessPlayer("五子棋");
- }
- }
java五子棋游戏 代码
最新推荐文章于 2024-06-07 17:07:52 发布