forked from slint-ui/slint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.rs
277 lines (251 loc) · 9.72 KB
/
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
// Copyright © SixtyFPS GmbH <[email protected]>
// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-commercial
use slint::Model;
use std::cell::RefCell;
use std::rc::Rc;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::prelude::*;
slint::include_modules!();
fn shuffle() -> Vec<i8> {
fn is_solvable(positions: &[i8]) -> bool {
// Same source as the flutter's slide_puzzle:
// https://www.cs.bham.ac.uk/~mdr/teaching/modules04/java2/TilesSolvability.html
// This page seems to be no longer available, a copy can be found here:
// https://horatiuvlad.com/unitbv/inteligenta_artificiala/2015/TilesSolvability.html
let mut inversions = 0;
for x in 0..positions.len() - 1 {
let v = positions[x];
inversions += positions[x + 1..].iter().filter(|x| **x >= 0 && **x < v).count();
}
//((blank on odd row from bottom) == (#inversions even))
let blank_row = positions.iter().position(|x| *x == -1).unwrap() / 4;
inversions % 2 != blank_row % 2
}
let mut vec = ((-1)..15).into_iter().collect::<Vec<i8>>();
use rand::seq::SliceRandom;
let mut rng = rand::thread_rng();
vec.shuffle(&mut rng);
while !is_solvable(&vec) {
vec.shuffle(&mut rng);
}
vec
}
struct AppState {
pieces: Rc<slint::VecModel<Piece>>,
main_window: slint::Weak<MainWindow>,
/// An array of 16 values which represent a 4x4 matrix containing the piece number in that
/// position. -1 is no piece.
positions: Vec<i8>,
auto_play_timer: slint::Timer,
kick_animation_timer: slint::Timer,
/// The speed in the x and y direction for the associated tile
speed_for_kick_animation: [(f32, f32); 15],
finished: bool,
}
impl AppState {
fn set_pieces_pos(&self, p: i8, pos: i8) {
if p >= 0 {
self.pieces.set_row_data(
p as usize,
Piece { pos_y: (pos % 4) as _, pos_x: (pos / 4) as _, offset_x: 0., offset_y: 0. },
);
}
}
fn randomize(&mut self) {
self.positions = shuffle();
for (i, p) in self.positions.iter().enumerate() {
self.set_pieces_pos(*p, i as _);
}
self.main_window.unwrap().set_moves(0);
self.apply_tiles_left();
}
fn apply_tiles_left(&mut self) {
let left = 15 - self.positions.iter().enumerate().filter(|(i, x)| *i as i8 == **x).count();
self.main_window.unwrap().set_tiles_left(left as _);
self.finished = left == 0;
}
fn piece_clicked(&mut self, p: i8) -> bool {
let piece = self.pieces.row_data(p as usize).unwrap_or_default();
assert_eq!(self.positions[(piece.pos_x * 4 + piece.pos_y) as usize], p);
// find the coordinate of the hole.
let hole = self.positions.iter().position(|x| *x == -1).unwrap() as i8;
let pos = (piece.pos_x * 4 + piece.pos_y) as i8;
let sign = if pos > hole { -1 } else { 1 };
if hole % 4 == piece.pos_y as i8 {
self.slide(pos, sign * 4)
} else if hole / 4 == piece.pos_x as i8 {
self.slide(pos, sign)
} else {
self.speed_for_kick_animation[p as usize] = (
if hole % 4 > piece.pos_y as i8 { 10. } else { -10. },
if hole / 4 > piece.pos_x as i8 { 10. } else { -10. },
);
return false;
};
self.apply_tiles_left();
if let Some(x) = self.main_window.upgrade() {
x.set_moves(x.get_moves() + 1);
}
true
}
fn slide(&mut self, pos: i8, offset: i8) {
let mut swap = pos;
while self.positions[pos as usize] != -1 {
swap += offset;
self.positions.swap(pos as usize, swap as usize);
self.set_pieces_pos(self.positions[swap as usize] as _, swap);
}
}
fn random_move(&mut self) {
let mut rng = rand::thread_rng();
let hole = self.positions.iter().position(|x| *x == -1).unwrap() as i8;
let mut p;
loop {
p = rand::Rng::gen_range(&mut rng, 0..16);
if hole == p {
continue;
} else if (hole % 4 == p % 4) || (hole / 4 == p / 4) {
break;
}
}
let p = self.positions[p as usize];
self.piece_clicked(p);
}
/// Advance the kick animation
fn kick_animation(&mut self) {
/// update offset and speed, returns true if the animation is still running
fn spring_animation(offset: &mut f32, speed: &mut f32) -> bool {
const C: f32 = 0.3; // Constant = k/m
const DAMP: f32 = 0.7;
const EPS: f32 = 0.3;
let acceleration = -*offset * C;
*speed += acceleration;
*speed *= DAMP;
if *speed != 0. || *offset != 0. {
*offset += *speed;
if speed.abs() < EPS && offset.abs() < EPS {
*speed = 0.;
*offset = 0.;
}
true
} else {
false
}
}
let mut has_animation = false;
for idx in 0..15 {
let mut p = self.pieces.row_data(idx).unwrap_or_default();
let ax = spring_animation(&mut p.offset_x, &mut self.speed_for_kick_animation[idx].0);
let ay = spring_animation(&mut p.offset_y, &mut self.speed_for_kick_animation[idx].1);
if ax || ay {
self.pieces.set_row_data(idx, p);
has_animation = true;
}
}
if !has_animation {
self.kick_animation_timer.stop();
}
}
}
#[cfg_attr(target_arch = "wasm32", wasm_bindgen(start))]
pub fn main() {
// This provides better error messages in debug mode.
// It's disabled in release mode so it doesn't bloat up the file size.
#[cfg(all(debug_assertions, target_arch = "wasm32"))]
console_error_panic_hook::set_once();
let main_window = MainWindow::new().unwrap();
#[cfg(target_arch = "wasm32")]
handle_resize(main_window.as_weak());
let state = Rc::new(RefCell::new(AppState {
pieces: Rc::new(slint::VecModel::<Piece>::from(vec![Piece::default(); 15])),
main_window: main_window.as_weak(),
positions: vec![],
auto_play_timer: Default::default(),
kick_animation_timer: Default::default(),
speed_for_kick_animation: Default::default(),
finished: false,
}));
state.borrow_mut().randomize();
main_window.set_pieces(state.borrow().pieces.clone().into());
let state_copy = state.clone();
main_window.on_piece_clicked(move |p| {
state_copy.borrow().auto_play_timer.stop();
state_copy.borrow().main_window.unwrap().set_auto_play(false);
if state_copy.borrow().finished {
return;
}
if !state_copy.borrow_mut().piece_clicked(p as i8) {
let state_weak = Rc::downgrade(&state_copy);
state_copy.borrow().kick_animation_timer.start(
slint::TimerMode::Repeated,
std::time::Duration::from_millis(16),
move || {
if let Some(state) = state_weak.upgrade() {
state.borrow_mut().kick_animation();
}
},
);
}
});
let state_copy = state.clone();
main_window.on_reset(move || {
state_copy.borrow().auto_play_timer.stop();
state_copy.borrow().main_window.unwrap().set_auto_play(false);
state_copy.borrow_mut().randomize();
});
let state_copy = state;
main_window.on_enable_auto_mode(move |enabled| {
if enabled {
let state_weak = Rc::downgrade(&state_copy);
state_copy.borrow().auto_play_timer.start(
slint::TimerMode::Repeated,
std::time::Duration::from_millis(200),
move || {
if let Some(state) = state_weak.upgrade() {
state.borrow_mut().random_move();
}
},
);
} else {
state_copy.borrow().auto_play_timer.stop();
}
});
main_window.run().unwrap();
}
#[cfg(target_arch = "wasm32")]
/// winit doesn't handle the resizing of the canvas from CSS well
/// https://github.com/rust-windowing/winit/issues/1661
/// in the mean time, adjust the size manually
fn handle_resize(slint_window: slint::Weak<MainWindow>) -> Option<()> {
let window = web_sys::window()?;
let resize_handler = move || {
let window = web_sys::window()?;
let doc = window.document()?;
let container = doc.get_element_by_id("container")?;
let children = container.children();
let mut height_sum = 0.;
for i in 0..children.length() {
let child = children.item(i).unwrap();
if child.tag_name().to_lowercase() == "canvas" {
continue;
}
let style = window.get_computed_style(&child).ok()?;
let get_margin = |m| {
style.as_ref()?.get_property_value(m).ok()?.strip_suffix("px")?.parse::<f32>().ok()
};
height_sum += child.scroll_height() as f32
+ get_margin("margin-top").unwrap_or(0.)
+ get_margin("margin-bottom").unwrap_or(0.)
+ 1.;
}
let width = doc.body()?.client_width() as f32;
let height = doc.body()?.client_height() as f32 - height_sum;
slint_window.upgrade()?.window().set_size(slint::LogicalSize { width, height });
Some(())
};
resize_handler();
let closure = Closure::wrap(Box::new(move || drop(resize_handler())) as Box<dyn FnMut()>);
window.set_onresize(Some(closure.as_ref().unchecked_ref()));
closure.forget();
Some(())
}