DHEIVER commited on
Commit
9f39510
·
verified ·
1 Parent(s): 94ea014

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +115 -94
app.py CHANGED
@@ -1,7 +1,6 @@
1
  import gradio as gr
2
  import numpy as np
3
- import matplotlib.pyplot as plt
4
- import random
5
 
6
  class Minesweeper:
7
  def __init__(self, width=8, height=8, num_mines=10):
@@ -81,126 +80,148 @@ class Minesweeper:
81
  elif self.visible_board[x, y] == -1:
82
  self.visible_board[x, y] = -2
83
 
84
- def create_board_image(game):
85
- fig, ax = plt.subplots(figsize=(8, 8))
86
-
87
- colors = {
88
- -2: '#CCCCCC', # Coberto
89
- -1: '#FF0000', # Bandeira/Mina
90
- 0: '#FFFFFF', # Vazio
91
- 1: '#0000FF', # Azul
92
- 2: '#008000', # Verde
93
- 3: '#FF0000', # Vermelho
94
- 4: '#000080', # Azul escuro
95
- 5: '#800000', # Vermelho escuro
96
- 6: '#008080', # Ciano
97
- 7: '#000000', # Preto
98
- 8: '#808080' # Cinza
99
  }
100
 
101
- for i in range(game.height):
102
- for j in range(game.width):
103
- color = colors[game.visible_board[i, j]]
104
- ax.add_patch(plt.Rectangle((j, game.height-1-i), 1, 1, facecolor=color, edgecolor='black'))
105
-
106
- if game.visible_board[i, j] > 0:
107
- plt.text(j+0.5, game.height-1-i+0.5, str(game.visible_board[i, j]),
108
- horizontalalignment='center',
109
- verticalalignment='center',
110
- color='black')
111
- elif game.visible_board[i, j] == -1:
112
- plt.text(j+0.5, game.height-1-i+0.5, 'F',
113
- horizontalalignment='center',
114
- verticalalignment='center',
115
- color='black')
116
-
117
- if game.game_over:
118
- for i in range(game.height):
119
- for j in range(game.width):
120
- if game.board[i, j] == -1:
121
- ax.add_patch(plt.Rectangle((j, game.height-1-i), 1, 1, facecolor='red', edgecolor='black'))
122
- plt.text(j+0.5, game.height-1-i+0.5, 'M',
123
- horizontalalignment='center',
124
- verticalalignment='center',
125
- color='black')
126
-
127
- ax.set_xlim(0, game.width)
128
- ax.set_ylim(0, game.height)
129
- ax.set_xticks(range(game.width))
130
- ax.set_yticks(range(game.height))
131
- ax.grid(True)
132
-
133
- status = "Jogando"
134
  if game.game_over:
135
- status = "Game Over!"
136
  elif game.won:
137
- status = "Você Venceu!"
138
 
139
- plt.title(f'Campo Minado - {status}')
140
- return fig
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
 
142
- def make_move(x, y, action, game_state):
143
  if not game_state:
144
- game = Minesweeper(8, 8, 10)
145
  else:
146
- game = Minesweeper(8, 8, 10)
147
  game.__dict__ = game_state
148
 
149
  if action == "reveal":
150
- game.reveal(x, y)
151
  else:
152
- game.toggle_flag(x, y)
153
 
154
- fig = create_board_image(game)
155
- status = "Jogando"
156
- if game.game_over:
157
- status = "Game Over!"
158
- elif game.won:
159
- status = "Você Venceu!"
160
-
161
- return fig, game.__dict__, status
162
 
163
  def new_game():
164
- game = Minesweeper(8, 8, 10)
165
- fig = create_board_image(game)
166
- return fig, game.__dict__, "Novo jogo iniciado!"
167
 
168
  with gr.Blocks(title="Campo Minado") as demo:
169
  gr.Markdown("""
170
  # Campo Minado
171
 
172
  Instruções:
173
- 1. Digite as coordenadas (0-7) para linha e coluna
174
- 2. Escolha "Revelar" para abrir uma célula ou "Bandeira" para marcar uma mina
175
- 3. Evite as minas e revele todas as células seguras!
176
  """)
177
 
178
  game_state = gr.State()
179
- board = gr.Plot(label="Tabuleiro")
180
- status = gr.Textbox(label="Status do Jogo", interactive=False)
181
-
182
- with gr.Row():
183
- x_coord = gr.Number(label="Linha (0-7)", minimum=0, maximum=7, step=1)
184
- y_coord = gr.Number(label="Coluna (0-7)", minimum=0, maximum=7, step=1)
185
 
186
  with gr.Row():
187
- reveal_btn = gr.Button("Revelar")
188
- flag_btn = gr.Button("Bandeira")
189
  new_game_btn = gr.Button("Novo Jogo")
190
 
191
- reveal_btn.click(
192
- make_move,
193
- inputs=[x_coord, y_coord, gr.Textbox(value="reveal", visible=False), game_state],
194
- outputs=[board, game_state, status]
195
- )
196
-
197
- flag_btn.click(
198
- make_move,
199
- inputs=[x_coord, y_coord, gr.Textbox(value="flag", visible=False), game_state],
200
- outputs=[board, game_state, status]
201
- )
202
 
203
- new_game_btn.click(new_game, outputs=[board, game_state, status])
204
- demo.load(new_game, outputs=[board, game_state, status])
205
 
206
  demo.launch()
 
1
  import gradio as gr
2
  import numpy as np
3
+ import json
 
4
 
5
  class Minesweeper:
