PC SOFT

FOROS PROFESIONALES
WINDEVWEBDEV y WINDEV Mobile

Inicio → WINDEV 25 → Jogo Pac Man em WLanguage
Jogo Pac Man em WLanguage
Iniciado por Boller, 17,mar. 2025 14:35 - 1 respuesta
Miembro registrado
4.520 mensajes
Publicado el 17,marzo 2025 - 14:35
Hi,

### Pac-Man Game in WLanguage (English Code)

#### 1. Project Setup
- Use WINDEV to create a new project with a main window (`WINDOW_Game`).
- Set a fixed resolution, e.g., 800x600 pixels.

#### 2. Global Declarations
Define the maze and Pac-Man's initial position in the global code of the window:

```wlanguage
// Global maze array (5x5 for simplicity: 0 = path, 1 = wall, 2 = pellet)
Maze is an array of 5, 5 of integer
Maze = [
[1, 1, 1, 1, 1],
[1, 0, 0, 0, 1],
[1, 0, 1, 0, 1],
[1, 0, 0, 0, 1],
[1, 1, 1, 1, 1]
]

// Pac-Man's initial position (0-based index)
PacmanX is an integer = 1 // Column
PacmanY is an integer = 1 // Row
CellSize is an integer = 50 // Size of each cell in pixels
Score is an integer = 0 // Player score
```

#### 3. Drawing the Game
Create a procedure to draw the maze and Pac-Man:

```wlanguage
// Procedure to draw the game
PROCEDURE DrawGame()
// Clear the window
dClear(WINDOW_Game)

// Draw the maze
FOR i = 0 TO 4
FOR j = 0 TO 4
IF Maze[i+1, j+1] = 1 THEN
// Draw wall (blue rectangle)
dRectangle(WINDOW_Game, j*CellSize, i*CellSize,
(j+1)*CellSize, (i+1)*CellSize, Blue)
ELSE
// Draw path (black background)
dRectangle(WINDOW_Game, j*CellSize, i*CellSize,
(j+1)*CellSize, (i+1)*CellSize, Black)
// Draw pellet if present (small white circle)
IF Maze[i+1, j+1] = 2 THEN
dCircle(WINDOW_Game, j*CellSize + CellSize/2,
i*CellSize + CellSize/2, 5, White)
END
END
END
END

// Draw Pac-Man (yellow circle)
dCircle(WINDOW_Game, PacmanX*CellSize + CellSize/2,
PacmanY*CellSize + CellSize/2, CellSize/2, Yellow)
END

// Call drawing on window opening
DrawGame()
```

#### 4. Handling Pac-Man Movement
Capture key presses to move Pac-Man and check for collisions or pellets:

```wlanguage
// Key press event for the window
CASE KeyPressed()
WHEN vk_Right // Right arrow
IF PacmanX < 4 AND Maze[PacmanY+1, PacmanX+2] <> 1 THEN
PacmanX += 1
CheckPellet()
DrawGame()
END
WHEN vk_Left // Left arrow
IF PacmanX > 0 AND Maze[PacmanY+1, PacmanX] <> 1 THEN
PacmanX -= 1
CheckPellet()
DrawGame()
END
WHEN vk_Up // Up arrow
IF PacmanY > 0 AND Maze[PacmanY, PacmanX+1] <> 1 THEN
PacmanY -= 1
CheckPellet()
DrawGame()
END
WHEN vk_Down // Down arrow
IF PacmanY < 4 AND Maze[PacmanY+2, PacmanX+1] <> 1 THEN
PacmanY += 1
CheckPellet()
DrawGame()
END
END

// Procedure to check if Pac-Man collects a pellet
PROCEDURE CheckPellet()
IF Maze[PacmanY+1, PacmanX+1] = 2 THEN
Maze[PacmanY+1, PacmanX+1] = 0
Score += 10
Info("Score: " + Score)
END
END
```

#### 5. Adding Pellets
Add some pellets to the maze for Pac-Man to collect:

```wlanguage
// Add pellets to the maze (in global declaration or initialization)
Maze[2, 2] = 2 // Pellet at position (1,1)
Maze[2, 4] = 2 // Pellet at position (1,3)
Maze[4, 2] = 2 // Pellet at position (3,1)
```

