sehsapneb commited on
Commit
74594d1
·
verified ·
1 Parent(s): 21c18be

Rename ai_server.py to game_logic.py

Browse files
Files changed (2) hide show
  1. ai_server.py +0 -6
  2. game_logic.py +188 -0
ai_server.py DELETED
@@ -1,6 +0,0 @@
1
- from flask import Flask
2
- app = Flask(__name__)
3
-
4
- @app.route('/')
5
- def hello():
6
- return "Minimal Flask App Test"
 
 
 
 
 
 
 
game_logic.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # game_logic.py
2
+ import numpy as np
3
+ import random
4
+ import math
5
+
6
+ # --- PARSING ---
7
+ def parse_board_hex(hex_string: str) -> np.ndarray:
8
+ """Converts 16-char hex string (exponents) to 4x4 numpy array (values)."""
9
+ if len(hex_string) != 16:
10
+ raise ValueError("Board string must be 16 characters long")
11
+ board = np.zeros((4, 4), dtype=int)
12
+ for i, char in enumerate(hex_string):
13
+ exponent = int(char, 16)
14
+ value = 0
15
+ if exponent > 0:
16
+ # handle potential float issues with 2**exp for large numbers
17
+ value = 1 << exponent # 2**exponent
18
+ row, col = divmod(i, 4)
19
+ board[row, col] = value
20
+ return board
21
+
22
+ def get_empty_cells(board: np.ndarray):
23
+ """Returns a list of (row, col) tuples for empty cells."""
24
+ return list(zip(*np.where(board == 0)))
25
+
26
+ # --- MOVE LOGIC ---
27
+ # Core idea: implement move_left, all others are transformations
28
+
29
+ def _compress(row):
30
+ """Move all non-zero tiles to the left."""
31
+ new_row = [i for i in row if i != 0]
32
+ new_row.extend([0] * (4 - len(new_row)))
33
+ return new_row
34
+
35
+ def _merge(row):
36
+ """Merge identical adjacent tiles (left to right), returns new row and score gained."""
37
+ score = 0
38
+ new_row = list(row) # copy
39
+ for i in range(3):
40
+ if new_row[i] == new_row[i+1] and new_row[i] != 0:
41
+ new_row[i] *= 2
42
+ score += new_row[i]
43
+ new_row[i+1] = 0
44
+ return new_row, score
45
+
46
+ def move_left(board: np.ndarray):
47
+ """Executes a left move, returns (new_board, changed, score_gained)."""
48
+ new_board = np.zeros_like(board)
49
+ total_score = 0
50
+ changed = False
51
+ for i in range(4):
52
+ row = board[i]
53
+ compressed_row = _compress(row)
54
+ merged_row, score = _merge(compressed_row)
55
+ final_row = _compress(merged_row) # Compress again after merge
56
+ new_board[i] = final_row
57
+ total_score += score
58
+ if not np.array_equal(row, final_row):
59
+ changed = True
60
+ return new_board, changed, total_score
61
+
62
+ # Transformations for other moves
63
+ def _transpose(board):
64
+ return np.transpose(board)
65
+
66
+ def _reverse_rows(board):
67
+ return np.array([row[::-1] for row in board])
68
+
69
+ def move_right(board: np.ndarray):
70
+ reversed_board = _reverse_rows(board)
71
+ new_board, changed, score = move_left(reversed_board)
72
+ return _reverse_rows(new_board), changed, score
73
+
74
+ def move_up(board: np.ndarray):
75
+ transposed_board = _transpose(board)
76
+ new_board, changed, score = move_left(transposed_board)
77
+ return _transpose(new_board), changed, score
78
+
79
+ def move_down(board: np.ndarray):
80
+ transposed_board = _transpose(board)
81
+ new_board, changed, score = move_right(transposed_board) # Use move_right on transposed
82
+ return _transpose(new_board), changed, score
83
+
84
+ MOVE_MAP = {
85
+ 'u': move_up,
86
+ 'd': move_down,
87
+ 'l': move_left,
88
+ 'r': move_right,
89
+ }
90
+ DIRECTIONS = ['u', 'd', 'l', 'r']
91
+
92
+ def get_possible_moves(board: np.ndarray):
93
+ """Returns a list of (direction_char, new_board, score) for all VALID moves."""
94
+ possible = []
95
+ for direction in DIRECTIONS:
96
+ move_func = MOVE_MAP[direction]
97
+ new_board, changed, score = move_func(board)
98
+ if changed:
99
+ possible.append({'dir': direction, 'board': new_board, 'score': score})
100
+ return possible
101
+
102
+ def is_game_over(board: np.ndarray):
103
+ """Check if any move is possible."""
104
+ if get_empty_cells(board): # If there are empty cells, moves are possible
105
+ return False
106
+ # check if any adjacent tiles can merge
107
+ for move_func in MOVE_MAP.values():
108
+ _, changed, _ = move_func(board)
109
+ if changed:
110
+ return False
111
+ return True # No empty cells and no merges possible
112
+
113
+ # --- HEURISTIC EVALUATION ---
114
+ # CRITICAL: A good AI needs a good heuristic!
115
+ # Score alone is bad. Combine score, empty cells, smoothness, monotonicity.
116
+
117
+ def evaluate_board(board: np.ndarray, score_gained:int=0) -> float:
118
+ """ Assign a score to a board state. Higher is better."""
119
+ empty_cells = len(get_empty_cells(board))
120
+ if empty_cells == 0 and is_game_over(board):
121
+ return -100000.0 # Severe penalty for game over
122
+
123
+ # Simple heuristic: prioritise empty cells and add score
124
+ # More complex: add penalties if large tiles are not in corners,
125
+ # or if rows/cols are not monotonic (always increasing or decreasing)
126
+ # or if adjacent tiles have large differences (smoothness)
127
+
128
+ # Calculate smoothness penalty (difference between neighbours)
129
+ smoothness_penalty = 0
130
+ for r in range(4):
131
+ for c in range(4):
132
+ if board[r,c] > 0:
133
+ log_val = math.log2(board[r,c])
134
+ # Check right
135
+ if c + 1 < 4 and board[r, c+1] > 0:
136
+ smoothness_penalty += abs(log_val - math.log2(board[r, c+1]))
137
+ # Check down
138
+ if r + 1 < 4 and board[r+1, c] > 0:
139
+ smoothness_penalty += abs(log_val - math.log2(board[r+1, c]))
140
+
141
+ # Very basic Monotonicity (penalty if not increasing/decreasing)
142
+ # This could be much more sophisticated (e.g., snake pattern)
143
+ mono_penalty = 0
144
+ # Columns
145
+ for c in range(4):
146
+ for r in range(3):
147
+ if board[r,c] > 0 and board[r+1,c] > 0 and board[r+1,c] > board[r,c] : # decreasing down
148
+ mono_penalty += math.log2(board[r+1,c]) - math.log2(board[r,c])
149
+ # Could add check for increasing too
150
+ # Rows
151
+ for r in range(4):
152
+ for c in range(3):
153
+ if board[r,c] > 0 and board[r,c+1] > 0 and board[r, c+1] > board[r,c]: # decreasing right
154
+ mono_penalty += math.log2(board[r,c+1]) - math.log2(board[r,c])
155
+ # Could add check for increasing too
156
+
157
+ # Max tile value bonus
158
+ max_tile_bonus = math.log2(board.max()) if board.max() > 0 else 0
159
+
160
+ # Weights - TUNE THESE!
161
+ EMPTY_WEIGHT = 200.0
162
+ SMOOTH_WEIGHT = 0.5
163
+ MONO_WEIGHT = 1.5
164
+ MAX_TILE_WEIGHT = 1.0
165
+ # SCORE_WEIGHT = 1.0 # Using score directly can be misleading, prefer structural properties
166
+
167
+ # Avoid log2(0) if board is all zero
168
+ if board.max() == 0: return 0.0
169
+
170
+ heuristic_score = (
171
+ empty_cells * EMPTY_WEIGHT
172
+ # + score_gained * SCORE_WEIGHT # score gained on the move leading here
173
+ + max_tile_bonus * MAX_TILE_WEIGHT
174
+ - smoothness_penalty * SMOOTH_WEIGHT
175
+ - mono_penalty * MONO_WEIGHT
176
+ )
177
+
178
+ return heuristic_score
179
+
180
+ # Example usage for testing
181
+ # if __name__ == "__main__":
182
+ # b = parse_board_hex("0000000000100010")
183
+ # print("Start:\n", b)
184
+ # nb, ch, sc = move_up(b)
185
+ # print("Up:\n", nb, ch, sc)
186
+ # print("Score:", evaluate_board(nb, sc))
187
+ # print("Possible:", [p['dir'] for p in get_possible_moves(b)])
188
+ # print("GameOver:", is_game_over(parse_board_hex("123456789ABCDEFA")))