6
  def __init__(self, width=8, height=8, num_mines=10):
 
80
  elif self.visible_board[x, y] == -1:
81
  self.visible_board[x, y] = -2
82
 
83
+ def create_game_html(game):
84
+ # Cores para diferentes estados das células
85
+ cell_styles = {
86
+ -2: "background-color: #ccc;", # Coberto
87
+ -1: "background-color: #f00;", # Bandeira
88
+ 0: "background-color: #fff;", # Vazio
89
+ 1: "background-color: #fff; color: blue;",
90
+ 2: "background-color: #fff; color: green;",
91
+ 3: "background-color: #fff; color: red;",
92
+ 4: "background-color: #fff; color: darkblue;",
93
+ 5: "background-color: #fff; color: darkred;",
94
+ 6: "background-color: #fff; color: teal;",
95
+ 7: "background-color: #fff; color: black;",
96
+ 8: "background-color: #fff; color: gray;"
 
97
  }
98
 
99
+ html = """
100
+ <style>
101
+ .minesweeper-board {
102
+ display: inline-block;
103
+ border: 2px solid #999;
104
+ background-color: #eee;
105
+ padding: 10px;
106
+ }
107
+ .board-row {
108
+ display: flex;
109
+ }
110
+ .cell {
111
+ width: 40px;
112
+ height: 40px;
113
+ border: 1px solid #999;
114
+ display: flex;
115
+ align-items: center;
116
+ justify-content: center;
117
+ font-weight: bold;
118
+ font-size: 20px;
119
+ cursor: pointer;
120
+ user-select: none;
121
+ }
122
+ .game-over .cell {
123
+ cursor: not-allowed;
124
+ }
125
+ </style>
126
+
127
+ <div class="minesweeper-board">
128
+ """
129
+
130
+ # Adicionar status do jogo
 
131
  if game.game_over:
132
+ html += '<div style="text-align: center; margin-bottom: 10px; color: red; font-weight: bold;">Game Over!</div>'
133
  elif game.won:
134
+ html += '<div style="text-align: center; margin-bottom: 10px; color: green; font-weight: bold;">Você Venceu!</div>'
135
 
136
+ # Criar tabuleiro
137
+ for i in range(game.height):
138
+ html += '<div class="board-row">'
139
+ for j in range(game.width):
140
+ cell_value = game.visible_board[i, j]
141
+ style = cell_styles[cell_value]
142
+
143
+ # Se o jogo acabou, mostrar as minas
144
+ if game.game_over and game.board[i, j] == -1:
145
+ cell_content = "💣"
146
+ style = "background-color: #f00;"
147
+ # Se é uma bandeira
148
+ elif cell_value == -1:
149
+ cell_content = "🚩"
150
+ # Se está coberto
151
+ elif cell_value == -2:
152
+ cell_content = ""
153
+ # Se é um número
154
+ else:
155
+ cell_content = str(cell_value) if cell_value > 0 else ""
156
+
157
+ html += f'<div class="cell" style="{style}" data-x="{i}" data-y="{j}">{cell_content}</div>'
158
+ html += '</div>'
159
+ html += '</div>'
160
+
161
+ # Adicionar JavaScript para handling de cliques
162
+ html += """
163
+ <script>
164
+ function handleCellClick(event) {
165
+ const cell = event.target;
166
+ if (!cell.classList.contains('cell')) return;
167
+
168
+ const x = cell.getAttribute('data-x');
169
+ const y = cell.getAttribute('data-y');
170
+
171
+ if (event.button === 2 || event.ctrlKey) { // Clique direito ou Ctrl+Clique
172
+ handleAction(x, y, 'flag');
173
+ } else { // Clique esquerdo
174
+ handleAction(x, y, 'reveal');
175
+ }
176
+ }
177
+
178
+ document.querySelector('.minesweeper-board').addEventListener('click', handleCellClick);
179
+ document.querySelector('.minesweeper-board').addEventListener('contextmenu', (e) => {
180
+ e.preventDefault();
181
+ handleCellClick(e);
182
+ });
183
+ </script>
184
+ """
185
+
186
+ return html
187
 
188
+ def handle_action(x, y, action, game_state):
189
  if not game_state:
190
+ game = Minesweeper()
191
  else:
192
+ game = Minesweeper()
193
  game.__dict__ = game_state
194
 
195
  if action == "reveal":
196
+ game.reveal(int(x), int(y))
197
  else:
198
+ game.toggle_flag(int(x), int(y))
199
 
200
+ return create_game_html(game), game.__dict__
 
 
 
 
 
 
 
201
 
202
  def new_game():
203
+ game = Minesweeper()
204
+ return create_game_html(game), game.__dict__
 
205
 
206
  with gr.Blocks(title="Campo Minado") as demo:
207
  gr.Markdown("""
208
  # Campo Minado
209
 
210
  Instruções:
211
+ - Clique esquerdo para revelar uma célula
212
+ - Clique direito (ou Ctrl+Clique) para colocar/remover bandeira
213
+ - Evite as minas!
214
  """)
215
 
216
  game_state = gr.State()
217
+ board = gr.HTML()
 
 
 
 
 
218
 
219
  with gr.Row():
 
 
220
  new_game_btn = gr.Button("Novo Jogo")
221
 
222
+ board.change(handle_action, [board], [board, game_state]) # Para atualização após cliques
223
+ new_game_btn.click(new_game, outputs=[board, game_state])
 
 
 
 
 
 
 
 
 
224
 
225
+ demo.load(new_game, outputs=[board, game_state])
 
226
 
227
  demo.launch()