JULIA-ANTHROPIC-API
Simon-Pierre Boucher
2024-09-14

Julia Anthropic

In [1]:
using JSON
using HTTP

# Fonction pour appeler l'API Claude
function call_claude_api(
    messages::Vector{Dict{String, Any}};  # Required argument
    model::String = "claude-3-5-sonnet-20240620",
    max_tokens::Int = 1024,
    anthropic_version::String = "2023-06-01"
)
    # Récupérer la clé API depuis les variables d'environnement
    api_key = get(ENV, "ANTHROPIC_API_KEY", "")

    if isempty(api_key)
        error("API key not found in environment variables. Please set ANTHROPIC_API_KEY.")
    end

    url = "https://api.anthropic.com/v1/messages"

    headers = [
        "x-api-key" => api_key,
        "anthropic-version" => anthropic_version,
        "Content-Type" => "application/json"
    ]

    # Préparer le corps de la requête
    data = Dict(
        "model" => model,
        "max_tokens" => max_tokens,
        "messages" => messages
    )

    json_data = JSON.json(data)

    # Envoyer la requête POST à l'API Claude
    response = HTTP.post(url, headers; body = json_data)

    # Vérifier si la requête a réussi
    if response.status != 200
        error("API request failed: $(response.status) - $(String(response.body))")
    end

    # Parse la réponse JSON
    result = JSON.parse(String(response.body))
    return result
end
Out[1]:
call_claude_api (generic function with 1 method)
In [2]:
# Exemple d'utilisation de la fonction
messages = [
    Dict{String, Any}("role" => "user", "content" => "Give me a julia code for snake game"),
]
Out[2]:
1-element Vector{Dict{String, Any}}:
 Dict("role" => "user", "content" => "Give me a julia code for snake game")
In [4]:
# Appeler la fonction pour obtenir une réponse
response = call_claude_api(
    messages;  # Required argument
    model = "claude-3-5-sonnet-20240620",
    max_tokens = 2024
)

# Extraire et afficher le texte de la réponse
if "content" in keys(response) && length(response["content"]) > 0
    # Accéder au premier élément de "content" et extraire le texte
    println(response["content"][1]["text"])
else
    println("Unexpected response format")
end
Here's a basic implementation of the Snake game in Julia using the Luxor package for graphics:

```julia
using Luxor

# Game constants
const GRID_SIZE = 20
const CELL_SIZE = 25
const WIDTH = GRID_SIZE * CELL_SIZE
const HEIGHT = GRID_SIZE * CELL_SIZE
const BACKGROUND_COLOR = "white"
const SNAKE_COLOR = "green"
const FOOD_COLOR = "red"

# Directions
const UP = (0, -1)
const DOWN = (0, 1)
const LEFT = (-1, 0)
const RIGHT = (1, 0)

# Game state
mutable struct GameState
    snake::Vector{Tuple{Int, Int}}
    direction::Tuple{Int, Int}
    food::Tuple{Int, Int}
    score::Int
    game_over::Bool
end

# Initialize game state
function init_game()
    snake = [(GRID_SIZE ÷ 2, GRID_SIZE ÷ 2)]
    direction = RIGHT
    food = spawn_food(snake)
    score = 0
    game_over = false
    GameState(snake, direction, food, score, game_over)
end

# Spawn food at a random location
function spawn_food(snake)
    food = (rand(1:GRID_SIZE), rand(1:GRID_SIZE))
    while food in snake
        food = (rand(1:GRID_SIZE), rand(1:GRID_SIZE))
    end
    food
end

# Update game state
function update!(game::GameState)
    if game.game_over
        return
    end

    # Move snake
    new_head = (
        (game.snake[1][1] + game.direction[1] + GRID_SIZE - 1) % GRID_SIZE + 1,
        (game.snake[1][2] + game.direction[2] + GRID_SIZE - 1) % GRID_SIZE + 1
    )

    # Check for collision with self
    if new_head in game.snake
        game.game_over = true
        return
    end

    pushfirst!(game.snake, new_head)

    # Check if food is eaten
    if new_head == game.food
        game.score += 1
        game.food = spawn_food(game.snake)
    else
        pop!(game.snake)
    end
end

# Draw game state
function draw(game::GameState)
    background(BACKGROUND_COLOR)

    # Draw snake
    setcolor(SNAKE_COLOR)
    for segment in game.snake
        x, y = (segment .- 1) .* CELL_SIZE
        rect(Point(x, y), CELL_SIZE, CELL_SIZE, :fill)
    end

    # Draw food
    setcolor(FOOD_COLOR)
    x, y = (game.food .- 1) .* CELL_SIZE
    circle(Point(x + CELL_SIZE/2, y + CELL_SIZE/2), CELL_SIZE/2, :fill)

    # Draw score
    setcolor("black")
    fontsize(20)
    text("Score: $(game.score)", Point(10, 30))

    if game.game_over
        setcolor("red")
        fontsize(40)
        text("Game Over", Point(WIDTH/2, HEIGHT/2), halign=:center, valign=:middle)
    end
end

# Main game loop
function game_loop(game::GameState)
    @drawsvg begin
        draw(game)
    end WIDTH HEIGHT

    if !game.game_over
        update!(game)
    end
end

# Handle keyboard input
function handle_input(game::GameState, key)
    if key == "up" && game.direction != DOWN
        game.direction = UP
    elseif key == "down" && game.direction != UP
        game.direction = DOWN
    elseif key == "left" && game.direction != RIGHT
        game.direction = LEFT
    elseif key == "right" && game.direction != LEFT
        game.direction = RIGHT
    end
end

# Run the game
function run_game()
    game = init_game()
    
    @async begin
        while !game.game_over
            sleep(0.1)
            game_loop(game)
        end
    end

    while true
        key = readline()
        if key == "q"
            break
        end
        handle_input(game, key)
    end
end

# Start the game
run_game()
```

To run this game, you'll need to install the Luxor package:

```julia
using Pkg
Pkg.add("Luxor")
```

This implementation creates a basic Snake game with the following features:

1. A snake that moves around the grid
2. Food that appears randomly
3. Score tracking
4. Game over when the snake collides with itself
5. Keyboard controls (up, down, left, right arrows)

To play the game:

1. Run the script
2. Use the arrow keys (typed as "up", "down", "left", "right") to control the snake
3. Try to eat the food (red circles) to grow the snake and increase your score
4. Avoid colliding with the snake's own body
5. Type "q" to quit the game

Note that this implementation uses a simple console input for controls, which might not be ideal for real-time gameplay. For a more responsive game, you may want to consider using a GUI library like Gtk.jl or SDL2.jl.