#### 6. Optional Enhancements
- **Ghosts**: Add ghost positions (e.g., `GhostX`, `GhostY`) and move them with a timer:
```wlanguage
// Global ghost variables
GhostX is an integer = 3
GhostY is an integer = 3

// Timer to move ghost (e.g., every 500ms)
TimerSys(500, "MoveGhost")

PROCEDURE MoveGhost()
// Simple random movement (example)
Direction is an integer = Random(1, 4)
IF Direction = 1 AND Maze[GhostY, GhostX+1] <> 1 THEN GhostY -= 1
IF Direction = 2 AND Maze[GhostY+2, GhostX+1] <> 1 THEN GhostY += 1
IF Direction = 3 AND Maze[GhostY+1, GhostX] <> 1 THEN GhostX -= 1
IF Direction = 4 AND Maze[GhostY+1, GhostX+2] <> 1 THEN GhostX += 1
DrawGame()
// Check collision with Pac-Man
IF GhostX = PacmanX AND GhostY = PacmanY THEN
Info("Game Over!")
TimerSys(0) // Stop timer
END
END

// Add ghost drawing in DrawGame
dCircle(WINDOW_Game, GhostX*CellSize + CellSize/2,
GhostY*CellSize + CellSize/2, CellSize/2, Red)
```
- **Sound**: Use `SoundPlay` for eating pellets or game over effects.
- **Animation**: Alternate Pac-Man's shape (circle to semi-circle) for a "chomping" effect.

### Final Notes
This code gives you a basic Pac-Man game with a maze, movement, and pellet collection. You can expand it by adding more ghosts, a larger maze, or win/lose conditions. Test it in WINDEV, and let me know if you'd like to refine any part—like adding more features or debugging specific issues! What do you think of this starting point?

--
Adriano José Boller
______________________________________________
Consultor e Representante Oficial da
PcSoft no Brasil
+55 (41) 99949 1800
adrianoboller@gmail.com
skype: adrianoboller
http://wxinformatica.com.br/
Miembro registrado
4.520 mensajes
Publicado el 17,marzo 2025 - 15:09
### Resumo Explicativo do Jogo Pac-Man em WLanguage

O código apresentado cria uma versão simplificada do clássico jogo Pac-Man utilizando WLanguage, a linguagem do ambiente WINDEV. O objetivo é permitir que o jogador controle o Pac-Man em um labirinto, coletando pastilhas e evitando colisões com paredes (e, opcionalmente, fantasmas). Abaixo está uma explicação dos principais componentes:

1. **Estrutura do Projeto**:
- O jogo é desenvolvido em uma janela (`WINDOW_Game`) no WINDEV, com resolução fixa (ex.: 800x600 pixels).
- Tudo é configurado para rodar no ambiente gráfico do WINDEV.

2. **Declarações Globais**:
- O labirinto é representado por uma matriz 5x5 chamada `Maze`, onde:
- `0` = caminho livre,
- `1` = parede,
- `2` = pastilha (pellet).
- Posição inicial do Pac-Man (`PacmanX` e `PacmanY`) é definida como (1,1), e cada célula do labirinto tem tamanho fixo (`CellSize = 50` pixels).
- A pontuação (`Score`) começa em 0.

3. **Desenho do Jogo**:
- A função `DrawGame()` desenha o labirinto e o Pac-Man:
- Paredes são retângulos azuis, caminhos são pretos, e pastilhas são pequenos círculos brancos.
- O Pac-Man é um círculo amarelo que aparece na posição atual (`PacmanX`, `PacmanY`).
- Essa função é chamada ao abrir a janela e após cada movimento.

4. **Movimentação**:
- O evento `KeyPressed()` captura as teclas de seta (cima, baixo, esquerda, direita).
- Antes de mover o Pac-Man, o código verifica se a próxima posição não é uma parede (`Maze[posição] <> 1`).
- Após o movimento, verifica se há uma pastilha na nova posição com `CheckPellet()`, que remove a pastilha e adiciona 10 pontos ao `Score`.

5. **Pastilhas**:
- Algumas posições do labirinto (ex.: (1,1), (1,3), (3,1)) têm pastilhas (`Maze[x, y] = 2`) que o Pac-Man pode coletar.
- Ao coletar, a pontuação é exibida via `Info`.

6. **Expansões Opcionais**:
- **Fantasmas**: Um exemplo básico adiciona um fantasma (círculo vermelho) que se move aleatoriamente com um temporizador (`TimerSys`). Se colidir com o Pac-Man, o jogo termina.
- Outras melhorias sugeridas incluem sons, animação do Pac-Man e condições de vitória/derrota.

### Como Funciona
- O jogador usa as setas para mover o Pac-Man pelo labirinto.
- O objetivo é coletar pastilhas sem bater nas paredes.
- O jogo é simples, mas pode ser expandido com mais funcionalidades, como múltiplos fantasmas ou um labirinto maior.

Esse código é um ponto de partida funcional. Para torná-lo mais próximo do Pac-Man original, seria necessário adicionar lógica para fantasmas perseguirem o Pac-Man, mais pastilhas e uma interface mais detalhada. É um exemplo prático de como usar WLanguage para criar jogos básicos com gráficos e interação! Se quiser aprofundar algum aspecto, é só avisar!

--
Adriano José Boller
______________________________________________
Consultor e Representante Oficial da
PcSoft no Brasil
+55 (41) 99949 1800
adrianoboller@gmail.com
skype: adrianoboller
http://wxinformatica.com.br/