This repository has been archived by the owner on Apr 23, 2023. It is now read-only.
/
MainPage.xaml.cs
414 lines (351 loc) · 13.5 KB
/
MainPage.xaml.cs
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
using System;
using System.ComponentModel;
using Xamarin.Forms;
using Xamarin.Forms.DualScreen;
using Xamarin.Essentials;
namespace HingeIt
{
/// <summary>
/// The MainPage contains functionallity for the master and
/// the detail page.
/// </summary>
[DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
/// <summary>
/// Determines the state of the page.
/// </summary>
enum PageState
{
/// <summary>
/// App runs on a non supported device.
/// </summary>
UnsupportedDevice,
/// <summary>
/// App runs on a non supported orienation.
/// </summary>
UnsupportedOrientation,
/// <summary>
/// App runs capable of running the game.
/// </summary>
Game,
/// <summary>
/// User has succeeded.
/// </summary>
UserSucceeded
}
#region Private member
/// <summary>
/// Determines if the app is spanned across both screens.
/// </summary>
static bool IsSpanned => DualScreenInfo.Current.SpanMode == TwoPaneViewMode.Wide;
/// <summary>
/// Determines if the app runs in potrait mode.
/// </summary>
static bool IsPortrait => DualScreenInfo.Current.IsLandscape == false;
/// <summary>
/// Name of the angle changed event.
/// </summary>
readonly string ANGLE_CHANGED_EVENT_NAME = "HingeSensorChanged";
/// <summary>
/// Time span between each angle timer tick.
/// </summary>
readonly TimeSpan ANGLE_CHANGE_TIMEPAN = TimeSpan.FromMilliseconds(500);
/// <summary>
/// Minimum possible angle of the hinge.
/// TODO: Find correct value.
/// </summary>
readonly int ANGLE_MIN_VALUE = 0;
/// <summary>
/// Maximum possible angle of the hinge.
/// TODO: Find correct value.
/// </summary>
readonly int ANGLE_MAX_VALUE = 360;
/// <summary>
/// Threshold for the target (+-).
/// </summary>
readonly int ANGLE_THRESHOLD = 5;
/// <summary>
/// Angle target which the player has to find.
/// </summary>
int targetAngle;
/// <summary>
/// Current angle of the device.
/// </summary>
int currentAngle;
/// <summary>
/// Determines if the timer should stop.
/// </summary>
bool stopTargetRandomizerTimer = false;
/// <summary>
/// Hinging start time
/// </summary>
DateTime hingingStartTime;
/// <summary>
/// Sensor events will be ignored.
/// </summary>
bool ingoreSensorEvents = true;
/// <summary>
/// Underlying random engine.
/// </summary>
readonly Random random = new Random();
#endregion
#region Constructor
/// <summary>
/// Constructor.
///
/// Lesson learned:
/// Will be called each time the layout changes. (?!)
/// </summary>
public MainPage()
{
InitializeComponent();
// Update Page to current state.
UpdateUi();
// Add event listener for changed properties.
DualScreenInfo.Current.PropertyChanged += Current_PropertyChanged;
}
protected override void OnAppearing()
{
base.OnAppearing();
MessagingCenter.Subscribe<string>(this, ANGLE_CHANGED_EVENT_NAME, (angle) => {
Device.BeginInvokeOnMainThread(() => {
OnHingeSensorChanged(int.Parse(angle));
});
});
}
protected override void OnDisappearing()
{
base.OnDisappearing();
MessagingCenter.Unsubscribe<string>(this, ANGLE_CHANGED_EVENT_NAME);
}
#endregion
#region Event handler
/// <summary>
/// Called when ever an `ANGLE_CHANGED_EVENT_NAME` notification
/// is raised.
/// </summary>
/// <param name="angle">New angle value.</param>
private void OnHingeSensorChanged(int angle)
{
// Store current angle.
currentAngle = angle;
if (ingoreSensorEvents) return;
// Update page.
UpdateUi();
}
/// <summary>
/// Called on any DualScreenInfo property changed event.
/// </summary>
/// <param name="sender">Sender.</param>
/// <param name="e">Event args.</param>
private void Current_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
// Check if changed property is a layout related one.
if (e.PropertyName == "SpanMode")
{
UpdateUi();
}
}
/// <summary>
/// Called on each timer tick.
/// Will randomize the target angle value.
/// </summary>
/// <returns>True if timer should tick further.</returns>
private bool Timer_Ticked()
{
// Ensure ticker should tick (abort of stop timer is already set)
if (stopTargetRandomizerTimer) return true;
// Get random angle and store.
targetAngle = random.Next(ANGLE_MIN_VALUE, ANGLE_MAX_VALUE);
// Update label with three 000 to 360.
AngleTargetLabel.Text = $"{targetAngle:D3}°";
// Check if timer should be stopped.
return stopTargetRandomizerTimer == false;
}
/// <summary>
/// Start button tapped.
///
/// Stops the timer and starts the actual game.
/// </summary>
/// <param name="sender">Button as sender</param>
/// <param name="e">Event args.</param>
private void StartButton_Clicked(object sender, EventArgs e)
{
stopTargetRandomizerTimer = true;
hingingStartTime = DateTime.Now;
UpdateUi();
}
/// <summary>
/// Share button tapped.
/// </summary>
/// <param name="sender">Button as sender</param>
/// <param name="e">Event args.</param>
private void ShareButton_Clicked(object sender, EventArgs e)
{
PresentShareSheet();
}
/// <summary>
/// Try again button tapped.
/// </summary>
/// <param name="sender">Button as sender</param>
/// <param name="e">Event args.</param>
private void TryAgainButton_Clicked(object sender, EventArgs e)
{
// Reset app state.
targetAngle = 0;
stopTargetRandomizerTimer = false;
UpdateUi();
}
#endregion
#region Private helper
/// <summary>
/// Gets the page state according to the layout and device type.
/// </summary>
/// <returns>Current page state.</returns>
private PageState GetPageState()
{
// Ensure the app runs on a Surface Duo.
if (DualScreenInfo.Current.HingeBounds == null) return PageState.UnsupportedDevice;
// Ensure that the app is in portrait mode and spanned across both screens.
if (!IsSpanned || !IsPortrait) return PageState.UnsupportedOrientation;
// Check if current angle is within target threshold
if (currentAngle != 0 && currentAngle >= targetAngle - ANGLE_THRESHOLD && currentAngle <= targetAngle + ANGLE_THRESHOLD) return PageState.UserSucceeded;
// If everything is correct, the game is playable.
return PageState.Game;
}
/// <summary>
/// Updates the page to current state.
/// </summary>
private void UpdateUi()
{
// Get current state.
var state = GetPageState();
// Update controls.
ResultSuccessTextLabel.IsVisible = state == PageState.UserSucceeded;
GameStackLayout.IsVisible = state == PageState.Game;
WinStackLayout.IsVisible = state == PageState.UserSucceeded;
ErrorStackLayout.IsVisible = state != PageState.Game;
ErrorTitleLabel.Text = GetErrorTitleForState(state);
ErrorMessageLabel.Text = GetErrorMessageForState(state);
BackgroundView.BackgroundGradientStops = GetGradientForState(state);
ingoreSensorEvents = true;
// Check for diffrent state combinations.
if (state == PageState.Game && !stopTargetRandomizerTimer)
{
// Start timer.
Device.StartTimer(ANGLE_CHANGE_TIMEPAN, Timer_Ticked);
}
else if (state == PageState.Game && stopTargetRandomizerTimer)
{
ingoreSensorEvents = false;
ResultAngleLabel.Text = $"{currentAngle:D3}°";
BackgroundView.BackgroundGradientStops = GetGradientCurrentAngle();
}
else if (state == PageState.UserSucceeded)
{
ResultAngleLabel.Text = $"{targetAngle:D3}°";
DurationLabel.Text = $"{(DateTime.Now - hingingStartTime).Seconds}s";
}
else
{
ResultAngleLabel.Text = "? °";
}
}
/// <summary>
/// Gets the background gradient stops according to the current angle.
/// </summary>
/// <returns>Gradient stops according to the current an angle.</returns>
private Xamarin.Forms.PancakeView.GradientStopCollection GetGradientCurrentAngle()
{
if (Math.Abs(targetAngle - currentAngle) < 45)
{
return new Xamarin.Forms.PancakeView.GradientStopCollection
{
new Xamarin.Forms.PancakeView.GradientStop { Color = Color.DarkOrange, Offset = 0 },
new Xamarin.Forms.PancakeView.GradientStop { Color = Color.OrangeRed, Offset = 0.5f }
};
}
else
{
return new Xamarin.Forms.PancakeView.GradientStopCollection
{
new Xamarin.Forms.PancakeView.GradientStop { Color = Color.IndianRed, Offset = 0 },
new Xamarin.Forms.PancakeView.GradientStop { Color = Color.DarkRed, Offset = 0.5f }
};
}
}
/// <summary>
/// Gets the background gradient stops according to the current state.
/// </summary>
/// <returns>Gradient stops according to the current an state.</returns>
private Xamarin.Forms.PancakeView.GradientStopCollection GetGradientForState(PageState state)
{
switch(state)
{
case PageState.UnsupportedDevice:
case PageState.UnsupportedOrientation:
return new Xamarin.Forms.PancakeView.GradientStopCollection
{
new Xamarin.Forms.PancakeView.GradientStop { Color = Color.Gray, Offset = 0 },
new Xamarin.Forms.PancakeView.GradientStop { Color = Color.DarkGray, Offset = 0.5f }
};
case PageState.Game:
return GetGradientCurrentAngle();
case PageState.UserSucceeded:
return new Xamarin.Forms.PancakeView.GradientStopCollection
{
new Xamarin.Forms.PancakeView.GradientStop { Color = Color.LightSeaGreen, Offset = 0 },
new Xamarin.Forms.PancakeView.GradientStop { Color = Color.DarkOliveGreen, Offset = 0.5f }
};
}
return new Xamarin.Forms.PancakeView.GradientStopCollection();
}
/// <summary>
/// Gets the error title for given state.
/// </summary>
/// <param name="state">Underlying state.</param>
/// <returns>Error title for state.</returns>
private string GetErrorTitleForState(PageState state)
{
switch(state)
{
case PageState.UnsupportedDevice:
return "Unsupported device";
case PageState.UnsupportedOrientation:
return "Unsupported orientation";
default:
return "";
}
}
/// <summary>
/// Gets the error message for given state.
/// </summary>
/// <param name="state">Underlying state.</param>
/// <returns>Error message for state.</returns>
private string GetErrorMessageForState(PageState state)
{
switch(state)
{
case PageState.UnsupportedDevice:
return "HingeIt! is only supported on a Microsoft Surface Duo.";
case PageState.UnsupportedOrientation:
return "Please use portrait mode and span the app across both displays.";
default:
return "";
}
}
/// <summary>
/// Presents async a share sheet with a win message.
/// </summary>
private async void PresentShareSheet()
{
await Share.RequestAsync(new ShareTextRequest
{
Title = "Share your score!",
Text = $"It took only {DurationLabel.Text} to hinge my Surface Duo correctly! #HingeIt"
});
}
#endregion
}
}