JavaScript · 2067 bytes Raw Blame History
1 // p5.js 2D renderer for dougk
2 import p5 from 'p5'
3 import { Pond } from './pond.js'
4 import { Duck } from './duck.js'
5 import { BreadManager } from './bread.js'
6
7 let sketch = null
8 let p5Instance = null
9
10 export function start(container) {
11 if (p5Instance) return
12
13 sketch = (p) => {
14 let pond
15 let doug
16 let breadManager
17
18 p.setup = () => {
19 const canvas = p.createCanvas(window.innerWidth, window.innerHeight)
20 canvas.parent(container)
21 canvas.mousePressed(handleClick)
22 p.frameRate(60)
23
24 pond = new Pond(p, p.width / 2, p.height / 2, 400, 280)
25 doug = new Duck(p, p.width / 2, p.height / 2, pond)
26 breadManager = new BreadManager(p)
27 }
28
29 p.windowResized = () => {
30 p.resizeCanvas(window.innerWidth, window.innerHeight)
31 pond.x = p.width / 2
32 pond.y = p.height / 2
33 }
34
35 p.draw = () => {
36 // Vibrant grass background
37 p.background(85, 160, 75)
38
39 drawGrassDetails()
40
41 pond.update()
42 pond.draw()
43
44 breadManager.update()
45 breadManager.draw()
46
47 doug.update(breadManager.bits)
48 doug.draw()
49 }
50
51 function handleClick() {
52 if (pond.contains(p.mouseX, p.mouseY)) {
53 breadManager.spawnBread(p.mouseX, p.mouseY)
54 pond.addRipple(p.mouseX, p.mouseY)
55 }
56 }
57
58 function drawGrassDetails() {
59 const seed = 12345
60 p.randomSeed(seed)
61
62 for (let i = 0; i < 40; i++) {
63 const gx = p.random(p.width)
64 const gy = p.random(p.height)
65
66 const dx = gx - pond.x
67 const dy = gy - pond.y
68 if (Math.sqrt(dx * dx + dy * dy) < 250) continue
69
70 p.stroke(25, 20, 15)
71 p.strokeWeight(1)
72 p.fill(65, 130, 55)
73 p.ellipse(gx, gy, 18, 10)
74
75 p.noStroke()
76 p.fill(110, 180, 95)
77 p.ellipse(gx - 3, gy - 2, 10, 5)
78 }
79
80 p.randomSeed(p.millis())
81 p.noStroke()
82 }
83 }
84
85 p5Instance = new p5(sketch)
86 }
87
88 export function stop() {
89 if (p5Instance) {
90 p5Instance.remove()
91 p5Instance = null
92 sketch = null
93 }
94 }
95
96 export const name = '2D'