Skip to content

Instantly share code, notes, and snippets.

@panchishin
Created July 30, 2021 14:32
Show Gist options
  • Save panchishin/7fa82e5994e402438cccc69eb21d883b to your computer and use it in GitHub Desktop.
Save panchishin/7fa82e5994e402438cccc69eb21d883b to your computer and use it in GitHub Desktop.
Basic tic tac tow with random move unless the next move could win
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <bitset>
using namespace std;
int main() {
int me = 0b000'000'000;
// game loop
while (1) {
int winners[] = {
0b000'000'111, 0b000'111'000, 0b111'000'000, // row
0b001'001'001, 0b010'010'010, 0b100'100'100, // col
0b100'010'001, 0b001'010'100 // x
};
int opponentRow;
int opponentCol;
cin >> opponentRow >> opponentCol; cin.ignore();
int validActionCount;
cin >> validActionCount; cin.ignore();
int answer_row = -1;
int answer_col = -1;
int row;
int col;
for (int i = 0; i < validActionCount; i++) {
cin >> row >> col; cin.ignore();
// pick the first move incase there isn't a winning move
if (answer_row == -1){
answer_row = row;
answer_col = col;
}
int position = row * 3 + col;
int position_bit = 0b1 << position;
int move = me | position_bit;
for(int j=0;j<8;j++){
// replace with winning move
if(winners[j] == (winners[j] & move)){
answer_row = row;
answer_col = col;
}
}
}
int position = answer_row * 3 + answer_col;
int position_bit = 0b1 << position;
me = (me | 0b1 << position);
cout << answer_row << " " << answer_col << endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment