Skip to content

Instantly share code, notes, and snippets.

@wasabili
Created October 31, 2010 04:39
Show Gist options
  • Save wasabili/656134 to your computer and use it in GitHub Desktop.
Save wasabili/656134 to your computer and use it in GitHub Desktop.
Othello
import java.net.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class Othello{
public static final int WHITE=-1;
public static final int BLACK=1;
public static final int INVALID=-2;
public static final int NONE=0;
public int board[][] = new int[8][8];
private int dirs[] = {1,0,-1};
public int turn;
public Othello(){
for(int i=0;i<8;i++) for(int j=0;j<8;j++) board[i][j] = NONE;
board[4][4]=board[3][3]=WHITE;
board[4][3]=board[3][4]=BLACK;
turn = BLACK;
}
public int getStone(int x,int y){
if(0<=x&&x<8&&0<=y&&y<8) return board[x][y];
else return INVALID;
}
public boolean canPut(int x,int y,int self){
if(getStone(x,y)!=NONE) return false;
for(int xd:dirs){
for(int yd:dirs){
if(xd==0&&yd==0) continue;
if(getStone(x+xd,y+yd)==-self){
for(int xs=x+xd*2,ys=y+yd*2;true;xs+=xd,ys+=yd){
int stone = getStone(xs,ys);
if(stone == INVALID || stone==NONE) break;
else if(stone == self) return true;
}
}
}
}
return false;
}
public void put(int x,int y,int self){
ArrayList<Point> rev = new ArrayList<Point>();
board[x][y] = self;
for(int xd:dirs){
for(int yd:dirs){
if(xd==0&&yd==0) continue;
if(getStone(x+xd,y+yd)==-self){
rev.add(new Point(x+xd,y+yd));
for(int xs=x+xd*2,ys=y+yd*2;true;xs+=xd,ys+=yd){
int stone = getStone(xs,ys);
if(stone == INVALID || stone == NONE){
rev.clear();
break;
}else if(stone == self){
for(Point p:rev) board[p.x][p.y]*=-1;
rev.clear();
break;
}else if(stone == -self){
rev.add(new Point(xs,ys));
}
}
}
}
}
}
public void changeTurn(){
turn *= -1;
}
public void setTurn(int turn){
this.turn = turn;
}
public void display(){
for(int[] line:board){
for(int p:line){
String s="";
if(p==BLACK) s = "黒";
else if(p==WHITE) s = "白";
else if(p==NONE) s = "・";
System.out.print(s);
}
System.out.println();
}
}
public static void main(String[] args){
Othello oth = new Othello();
while(true){
oth.display();
Scanner sc = new Scanner(System.in);
int x = sc.nextInt();
int y = sc.nextInt();
if(oth.canPut(x,y,oth.turn)){
oth.put(x,y,oth.turn);
oth.changeTurn();
System.out.println("Put "+oth.turn);
}else {
System.out.println("Cannot put there");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment