Chat GPT 4o Code

For everything that's not in any way related to PureBasic. General chat etc...
deathmx
User
User
Posts: 34
Joined: Mon Feb 26, 2018 3:14 am

Chat GPT 4o Code

Post by deathmx »

I thought this would be interesting to show. It seems that Chat Gpt can finally write good purebasic code. It only took one attempt.

i had to add initkeyboard() , ExamineKeyboard(), StartDrawing(ScreenOutput()), stopdrawing()

it was only missing these 4 lines.

Code: Select all

; PureBasic Snake Game
; Basic implementation

#WindowWidth = 800
#WindowHeight = 600
#BlockSize = 20
#FPS = 10
InitKeyboard()
Structure Vector2D
  x.i
  y.i
EndStructure

Global Dim Snake.Vector2D(100)
Global SnakeLength.i = 5
Global Direction.Vector2D
Global Apple.Vector2D

Procedure CreateApple()
  Apple\x = Random(#WindowWidth / #BlockSize - 1) * #BlockSize
  Apple\y = Random(#WindowHeight / #BlockSize - 1) * #BlockSize
EndProcedure

Procedure InitGame()
  For i = 0 To SnakeLength - 1
    Snake(i)\x = #WindowWidth / 2 - i * #BlockSize
    Snake(i)\y = #WindowHeight / 2
  Next i
  Direction\x = #BlockSize
  Direction\y = 0
  CreateApple()
EndProcedure

Procedure UpdateGame()
  ; Move the snake
  For i = SnakeLength - 1 To 1 Step -1
    Snake(i)\x = Snake(i - 1)\x
    Snake(i)\y = Snake(i - 1)\y
  Next i
  Snake(0)\x + Direction\x
  Snake(0)\y + Direction\y

  ; Check for collisions with walls
  If Snake(0)\x < 0 Or Snake(0)\x >= #WindowWidth Or Snake(0)\y < 0 Or Snake(0)\y >= #WindowHeight
    InitGame() ; Restart the game
  EndIf

  ; Check for collisions with itself
  For i = 1 To SnakeLength - 1
    If Snake(0)\x = Snake(i)\x And Snake(0)\y = Snake(i)\y
      InitGame() ; Restart the game
    EndIf
  Next i

  ; Check for collisions with the apple
  If Snake(0)\x = Apple\x And Snake(0)\y = Apple\y
    SnakeLength + 1
    CreateApple()
  EndIf
EndProcedure

Procedure RenderGame()
  ClearScreen(RGB(0, 0, 0))
  ; Draw the snake
 StartDrawing(ScreenOutput()) 
  For i = 0 To SnakeLength - 1
    Box(Snake(i)\x, Snake(i)\y, #BlockSize, #BlockSize, RGB(0, 255, 0))
  Next i
  ; Draw the apple
  Box(Apple\x, Apple\y, #BlockSize, #BlockSize, RGB(255, 0, 0))
  StopDrawing()
EndProcedure

InitSprite()
OpenWindow(0, 0, 0, #WindowWidth, #WindowHeight, "Snake Game", #PB_Window_ScreenCentered | #PB_Window_SystemMenu)
OpenWindowedScreen(WindowID(0), 0, 0, #WindowWidth, #WindowHeight)

InitGame()

Repeat
  Event = WindowEvent()
  ExamineKeyboard()
  ; Handle input
  If KeyboardPushed(#PB_Key_Left) And Direction\x = 0
    Direction\x = -#BlockSize
    Direction\y = 0
  ElseIf KeyboardPushed(#PB_Key_Right) And Direction\x = 0
    Direction\x = #BlockSize
    Direction\y = 0
  ElseIf KeyboardPushed(#PB_Key_Up) And Direction\y = 0
    Direction\x = 0
    Direction\y = -#BlockSize
  ElseIf KeyboardPushed(#PB_Key_Down) And Direction\y = 0
    Direction\x = 0
    Direction\y = #BlockSize
  EndIf
  
  UpdateGame()
  RenderGame()
  
  FlipBuffers()
  Delay(1000 / #FPS)
  
Until Event = #PB_Event_CloseWindow
End
BarryG
Addict
Addict
Posts: 4122
Joined: Thu Apr 18, 2019 8:17 am

Re: Chat GPT 4o Code

Post by BarryG »

That's amazing! I remember some people here saying that using ChatGPT for code is just a gimmick as it would never generate working code, but it's progressing very well!
deathmx
User
User
Posts: 34
Joined: Mon Feb 26, 2018 3:14 am

Re: Chat GPT 4o Code

Post by deathmx »

I was very surpised as well. I have tried this in the past with many Large Language Models. They all really completely fail to understand purebasic because it is less known.

The code also looks pretty advanced, organized and just overall very well written which amazed me even more.
Quin
Addict
Addict
Posts: 1122
Joined: Thu Mar 31, 2022 7:03 pm
Location: Colorado, United States
Contact:

Re: Chat GPT 4o Code

Post by Quin »

Pretty amazing.
If you want more AI amazingness, slightly off-topic, but look here.
BarryG
Addict
Addict
Posts: 4122
Joined: Thu Apr 18, 2019 8:17 am

Re: Chat GPT 4o Code

Post by BarryG »

Okay, so I've got temporary free access to ChatGPT 4o so I asked it this: "using purebasic, write a program that opens notepad at the top-left quarter of the desktop". It gave me this code, which was 99% right but the imports didn't work:

Code: Select all

EnableExplicit

; Declare Windows API functions
Import "user32.lib"
  FindWindowA(lpClassName.l, lpWindowName.l) As "_FindWindowA@8"
  MoveWindow(hWnd.l, X.l, Y.l, nWidth.l, nHeight.l, bRepaint.l) As "_MoveWindow@24"
EndImport

Procedure OpenNotepadAndPosition()
  Protected hWndNotepad.l
  Protected desktopWidth.l
  Protected desktopHeight.l
  Protected notepadWidth.l
  Protected notepadHeight.l
  
  ; Run Notepad
  RunProgram("notepad.exe")
  
  ; Wait a bit to make sure Notepad has opened
  Delay(1000)
  
  ; Find the Notepad window by its class name and window name
  hWndNotepad = FindWindowA(0, @"Untitled - Notepad")
  
  If hWndNotepad = 0
    MessageRequester("Error", "Notepad window not found.", #PB_MessageRequester_Ok)
    ProcedureReturn
  EndIf
  
  ; Get the desktop dimensions
  desktopWidth = GetSystemMetrics_(#SM_CXSCREEN)
  desktopHeight = GetSystemMetrics_(#SM_CYSCREEN)
  
  ; Calculate the top-left quarter dimensions
  notepadWidth = desktopWidth / 2
  notepadHeight = desktopHeight / 2
  
  ; Move and resize the Notepad window
  MoveWindow(hWndNotepad, 0, 0, notepadWidth, notepadHeight, #True)
EndProcedure

OpenNotepadAndPosition()
So I modified my question to this instead: "using purebasic, write a program that opens notepad at the top-left quarter of the desktop, without using imports" and it gave me this shorter compilable and working code! :shock:

Code: Select all

; PureBasic program to open Notepad at the top-left quarter of the desktop

Procedure OpenNotepadAtTopLeftQuarter()
  Protected notepadPID
  Protected notepadHWND
  Protected screenWidth, screenHeight
  Protected topLeftQuarterWidth, topLeftQuarterHeight

  ; Get the screen dimensions
  screenWidth = GetSystemMetrics_(#SM_CXSCREEN)
  screenHeight = GetSystemMetrics_(#SM_CYSCREEN)

  ; Calculate the size of the top-left quarter
  topLeftQuarterWidth = screenWidth / 2
  topLeftQuarterHeight = screenHeight / 2

  ; Run Notepad
  notepadPID = RunProgram("notepad.exe")

  ; Wait for Notepad to open and get its window handle
  Repeat
    Delay(100)
    notepadHWND = FindWindow_(0, "Untitled - Notepad")
  Until notepadHWND <> 0

  ; Move and resize Notepad to the top-left quarter of the screen
  SetWindowPos_(notepadHWND, 0, 0, 0, topLeftQuarterWidth, topLeftQuarterHeight, #SWP_NOZORDER)
EndProcedure

OpenNotepadAtTopLeftQuarter()
Pretty cool, IMO. 8)

Side-note: I actually use ChatGPT 3.5 to ask generic coding questions instead of asking here, and it's usually given me the right answers to get me going. Like, it'll give me the theory and then I translate that into practice. It's quite a very capable resource to prod you in the right direction when you're stumped over something.
r-i-v-e-r
User
User
Posts: 20
Joined: Thu May 09, 2024 5:18 pm

Re: Chat GPT 4o Code

Post by r-i-v-e-r »

It's serviceable, but there are still several problems that have to be fixed manually.
deathmx wrote: Sat May 18, 2024 2:12 am

Code: Select all

Repeat
  Event = WindowEvent()
  ExamineKeyboard()
  ; Handle input
  ; ... (snip)
  UpdateGame()
  RenderGame()
  
  FlipBuffers()
  Delay(1000 / #FPS)
  
Until Event = #PB_Event_CloseWindow
End
The event loop is broken: it only processes a single event every rendered frame, and with #FPS = 10 that means a mere 10 events per second. This will result in general lagginess since Windows sometimes needs to send many events in short order, and the queue may continue to accrue more and more events resulting in sporadic unresponsiveness (e.g., random loading cursor or even a "This application has stopped working..." popup after some time).

It should instead be structured such that pending events are processed each frame, rather than building up. Similarly, Delay(1000 / #FPS) is a poor approach to limiting FPS as it'll slow down event processing further.

There are other weird design decisions and/or bugs, e.g.:
  • The game takes place on a small grid of blocks, but positions are all premultipleid to exist in window-space. This makes collision detection code pretty silly, since it fails if anything isn't perfectly grid-aligned. It kind of begs the question: why premultiply and not just use grid positions? (premultiplying makes things like resizing a pain anyway, since you'd have to loop over every entity and divide + remultiply...)
  • The snake array has space for 101 blocks, but growing the snake length past this will cause an OOB crash or glitchy behaviour.
  • Because of the way the snake is extended, a single frame with a block flashing at (0, 0) appears, as it's only placed properly behind the snake the following frame.
  • And some pedantic things: apples aren't generated in empty slots and can spawn on top of the snake itself, dying doesn't reset snake length, the terminal End is unnecessary, etc.
It may be useful as a base sometimes, though it's more often frustrating in my experience, generating code that looks nice and OK on the surface, but which actually ends up being more a vessel for weird bugs and/or bad practices. It might say it's doing one thing in a comment, while actually doing it incorrectly or doing something else entirely. It might be totally functional, but lacking robustness and so edge-cases are left uncovered. It might be totally fine, but plagiarised.

All in all, it should be taken with a grain of salt. Use it as turbo-powered Google and fact-check its responses. But please avoid falling under the impression it's remotely reliable in it's current state. I frequently deal with juniors becoming overly trusting of ChatGPT/Copilot responses, and it's a tremendous source of bugs and spaghetti code.
BarryG wrote: Sat May 18, 2024 3:23 am So I modified my question to this instead: "using purebasic, write a program that opens notepad at the top-left quarter of the desktop, without using imports" and it gave me this shorter compilable and working code! :shock:

Code: Select all

  ; Run Notepad
  notepadPID = RunProgram("notepad.exe")

  ; Wait for Notepad to open and get its window handle
  Repeat
    Delay(100)
    notepadHWND = FindWindow_(0, "Untitled - Notepad")
Works great until you realise it fails if the client isn't using English Windows, or one of several other scenarios apply :wink:
deathmx
User
User
Posts: 34
Joined: Mon Feb 26, 2018 3:14 am

Re: Chat GPT 4o Code

Post by deathmx »

Wow it really can get you started or work as a filler. This is so much better than it was.

BarryG I am very surprised it managed that so well. It would be much faster than looking it up functions or examples. greatly increases productivity. Very cool!

r-i-v-e-r: Thank you for the in depth analysis. Understanding some of these limitations could help. Maybe we can experiment with some prompts to try to enhance it. I only asked one time for it to create the snake game in purebasic and that is what i got. I think i'll try more prompts to see what we can get out of it.
BarryG
Addict
Addict
Posts: 4122
Joined: Thu Apr 18, 2019 8:17 am

Re: Chat GPT 4o Code

Post by BarryG »

r-i-v-e-r wrote: Sat May 18, 2024 3:30 amWorks great until you realise it fails if the client isn't using English Windows
That's not an issue, because it's no different to asking here how to do it and someone replying with an English answer (which happens all the time). It's quite obvious that you just change the text to the desired OS version's language.
deathmx
User
User
Posts: 34
Joined: Mon Feb 26, 2018 3:14 am

Re: Chat GPT 4o Code

Post by deathmx »

" I would like you to optimize the code as much as possible while making it as wasteful as possible in memmory etc. Also if you can see some missing features please feel free to add to make it feel like a real game. " - I meant to tell it make it less wastefull oops! I'll have to change it later lol ran out of tokens. So this is going to be the slow version...

Enhancements and Wasteful Optimizations:
Increased Snake Array Size: The snake array is now 10 times larger than necessary to waste memory.
Score Display: A score counter is displayed on the screen.
Game Over Message: A "GAME OVER" message appears when the snake collides with itself or the walls, and prompts the player to press 'R' to restart.
Improved Apple Generation: Ensures the apple does not spawn on the snake's initial position.
Increased Delay for Readability: A slight increase in delay ensures readability of the game over message and smoother gameplay.

"could you make the shapes and snake look more realistic also it is running to fast maybe you can use gettickcount_ or eplasetimer to slow it down a bit. Still needs to be more colorful maybe more rainbow like?"


I had to make quite a few fixes. It doesn't know about DisplayTransparentSprite Function. Had problems with gradients frontcolor and backcolor function. It also made the snake fade as time went by so i commented that part out. Had issues using the drawingmode(*gradients*) I think that is about all of the changes i made. Oh also had to fix up the roundedbox by getting rid of its 0 hex value and putting in the color variable while making sure rgba worked with it. That is about it.

Maybe i'll try a couple more but chatgpt 4o is very limited for the free edition at the moment lol.

Code: Select all

; PureBasic Snake Game
; Enhanced, wasteful, colorful, and visually appealing implementation

#WindowWidth = 800
#WindowHeight = 600
#BlockSize = 20
#GridWidth = #WindowWidth / #BlockSize
#GridHeight = #WindowHeight / #BlockSize
#FPS = 10

InitKeyboard()
InitSprite()
InitMouse()

Structure Vector2D
  x.i
  y.i
EndStructure

Global Dim Snake.Vector2D(1000) ; Wasteful memory allocation
Global SnakeLength.i = 5
Global Direction.Vector2D
Global Apple.Vector2D
Global Score.i
Global GameOver.b
Global LastUpdate.i

Procedure CreateApple()
  Protected isOnSnake.b
  Repeat
    isOnSnake = #False
    Apple\x = Random(#GridWidth - 1)
    Apple\y = Random(#GridHeight - 1)
    For i = 0 To SnakeLength - 1
      If Apple\x = Snake(i)\x And Apple\y = Snake(i)\y
        isOnSnake = #True
        Break
      EndIf
    Next i
  Until Not isOnSnake
EndProcedure

Procedure InitGame()
  For i = 0 To SnakeLength - 1
    Snake(i)\x = #GridWidth / 2 - i
    Snake(i)\y = #GridHeight / 2
  Next i
  Direction\x = 1
  Direction\y = 0
  Score = 0
  GameOver = #False
  CreateApple()
  LastUpdate = ElapsedMilliseconds()
EndProcedure

Procedure.f HueToRGB(p.f, q.f, t.f)
  If t < 0 : t + 1 : EndIf
  If t > 1 : t - 1 : EndIf
  If t < 1 / 6 : ProcedureReturn p + (q - p) * 6 * t : EndIf
  If t < 1 / 2 : ProcedureReturn q : EndIf
  If t < 2 / 3 : ProcedureReturn p + (q - p) * (2 / 3 - t) * 6 : EndIf
  ProcedureReturn p
EndProcedure

Procedure RGBFromHSL(hue.f, saturation.f, lightness.f)
  Protected r.f, g.f, b.f, q.f, p.f
  hue / 360
  If saturation = 0
    r = lightness
    g = lightness
    b = lightness
  Else
    If lightness < 0.5
      q = lightness * (1 + saturation)
    Else
      q = lightness + saturation - lightness * saturation
    EndIf
    p = 2 * lightness - q
    r = HueToRGB(p, q, hue + 1 / 3)
    g = HueToRGB(p, q, hue)
    b = HueToRGB(p, q, hue - 1 / 3)
  EndIf
  ProcedureReturn RGB(r * 255, g * 255, b * 255)
EndProcedure

Procedure UpdateGame()
  If GameOver = #True
    ProcedureReturn
  EndIf
  
  ; Move the snake
  For i = SnakeLength - 1 To 1 Step -1
    Snake(i)\x = Snake(i - 1)\x
    Snake(i)\y = Snake(i - 1)\y
  Next i
  Snake(0)\x = Snake(0)\x + Direction\x
  Snake(0)\y = Snake(0)\y + Direction\y

  ; Check for collisions with walls
  If Snake(0)\x < 0 Or Snake(0)\x >= #GridWidth Or Snake(0)\y < 0 Or Snake(0)\y >= #GridHeight
    GameOver = #True
  EndIf

  ; Check for collisions with itself
  For i = 1 To SnakeLength - 1
    If Snake(0)\x = Snake(i)\x And Snake(0)\y = Snake(i)\y
      GameOver = #True
    EndIf
  Next i

  ; Check for collisions with the apple
  If Snake(0)\x = Apple\x And Snake(0)\y = Apple\y
    SnakeLength = SnakeLength + 1
    Score + 10
    CreateApple()
  EndIf
EndProcedure

Procedure DrawRoundedBox(x, y, width, height, radius, color)
  Protected DrawingBuffer, TransparentBuffer
  
  DrawingBuffer = CreateImage(#PB_Any, width, height)
  If StartDrawing(ImageOutput(DrawingBuffer))
    Box(0, 0, width, height, color)
    StopDrawing()
  EndIf

  TransparentBuffer = CreateImage(#PB_Any, width, height, 32 , #PB_Image_Transparent)
  If StartDrawing(ImageOutput(TransparentBuffer))
    color = RGBA(Red(color),Green(color),Blue(color),255)
    DrawingMode(#PB_2DDrawing_AlphaBlend)
    Circle(radius, radius, radius, color)
    Circle(width - radius, radius, radius, color)
    Circle(radius, height - radius, radius, color)
    Circle(width - radius, height - radius, radius, color)
    Box(0, radius, width, height - radius * 2, color)
    Box(radius, 0, width - radius * 2, height, color)
    ;DrawingMode(#PB_2DDrawing_AlphaBlend)
   ; Box(0, 0, width, height, color)
    StopDrawing()
  EndIf
  
  If StartDrawing(ScreenOutput())
    ;DrawImage(ImageID(DrawingBuffer), x, y)
    DrawAlphaImage(ImageID(TransparentBuffer), x, y)
    StopDrawing()
  EndIf

  FreeImage(DrawingBuffer)
  FreeImage(TransparentBuffer)
EndProcedure

Procedure RenderGame()
  ClearScreen(RGB(0, 0, 0))
  
  ; Draw the snake with rainbow colors
  For i = 0 To SnakeLength - 1
    Protected hue.f = (i * 360.0 / SnakeLength); + (ElapsedMilliseconds() / 10.0)
    Protected color = RGBFromHSL(hue, 1.0, 0.5)
    DrawRoundedBox(Snake(i)\x * #BlockSize, Snake(i)\y * #BlockSize, #BlockSize, #BlockSize, 5, color)
  Next i
  
  ; Draw the apple with a gradient
  Protected AppleColor1 = RGB(255, 50, 50)
  Protected AppleColor2 = RGB(255, 0, 0)
  Protected DrawingBuffer = CreateImage(#PB_Any, #BlockSize, #BlockSize)
  If StartDrawing(ImageOutput(DrawingBuffer))
    DrawingMode(#PB_2DDrawing_Gradient)
    
    BackColor(AppleColor1)
    FrontColor(AppleColor2)
    ;GradientColor(0.5, AppleColor1)
    ;GradientColor(0.9, AppleColor2)
    ;FrontColor(AppleColor2)
    LinearGradient(0, 0, #BlockSize, #BlockSize)
    Box(0, 0, #BlockSize, #BlockSize)
    StopDrawing()
  EndIf
  
  If StartDrawing(ScreenOutput())
    DrawImage(ImageID(DrawingBuffer), Apple\x * #BlockSize, Apple\y * #BlockSize)
    StopDrawing()
  EndIf
  FreeImage(DrawingBuffer)
  
  ; Draw the score
  If StartDrawing(ScreenOutput())
    DrawText(10, 10, "Score: " + Str(Score), RGB(255, 255, 255), RGB(0, 0, 0))
  
    ; Draw game over message
    If GameOver = #True
      DrawText(#WindowWidth / 2 - 50, #WindowHeight / 2 - 10, "GAME OVER", RGB(255, 0, 0), RGB(0, 0, 0))
      DrawText(#WindowWidth / 2 - 80, #WindowHeight / 2 + 10, "Press R to Restart", RGB(255, 0, 0), RGB(0, 0, 0))
    EndIf
    StopDrawing()
  EndIf
EndProcedure

OpenWindow(0, 0, 0, #WindowWidth, #WindowHeight, "Snake Game", #PB_Window_ScreenCentered | #PB_Window_SystemMenu)
OpenWindowedScreen(WindowID(0), 0, 0, #WindowWidth, #WindowHeight)

InitGame()

Repeat
  Repeat
    Event = WindowEvent()
    If Event = #PB_Event_CloseWindow
      End
    EndIf
  Until Event = 0
  
  ExamineKeyboard()
  
  ; Handle input
  If GameOver = #False
    If KeyboardPushed(#PB_Key_Left) And Direction\x = 0
      Direction\x = -1
      Direction\y = 0
    ElseIf KeyboardPushed(#PB_Key_Right) And Direction\x = 0
      Direction\x = 1
      Direction\y = 0
    ElseIf KeyboardPushed(#PB_Key_Up) And Direction\y = 0
      Direction\x = 0
      Direction\y = -1


ElseIf KeyboardPushed(#PB_Key_Down) And Direction\y = 0
      Direction\x = 0
      Direction\y = 1
    EndIf
  Else
    If KeyboardPushed(#PB_Key_R)
      InitGame()
    EndIf
  EndIf
  
  If ElapsedMilliseconds() - LastUpdate >= 1000 / #FPS
    UpdateGame()
    LastUpdate = ElapsedMilliseconds()
  EndIf
  
  RenderGame()
  FlipBuffers()
  
Until Event = #PB_Event_CloseWindow
End
deathmx
User
User
Posts: 34
Joined: Mon Feb 26, 2018 3:14 am

Re: Chat GPT 4o Code

Post by deathmx »

" It would be nice if the rainbow color could rotate. Please lets make this code as fast and as optimal as possible. Lets do the oposite of being wasteful this time."

Only problem was the couple of mod functions it thought you could just say x mod y instead of using it like a function and startdrawing needed to be moved to the top of the function.


GPT response:
Changes Made:
Memory Optimization: Removed the fixed allocation for the snake array and instead dynamically adjusted its size.
Rotating Rainbow Color: Added a rotating hue for the snake based on the elapsed time.
Performance Improvement: Simplified the rendering of the apple and the snake blocks to reduce unnecessary image creation and drawing operations.
Simplified Draw Function: Removed the rounded box drawing function to use a simple box drawing for better performance.
These changes should make the game run more efficiently while still maintaining the colorful and visually appealing features.

Code: Select all

; PureBasic Snake Game
; Enhanced, optimized, colorful, and visually appealing implementation

#WindowWidth = 800
#WindowHeight = 600
#BlockSize = 20
#GridWidth = #WindowWidth / #BlockSize
#GridHeight = #WindowHeight / #BlockSize
#FPS = 10

InitKeyboard()
InitSprite()
InitMouse()

Structure Vector2D
  x.i
  y.i
EndStructure

Global Dim Snake.Vector2D(0)
Global SnakeLength.i = 5
Global Direction.Vector2D
Global Apple.Vector2D
Global Score.i
Global GameOver.b
Global LastUpdate.i

Procedure CreateApple()
  Protected isOnSnake.b
  Repeat
    isOnSnake = #False
    Apple\x = Random(#GridWidth - 1)
    Apple\y = Random(#GridHeight - 1)
    For i = 0 To SnakeLength - 1
      If Apple\x = Snake(i)\x And Apple\y = Snake(i)\y
        isOnSnake = #True
        Break
      EndIf
    Next i
  Until Not isOnSnake
EndProcedure

Procedure InitGame()
  ReDim Snake(SnakeLength - 1)
  For i = 0 To SnakeLength - 1
    Snake(i)\x = #GridWidth / 2 - i
    Snake(i)\y = #GridHeight / 2
  Next i
  Direction\x = 1
  Direction\y = 0
  Score = 0
  GameOver = #False
  CreateApple()
  LastUpdate = ElapsedMilliseconds()
EndProcedure

Procedure.f HueToRGB(p.f, q.f, t.f)
  If t < 0 : t + 1 : EndIf
  If t > 1 : t - 1 : EndIf
  If t < 1 / 6 : ProcedureReturn p + (q - p) * 6 * t : EndIf
  If t < 1 / 2 : ProcedureReturn q : EndIf
  If t < 2 / 3 : ProcedureReturn p + (q - p) * (2 / 3 - t) * 6 : EndIf
  ProcedureReturn p
EndProcedure

Procedure RGBFromHSL(hue.f, saturation.f, lightness.f)
  Protected r.f, g.f, b.f, q.f, p.f
  hue / 360
  If saturation = 0
    r = lightness
    g = lightness
    b = lightness
  Else
    If lightness < 0.5
      q = lightness * (1 + saturation)
    Else
      q = lightness + saturation - lightness * saturation
    EndIf
    p = 2 * lightness - q
    r = HueToRGB(p, q, hue + 1 / 3)
    g = HueToRGB(p, q, hue)
    b = HueToRGB(p, q, hue - 1 / 3)
  EndIf
  ProcedureReturn RGB(r * 255, g * 255, b * 255)
EndProcedure

Procedure UpdateGame()
  If GameOver = #True
    ProcedureReturn
  EndIf
  
  ; Move the snake
  For i = SnakeLength - 1 To 1 Step -1
    Snake(i)\x = Snake(i - 1)\x
    Snake(i)\y = Snake(i - 1)\y
  Next i
  Snake(0)\x = Snake(0)\x + Direction\x
  Snake(0)\y = Snake(0)\y + Direction\y

  ; Check for collisions with walls
  If Snake(0)\x < 0 Or Snake(0)\x >= #GridWidth Or Snake(0)\y < 0 Or Snake(0)\y >= #GridHeight
    GameOver = #True
  EndIf

  ; Check for collisions with itself
  For i = 1 To SnakeLength - 1
    If Snake(0)\x = Snake(i)\x And Snake(0)\y = Snake(i)\y
      GameOver = #True
    EndIf
  Next i

  ; Check for collisions with the apple
  If Snake(0)\x = Apple\x And Snake(0)\y = Apple\y
    SnakeLength + 1
    ReDim Snake(SnakeLength - 1)
    Score + 10
    CreateApple()
  EndIf
EndProcedure

Procedure RenderGame()
  ClearScreen(RGB(0, 0, 0))
  If StartDrawing(ScreenOutput())
  ; Draw the snake with rotating rainbow colors
  Protected CurrentHue.f = Mod(ElapsedMilliseconds() / 10.0,360)
  For i = 0 To SnakeLength - 1
    Protected hue.f = Mod((CurrentHue + (i * 360.0 / SnakeLength)),360)
    Protected color = RGBFromHSL(hue, 1.0, 0.5)
    Box(Snake(i)\x * #BlockSize, Snake(i)\y * #BlockSize, #BlockSize, #BlockSize, color)
  Next i
  
  ; Draw the apple
  Protected AppleColor = RGB(255, 0, 0)
  Box(Apple\x * #BlockSize, Apple\y * #BlockSize, #BlockSize, #BlockSize, AppleColor)
  
  ; Draw the score
  
    DrawText(10, 10, "Score: " + Str(Score), RGB(255, 255, 255), RGB(0, 0, 0))
  
    ; Draw game over message
    If GameOver = #True
      DrawText(#WindowWidth / 2 - 50, #WindowHeight / 2 - 10, "GAME OVER", RGB(255, 0, 0), RGB(0, 0, 0))
      DrawText(#WindowWidth / 2 - 80, #WindowHeight / 2 + 10, "Press R to Restart", RGB(255, 0, 0), RGB(0, 0, 0))
    EndIf
    StopDrawing()
  EndIf
EndProcedure

OpenWindow(0, 0, 0, #WindowWidth, #WindowHeight, "Snake Game", #PB_Window_ScreenCentered | #PB_Window_SystemMenu)
OpenWindowedScreen(WindowID(0), 0, 0, #WindowWidth, #WindowHeight)

InitGame()

Repeat
  Repeat
    Event = WindowEvent()
    If Event = #PB_Event_CloseWindow
      End
    EndIf
  Until Event = 0
  
  ExamineKeyboard()
  
  ; Handle input
  If GameOver = #False
    If KeyboardPushed(#PB_Key_Left) And Direction\x = 0
      Direction\x = -1
      Direction\y = 0
    ElseIf KeyboardPushed(#PB_Key_Right) And Direction\x = 0
      Direction\x = 1
      Direction\y = 0
    ElseIf KeyboardPushed(#PB_Key_Up) And Direction\y = 0
      Direction\x = 0
      Direction\y = -1
    ElseIf KeyboardPushed(#PB_Key_Down) And Direction\y = 0
      Direction\x = 0
      Direction\y = 1
    EndIf
  Else
    If KeyboardPushed(#PB_Key_R)
      InitGame()
    EndIf
  EndIf
  
  If ElapsedMilliseconds() - LastUpdate >= 1000 / #FPS
    UpdateGame()
    LastUpdate = ElapsedMilliseconds()
  EndIf
  
  RenderGame()
  FlipBuffers()
  
Until Event = #PB_Event_CloseWindow
End
r-i-v-e-r
User
User
Posts: 20
Joined: Thu May 09, 2024 5:18 pm

Re: Chat GPT 4o Code

Post by r-i-v-e-r »

BarryG wrote: Sat May 18, 2024 8:34 am
r-i-v-e-r wrote: Sat May 18, 2024 3:30 amWorks great until you realise it fails if the client isn't using English Windows
That's not an issue, because it's no different to asking here how to do it and someone replying with an English answer (which happens all the time).
There's a profound difference between receiving help on a public forum and receiving answers from an LLM chatbot. The former is a public interaction, where posted code would be scrutinised and issues likely pointed out by other forum members. The latter is effectively a private conversation and so the only one left to scrutinise code is the asker (you). As I've mentioned, that becomes problematic when people become too trusting (and/or lazy) and just ship what ChatGPT/Copilot has emit.

BarryG wrote: Sat May 18, 2024 8:34 am It's quite obvious that you just change the text to the desired OS version's language.
If it's obvious, it's obviously wrong. Hardcoding locale-dependent variants of "Untitled - Notepad" is a fragile and hacky solution which entirely forgoes robustness.

What if the user is running Windows 11 and has ticked the "restore my previous session" option in Notepad? In that case, the opened window likely won't be "Untitled - Notepad" at all, but some arbitrary text instead. Your program will then hang until an "Untitled - Notepad" window opens (if ever).

What if the user already had an "Untitled - Notepad" window open? Then you'll likely reposition that while opening a new blank window as well.

You've handily exemplified the problem I described. Chatbots will spit out code doing something vaguely as asked, even if the approach is fundamentally flawed. Until they're smart enough to lead with a disclaimer in some cases ("hey, there's a better way..."), then they pose a risk when not used carefully. They need adequate supervision. Your "obvious" solution is demonstrably incorrect, so where will that supervision come from when you're misled?

This is a pattern I see frequently, where people are misled and follow a deeply flawed rabbit hole of ChatGPT/Copilot responses to a dead end of crude spaghetti-code, half-measures, and bugs. It's not a one-off woopsie requiring some "prompt engineering" to refine things.
BarryG
Addict
Addict
Posts: 4122
Joined: Thu Apr 18, 2019 8:17 am

Re: Chat GPT 4o Code

Post by BarryG »

r-i-v-e-r wrote: Sun May 19, 2024 12:47 amWhat if the user already had an "Untitled - Notepad" window open? Then you'll likely reposition that while opening a new blank window as well.
If you read ChatGPT's code, you'll see that it uses the newly-opened Notepad handle, thus ensuring no existing Notepad window would be affected.

I'm skilled enough in coding to check its responses and see what it's saying, and to fix any errors that it has. That's how I spotted its import API error and asked it to redo the code without imports, and it did - 100% correctly and instantly compilable the second time. So it's a good resource for me personally.
r-i-v-e-r wrote: Sun May 19, 2024 12:47 amUntil they're smart enough to lead with a disclaimer in some cases ("hey, there's a better way..."), then they pose a risk when not used carefully.
It does come with that disclaimer on its web page: "ChatGPT can make mistakes. Check important info."
Last edited by BarryG on Sun May 19, 2024 3:36 am, edited 4 times in total.
deathmx
User
User
Posts: 34
Joined: Mon Feb 26, 2018 3:14 am

Re: Chat GPT 4o Code

Post by deathmx »

BarryG wrote: Sun May 19, 2024 3:13 am
r-i-v-e-r wrote: Sun May 19, 2024 12:47 amWhat if the user already had an "Untitled - Notepad" window open? Then you'll likely reposition that while opening a new blank window as well.
If you read ChatGPT's code, you'll see that it uses the newly-opened Notepad handle, thus ensuring no existing Notepad window would be affected.

I'm skilled enough in coding to check its responses and see what it's saying, and to fix any errors that it has. So it's a good resource for me personally.
I agree with you. It is already saving me lots of time with the grunt work. I just need to go through it and check it and fix some small errors. It has easily saved me many hours of time for programming simulations. Of coarse there are many things that should be double checked. It is very quick to change all the code if you need a big change that would take hours of work. It is not perfect but is insainly extremely productive.
r-i-v-e-r
User
User
Posts: 20
Joined: Thu May 09, 2024 5:18 pm

Re: Chat GPT 4o Code

Post by r-i-v-e-r »

BarryG wrote: Sun May 19, 2024 3:13 am
r-i-v-e-r wrote: Sun May 19, 2024 12:47 amWhat if the user already had an "Untitled - Notepad" window open? Then you'll likely reposition that while opening a new blank window as well.
If you read ChatGPT's code, you'll see that it uses the newly-opened Notepad handle, thus ensuring no existing Notepad window would be affected.

I'm skilled enough in coding to check its responses and see what it's saying, and to fix any errors that it has. That's how I spotted its import API error and asked it to redo the code without imports, and it did - 100% correctly and instantly compilable the second time. So it's a good resource for me personally.
Are you sure? That's really not the case... :|

Please, look closely at the code you posted:
BarryG wrote: Sat May 18, 2024 3:23 am So I modified my question to this instead: "using purebasic, write a program that opens notepad at the top-left quarter of the desktop, without using imports" and it gave me this shorter compilable and working code! :shock:

Code: Select all

  ; Run Notepad
  notepadPID = RunProgram("notepad.exe")

  ; Wait for Notepad to open and get its window handle
  Repeat
    Delay(100)
    notepadHWND = FindWindow_(0, "Untitled - Notepad")
Where does it ensure that a new handle is used? It's just running FindWindow_(...) for any "Untitled - Notepad" window. Sure, it waits 100ms before running the search, but it can easily take longer than that for a new window to appear, meaning it can easily grab an existing one and move that before the new one spawns on top of it.

If you were to actually run it multiple times in succession, you'd probably see it doesn't do what's advertised and instead resizes the previous Notepad instance while creating a new one placed normally. That's to say nothing of the other problems you've glanced over.

Maybe you were under the impression that it would search for only windows belonging to the new PID, but this isn't the case. If you look into the code, you'll notice that notepadPID is assigned a value for no reason at all. It's never used. This is exactly the type of sloppy code it frequently outputs, and people are frequently confused by.
BarryG wrote: Sun May 19, 2024 3:13 am
r-i-v-e-r wrote: Sun May 19, 2024 12:47 amUntil they're smart enough to lead with a disclaimer in some cases ("hey, there's a better way..."), then they pose a risk when not used carefully.
It does come with that disclaimer on its web page: "ChatGPT can make mistakes. Check important info."
That's not what I said. TLDR: if you ask ChatGPT to do something wrong*, it'll do just that without complaint. Instead, it should warn the user "hey, you're asking to shoot yourself in the foot I can do that, but another way is better."

By your own admission, certain mistakes are commonplace and well understood, so it should be simple to avoid taking such paths.

* There are some queries where it will straight up refuse to do things wrongly, but not reckless coding practices, rather things that might be discriminatory or harmful to people in general. I'm saying a similar disclaimer should be added when poor methodologies become involved, either explicitly or implicitly, in the solution of a problem.
deathmx wrote: Sun May 19, 2024 3:33 am Of coarse there are many things that should be double checked. It is very quick to change all the code if you need a big change that would take hours of work. It is not perfect but is insainly extremely productive.
I know it sounds like I'm just pooing on these tools, but I agree. They can certainly be useful.

I only feel that people should be sufficiently cautious, because as demonstrated above, the code generated for/by @BarryG really doesn't do what he alleges it does.
BarryG
Addict
Addict
Posts: 4122
Joined: Thu Apr 18, 2019 8:17 am

Re: Chat GPT 4o Code

Post by BarryG »

r-i-v-e-r wrote: Sun May 19, 2024 4:54 amMaybe you were under the impression that it would search for only windows belonging to the new PID, but this isn't the case. If you look into the code, you'll notice that notepadPID is assigned a value for no reason at all. It's never used.
True; I totally overlooked that in my haste to post it here. But if I were to use what ChatGPT posted in my own app, I'd certainly be properly bug-checking it first, as you recommend.
Post Reply