Como você pode fazer jogo da vida no Excel? [fechadas]
-
21-08-2019 - |
Pergunta
Só conheço pouco como fazer macros no Excel.
Solução
Deveria ter feito isso há muito tempo, mas aqui é a minha versão da Vida de Conway em excel.
Aqui está um hack do código. De maneira nenhuma uma solução perfeita (não gastar uma idade sobre isso), mas você pode ser capaz de pegar alguns pedaços para fora.
Private arrGrid(100, 100) As Boolean
Private arrGridNextGeneration(100, 100) As Boolean
Private Sub PopulateParentArrayData()
For k = 1 To Sheet1.Range("C2:AM20").Cells.Count
If Sheet1.Range("C2:AM20").Cells(k).Interior.Color = Sheet1.Range("A1").Interior.Color Then
arrGrid(Sheet1.Range("C2:AM20").Cells(k).Row, Sheet1.Range("C2:AM20").Cells(k).Column) = True
Else
arrGrid(Sheet1.Range("C2:AM20").Cells(k).Row, Sheet1.Range("C2:AM20").Cells(k).Column) = False
End If
DoEvents
Next
End Sub
Private Sub ApplyParentArrayData()
For k = 1 To Sheet1.Range("C2:AM20").Cells.Count
If arrGrid(Sheet1.Range("C2:AM20").Cells(k).Row, Sheet1.Range("C2:AM20").Cells(k).Column) Then
Sheet1.Range("C2:AM20").Cells(k).Interior.Color = Sheet1.Range("A1").Interior.Color
Else
Sheet1.Range("C2:AM20").Cells(k).Interior.Color = Sheet1.Range("B1").Interior.Color
End If
DoEvents
Next
End Sub
Private Sub ApplyNextGenerationArrayData()
For k = 1 To Sheet1.Range("C2:AM20").Cells.Count
If arrGridNextGeneration(Sheet1.Range("C2:AM20").Cells(k).Row, Sheet1.Range("C2:AM20").Cells(k).Column) Then
Sheet1.Range("C2:AM20").Cells(k).Interior.Color = Sheet1.Range("A1").Interior.Color
Else
Sheet1.Range("C2:AM20").Cells(k).Interior.Color = Sheet1.Range("B1").Interior.Color
End If
DoEvents
Next
End Sub
Private Function GetNeighbourCount(ByVal pintRow As Integer, ByVal pintColumn As Integer) As Integer
Dim intCount As Integer
intCount = 0
For r = pintRow - 1 To pintRow + 1
For c = pintColumn - 1 To pintColumn + 1
If r <> pintRow Or c <> pintColumn Then
If arrGrid(r, c) Then
intCount = intCount + 1
End If
End If
Next c
Next r
GetNeighbourCount = intCount
End Function
Private Sub PopulateNextGenerationArray()
Dim intNeighbours As Integer
For r = 0 To 100
For c = 0 To 100
If r > Sheet1.Range("C2:AM20").Rows(0).Row Then
If r <= Sheet1.Range("C2:AM20").Rows(Sheet1.Range("C2:AM20").Rows.Count).Row Then
If c > Sheet1.Range("C2:AM20").Columns(0).Column Then
If c <= Sheet1.Range("C2:AM20").Columns(Sheet1.Range("C2:AM20").Columns.Count).Column Then
intNeighbours = GetNeighbourCount(r, c)
If arrGrid(r, c) Then
'A1 cell
If intNeighbours < 2 Or intNeighbours > 3 Then
arrGridNextGeneration(r, c) = False
Else
arrGridNextGeneration(r, c) = True
End If
Else
'B1 cell
If intNeighbours = 3 Then
arrGridNextGeneration(r, c) = True
Else
arrGridNextGeneration(r, c) = False
End If
End If
End If
End If
End If
End If
DoEvents
Next c
Next r
End Sub
Private Sub ActionLogic()
'Application.ScreenUpdating = False
PopulateParentArrayData
PopulateNextGenerationArray
ApplyNextGenerationArrayData
'Application.ScreenUpdating = True
End Sub
Para chegar a este trabalho apenas fazer o fundo da célula A1 preto, o fundo da célula B1 branco e, em seguida, adicionar alguns fundos pretos no intervalo C2:. AM20 e executar o método ActionLogic
Outras dicas
Você pode encontrar muitos exemplos através do Google.
O primeiro resultado é um post de blog de David Gainer que usa Jogo da Vida de Conway para ensinar sobre fórmulas de referência circular e iteração (sem VBA envolvidos):
http://blogs.office.com / 2007/11/02 / iteração-Conways-game-of-life
Você vai precisar de dois macros. O primeiro deverá formatar a folha de jogo, então as células são quadrado.
Ter o usuário executar essa macro. Depois disso, ela deve entrar em um 1 para cada célula que está vivo. Use formatação condicional para transformar a célula completamente preto (fundo = preto se o valor! = 0)
Agora tem uma segunda macro que calcula o próximo passo em uma folha de fundo (outra folha). Use posicionamento relativo de células (em relação ao ActiveCell) e dois circuitos encaixados. Quando isso é feito, copiar todos os valores da folha de fundo para a folha de jogo.
Procure-lo e olhar para o seu código. Muitas pessoas fizeram um hobby para fazer jogos completos no Excel.
Por que você diz Excel é a escolha errada?
Eu acho que Excel é a melhor maneira de resolver este:
Excel resolve isso com uma linha: IF (OU (SUM (B2: D4) C3 = 3, E (SUM (B2: D4) C3 = 2, C3 = 1)), 1,0)
* onde o acima é uma expressão que devolve o valor próxima geração para a célula C3.
Aqui está a demonstração: https://docs.google.com/open?id=0B4FcWULw3iQidlZSdG9GRDh0TXM
Se você estiver em uma situação onde você tem que implementar este tipo de coisas a partir do zero, em seguida, a programação funcional é o melhor caminho a percorrer. Caso contrário, o Excel funciona muito bem. Por quê? Porque o Excel é um sistema que obriga a inserir funções só puros. Você vê, a chave para simular este jogo da vida é perceber que cada estado das células é uma pura função do estado anterior. Excel naturalmente obriga a pensar desta forma.
outro tutorial sobre referências circulares em excel pode ser encontrada aqui: http://chandoo.org/wp/2009/01/08/timestamps-excel-formula-help/
este explica como você pode inserir marcas de tempo usando referências circulares.
Excel é definitivamente a escolha errada para este tipo de problema. Quanto à forma como seria possível: Primeiro aprender sobre o jogo de vida e depois < a href = "http://en.wikipedia.org/wiki/Visual_Basic" rel = "nofollow noreferrer"> visual basic para uso em Excel.