Tic-Tac-Toe My first attemp in the small world of J2ME... SampleMIDlet.java /* * SampleMIDlet.java * * Created on December 16, 2002, 3:29 PM */ package com.mlw.me.tictactoe; import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import javax.microedition.midlet.MIDlet; /** * * @author Matthew Wilson * @version */ public class SampleMIDlet extends MIDlet { private Display display; private TickTacToeScreen canvas; public SampleMIDlet(){ display = Display.getDisplay( this ); canvas = new TickTacToeScreen( this ); } protected void startApp(){ display.setCurrent( canvas ); } protected void pauseApp(){ } protected void destroyApp( boolean unconditional ){ } public void exit(){ destroyApp( true ); notifyDestroyed(); } } Figure 1 TickTacToeScreen.java /* * TickTacToeScreen.java * * Created on December 16, 2002, 3:39 PM */ package com.mlw.me.tictactoe; import javax.microedition.midlet.*; import javax.microedition.lcdui.*; /** * * @author Matthew Wilson * @version */ public class TickTacToeScreen extends Canvas { private String[] message = {"'O', you won!","'X', you won!"}; private int winner = 0; private int turn = 1; private int thirdWidth = getWidth()/3; private int thirdHeight = getHeight()/3; private MIDlet midlet; private int[][] board = new int[3][3]; public TickTacToeScreen( MIDlet midlet ) { this.midlet = midlet; } protected void paint( Graphics g ) { g.setColor( 255, 255, 255 ); g.fillRect( 0, 0, getWidth(), getHeight() ); g.setColor( 0, 0, 0 ); for( int i=1; i<3; i++) { g.drawLine( 0, i*thirdHeight, getWidth(), i*thirdHeight ); g.drawLine( i*thirdWidth, 0, i*thirdWidth, getHeight() ); } for( int x=0; x<3; x++) { for( int y=0; y<3; y++) { if( board[x][y]==1) { g.fillRoundRect( x*thirdWidth, y*thirdHeight, thirdWidth, thirdHeight, thirdWidth, thirdHeight ); } else if( board[x][y]==2) { g.drawLine( x*thirdWidth, (y+0)*thirdHeight, (x+1)*thirdWidth, (y+1)*thirdHeight ); g.drawLine( x*thirdWidth, (y+1)*thirdHeight, (x+1)*thirdWidth, (y+0)*thirdHeight ); } } } if( winner > 0 ) { g.setColor( 255, 255, 255 ); for( int i=-1; i<2; i++) { g.drawString(message[winner-1],i+15,thirdHeight+8, Graphics.TOP|Graphics.LEFT); g.drawString(message[winner-1],15,thirdHeight+8+i, Graphics.TOP|Graphics.LEFT); } g.setColor( 0, 0, 0 ); g.drawString(message[winner-1],15,thirdHeight+8, Graphics.TOP|Graphics.LEFT); } } protected void keyPressed( int keyCode ) { if( winner > 0 ) { keyCode=-8; } if( keyCode==-10 ) { AI ai = new AI(board); int[] best = ai.process(turn+1); keyCode = ((best[1]*3) + best[0] + 49); } if( keyCode== -8 ) { for( int x=0; x<3; x++) for( int y=0; y<3; y++) board[x][y]=0; winner = AI.getWinner(board); repaint(); } else { keyCode -= 49; if( keyCode >=0 ) { if( board[keyCode%3][keyCode/3] == 0 ) { board[keyCode%3][keyCode/3] = turn+1; turn = (turn+1)%2; repaint(); } if( (winner = AI.getWinner(board)) > 0 ) { repaint(); } } } } } Figure 2