-
Notifications
You must be signed in to change notification settings - Fork 0
/
master-mind.c
1493 lines (1273 loc) · 41.7 KB
/
master-mind.c
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* CW spec: https://www.macs.hw.ac.uk/~hwloidl/Courses/F28HS/F28HS_CW2_2022.pdf
* This repo: https://gitlab-student.macs.hw.ac.uk/f28hs-2021-22/f28hs-2021-22-staff/f28hs-2021-22-cwk2-sys
* Compile:
gcc -c -o lcdBinary.o lcdBinary.c
gcc -c -o master-mind.o master-mind.c
gcc -o master-mind master-mind.o lcdBinary.o
* Run:
sudo ./master-mind
OR use the Makefile to build
> make all
and run
> make run
and test
> make test
***********************************************************************
* The Low-level interface to LED, button, and LCD is based on:
* wiringPi libraries by
* Copyright (c) 2012-2013 Gordon Henderson.
***********************************************************************
* See:
* https://projects.drogon.net/raspberry-pi/wiringpi/
*
* wiringPi is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* wiringPi is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with wiringPi. If not, see <http://www.gnu.org/licenses/>.
***********************************************************************
*/
/* ======================================================= */
/* SECTION: includes */
/* ------------------------------------------------------- */
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdarg.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <sys/time.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
/* --------------------------------------------------------------------------- */
/* Config settings */
/* you can use CPP flags to e.g. print extra debugging messages */
/* or switch between different versions of the code e.g. digitalWrite() in Assembler */
#define DEBUG
#undef ASM_CODE
// =======================================================
// Tunables
// PINs (based on BCM numbering)
// For wiring see CW spec: https://www.macs.hw.ac.uk/~hwloidl/Courses/F28HS/F28HS_CW2_2022.pdf
// GPIO pin for green LED
#define GREEN 13
// GPIO pin for red LED
#define RED 5
// GPIO pin for button
#define BUTTON 19
// =======================================================
// delay for loop iterations (mainly), in ms
// in mili-seconds: 0.2s
#define DELAY 200
// in micro-seconds: 3s
#define TIMEOUT 3000000
// =======================================================
// APP constants ---------------------------------
// number of colours and length of the sequence
#define COLS 3
#define SEQL 3
// =======================================================
// generic constants
#ifndef TRUE
#define TRUE (1 == 1)
#define FALSE (1 == 2)
#endif
#define PAGE_SIZE (4 * 1024)
#define BLOCK_SIZE (4 * 1024)
#define INPUT 0
#define OUTPUT 1
#define LOW 0
#define HIGH 1
// =======================================================
// Wiring (see inlined initialisation routine)
#define STRB_PIN 24
#define RS_PIN 25
#define DATA0_PIN 23
#define DATA1_PIN 10
#define DATA2_PIN 27
#define DATA3_PIN 22
/* ======================================================= */
/* SECTION: constants and prototypes */
/* ------------------------------------------------------- */
// =======================================================
// char data for the CGRAM, i.e. defining new characters for the display
static unsigned char newChar[8] =
{
0b11111,
0b10001,
0b10001,
0b10101,
0b11111,
0b10001,
0b10001,
0b11111,
};
static unsigned char hawoNewChar[8] =
{
0b11111,
0b10001,
0b10001,
0b10001,
0b10001,
0b10001,
0b10001,
0b11111,
};
/* Constants */
static const int colors = COLS;
static const int seqlen = SEQL;
static char *color_names[] = {"red", "green", "blue"};
static int *theSeq = NULL;
static int *seq1, *seq2, *cpy1, *cpy2;
/* --------------------------------------------------------------------------- */
// data structure holding data on the representation of the LCD
struct lcdDataStruct
{
int bits, rows, cols;
int rsPin, strbPin;
int dataPins[8];
int cx, cy;
};
static int lcdControl;
/* ***************************************************************************** */
/* INLINED fcts from wiringPi/devLib/lcd.c: */
// HD44780U Commands (see Fig 11, p28 of the Hitachi HD44780U datasheet)
#define LCD_CLEAR 0x01
#define LCD_HOME 0x02
#define LCD_ENTRY 0x04
#define LCD_CTRL 0x08
#define LCD_CDSHIFT 0x10
#define LCD_FUNC 0x20
#define LCD_CGRAM 0x40
#define LCD_DGRAM 0x80
// Bits in the entry register
#define LCD_ENTRY_SH 0x01
#define LCD_ENTRY_ID 0x02
// Bits in the control register
#define LCD_BLINK_CTRL 0x01
#define LCD_CURSOR_CTRL 0x02
#define LCD_DISPLAY_CTRL 0x04
// Bits in the function register
#define LCD_FUNC_F 0x04
#define LCD_FUNC_N 0x08
#define LCD_FUNC_DL 0x10
#define LCD_CDSHIFT_RL 0x04
// Mask for the bottom 64 pins which belong to the Raspberry Pi
// The others are available for the other devices
#define PI_GPIO_MASK (0xFFFFFFC0)
static unsigned int gpiobase;
static uint32_t *gpio;
static int timed_out = 0;
/* ======================================================= */
/* SECTION: Aux function */
/* ------------------------------------------------------- */
/* misc aux functions */
int failure(int fatal, const char *message, ...)
{
va_list argp;
char buffer[1024];
if (!fatal)
return -1;
va_start(argp, message);
vsnprintf(buffer, 1023, message, argp);
va_end(argp);
fprintf(stderr, "%s", buffer);
exit(EXIT_FAILURE);
return 0;
}
/*
* waitForEnter:
*********************************************************************************
*/
void waitForEnter(void)
{
printf("Press ENTER to continue: ");
(void)fgetc(stdin);
}
/* ======================================================= */
/* SECTION: TIMER code */
/* ------------------------------------------------------- */
/* TIMER code */
/* timestamps needed to implement a time-out mechanism */
static uint64_t startT, stopT;
/* you may need this function in timer_handler() below */
/* use the libc fct gettimeofday() to implement it */
uint64_t timeInMicroseconds()
{
struct timeval tv;
uint64_t now;
gettimeofday(&tv, NULL);
now = (uint64_t)tv.tv_sec * (uint64_t)1000000 + (uint64_t)tv.tv_usec; // in us
// now = (uint64_t)tv.tv_sec * (uint64_t)1000 + (uint64_t)(tv.tv_usec / 1000) ; // in ms
return (uint64_t)now;
}
/* this should be the callback, triggered via an interval timer, */
/* that is set-up through a call to sigaction() in the main fct. */
void timer_handler(int signum)
{
//static int count = 0;
stopT = timeInMicroseconds();
//count++;
//fprintf(stderr, "timer expired %d times; (measured interval %f sec)\n", count, (stopT - startT) / 1000000.0);
startT = timeInMicroseconds();
}
/* initialise time-stamps, setup an interval timer, and install the timer_handler callback */
// Isn't needed since Professor said delay can be used instead
void initITimer(uint64_t timeout)
{
/* *** COMPLETE the code here *** */
}
/* From wiringPi code; comment by Gordon Henderson
* delayMicroseconds:
* This is somewhat intersting. It seems that on the Pi, a single call
* to nanosleep takes some 80 to 130 microseconds anyway, so while
* obeying the standards (may take longer), it's not always what we
* want!
*
* So what I'll do now is if the delay is less than 100uS we'll do it
* in a hard loop, watching a built-in counter on the ARM chip. This is
* somewhat sub-optimal in that it uses 100% CPU, something not an issue
* in a microcontroller, but under a multi-tasking, multi-user OS, it's
* wastefull, however we've no real choice )-:
*
* Plan B: It seems all might not be well with that plan, so changing it
* to use gettimeofday () and poll on that instead...
*********************************************************************************
*/
void delayMicroseconds(unsigned int howLong)
{
struct timespec sleeper;
unsigned int uSecs = howLong % 1000000;
unsigned int wSecs = howLong / 1000000;
/**/ if (howLong == 0)
return;
#if 0
else if (howLong < 100)
delayMicrosecondsHard (howLong) ;
#endif
else
{
sleeper.tv_sec = wSecs;
sleeper.tv_nsec = (long)(uSecs * 1000L);
nanosleep(&sleeper, NULL);
}
}
/*
* delay:
* Wait for some number of milliseconds
*********************************************************************************
*/
void delay(unsigned int howLong)
{
struct timespec sleeper, dummy;
sleeper.tv_sec = (time_t)(howLong / 1000);
sleeper.tv_nsec = (long)(howLong % 1000) * 1000000;
nanosleep(&sleeper, &dummy);
}
/* ======================================================= */
/* SECTION: hardware interface (LED, button, LCD display) */
/* ------------------------------------------------------- */
/* low-level interface to the hardware */
/* sends a @value (LOW or HIGH) on pin number @pin; @gpio@ is the mmaped GPIO base address */
void digitalWrite(uint32_t *gpio, int pin, int value)
{
int off, res;
off = (value == LOW) ? 10 : 7;
asm volatile(
"\tLDR R1, %[gpio]\n"
"\tADD R0, R1, %[off]\n"
"\tMOV R2, #1\n"
"\tMOV R1, %[pin]\n"
"\tAND R1, #31\n"
"\tLSL R2, R1\n"
"\tSTR R2, [R0, #0]\n"
"\tMOV %[result], R2\n"
: [result] "=r"(res)
: [pin] "r"(pin), [gpio] "m"(gpio), [off] "r"(off * 4)
: "r0", "r1", "r2", "cc");
}
/* sets the @mode of a GPIO @pin to INPUT or OUTPUT; @gpio is the mmaped GPIO base address */
void pinMode(uint32_t *gpio, int pin, int mode)
{
int fSel = pin / 10;
int shift = (pin % 10) * 3;
int res;
// output
if (mode == OUTPUT)
{
asm(/* inline assembler version of setting to ouput" */
"\tLDR R1, %[gpio]\n"
"\tADD R0, R1, %[fSel]\n"
"\tLDR R1, [R0, #0]\n"
"\tMOV R2, #0b111\n"
"\tLSL R2, %[shift]\n"
"\tBIC R1, R1, R2\n"
"\tMOV R2, #1\n"
"\tLSL R2, %[shift]\n"
"\tORR R1, R2\n"
"\tSTR R1, [R0, #0]\n"
"\tMOV %[result], R1\n"
: [result] "=r"(res)
: [pin] "r"(pin), [gpio] "m"(gpio), [fSel] "r"(fSel * 4), [shift] "r"(shift)
: "r0", "r1", "r2", "cc");
}
// input
else if (mode == INPUT)
{
asm(/* inline assembler version of setting to input" */
"\tLDR R1, %[gpio]\n"
"\tADD R0, R1, %[fSel]\n"
"\tLDR R1, [R0, #0]\n"
"\tMOV R2, #0b111\n"
"\tLSL R2, %[shift]\n"
"\tBIC R1, R1, R2\n"
"\tSTR R1, [R0, #0]\n"
"\tMOV %[result], R1\n"
: [result] "=r"(res)
: [pin] "r"(pin), [gpio] "m"(gpio), [fSel] "r"(fSel * 4), [shift] "r"(shift)
: "r0", "r1", "r2", "cc");
}
else
{
fprintf(stderr, "Invalid mode");
}
}
/* sends a @value (LOW or HIGH) on pin number @pin; @gpio is the mmaped GPIO base address */
void writeLED(uint32_t *gpio, int led, int value)
{
int off, res;
if (value == LOW)
{
off = 10;
asm volatile(
/*inline assembler version of clearing LED*/
"\tLDR R1, %[gpio]\n"
"\tADD R0, R1, %[off]\n"
"\tMOV R2, #1\n"
"\tMOV R1, %[pin]\n"
"\tAND R1, #31\n"
"\tLSL R2, R1\n"
"\tSTR R2, [R0,#0]\n"
"\tMOV %[result], R2\n"
: [result] "=r"(res)
: [pin] "r"(led), [gpio] "m"(gpio), [off] "r"(off * 4)
: "r0", "r1", "r2", "cc");
}
else
{
off = 7;
asm volatile(
/*inline assembler version of setting LED*/
"\tLDR R1, %[gpio]\n"
"\tADD R0, R1, %[off]\n"
"\tMOV R2, #1\n"
"\tMOV R1, %[pin]\n"
"\tAND R1, #31\n"
"\tLSL R2, R1\n"
"\tSTR R2, [R0,#0]\n"
"\tMOV %[result], R2\n"
: [result] "=r"(res)
: [pin] "r"(led), [gpio] "m"(gpio), [off] "r"(off * 4)
: "r0", "r1", "r2", "cc");
}
}
/* reads a @value (LOW or HIGH) from pin number @pin (a button device); @gpio is the mmaped GPIO base address */
int readButton(uint32_t *gpio, int button)
{
int state = 0;
asm volatile(
"MOV R1, %[gpio]\n"
"LDR R2, [R1, #0x34]\n"
"MOV R3, %[pin]\n"
"MOV R4, #1\n"
"LSL R4, R3\n"
"AND %[state], R2, R4\n"
: [state] "=r"(state)
: [pin] "r"(button), [gpio] "r"(gpio)
: "r0", "r1", "r2", "r3", "r4", "cc");
return state > 0;
}
/* waits for a button input on pin number @button; @gpio@ is the mmaped GPIO base address */
/* uses readButton() */
void waitForButton(uint32_t *gpio, int button)
{
for (int j = 0; j < 13; j++)
{
if (readButton(gpio, button))
break;
delay(DELAY);
}
}
/* ======================================================= */
/* SECTION: aux functions for game logic */
/* ------------------------------------------------------- */
/* --------------------------------------------------------------------------- */
/* interface on top of the low-level pin I/O code */
/* blink the led on pin @led, @c times */
void blinkN(uint32_t *gpio, int led, int c)
{
for (int i = 0; i < c; i++)
{
// Writes to LED to turn it on
writeLED(gpio, led, HIGH);
delay(700);
// Writes to LED to turn it off
writeLED(gpio, led, LOW);
delay(700);
}
}
/* ======================================================= */
/* SECTION: LCD functions */
/* ------------------------------------------------------- */
/* medium-level interface functions (all in C) */
/* from wiringPi:
* strobe:
* Toggle the strobe (Really the "E") pin to the device.
* According to the docs, data is latched on the falling edge.
*********************************************************************************
*/
void strobe(const struct lcdDataStruct *lcd)
{
// timing changes for new version of delayMicroseconds ()
digitalWrite(gpio, lcd->strbPin, 1);
delayMicroseconds(50);
digitalWrite(gpio, lcd->strbPin, 0);
delayMicroseconds(50);
}
/*
* sentDataCmd:
* Send some data or command byte to the display.
*********************************************************************************
*/
void sendDataCmd(const struct lcdDataStruct *lcd, unsigned char data)
{
register unsigned char myData = data;
unsigned char i, d4;
if (lcd->bits == 4)
{
d4 = (myData >> 4) & 0x0F;
for (i = 0; i < 4; ++i)
{
digitalWrite(gpio, lcd->dataPins[i], (d4 & 1));
d4 >>= 1;
}
strobe(lcd);
d4 = myData & 0x0F;
for (i = 0; i < 4; ++i)
{
digitalWrite(gpio, lcd->dataPins[i], (d4 & 1));
d4 >>= 1;
}
}
else
{
for (i = 0; i < 8; ++i)
{
digitalWrite(gpio, lcd->dataPins[i], (myData & 1));
myData >>= 1;
}
}
strobe(lcd);
}
/*
* lcdPutCommand:
* Send a command byte to the display
*********************************************************************************
*/
void lcdPutCommand(const struct lcdDataStruct *lcd, unsigned char command)
{
// #ifdef DEBUG
// fprintf(stderr, "lcdPutCommand: digitalWrite(%d,%d) and sendDataCmd(%d,%d)\n", lcd->rsPin, 0, lcd, command);
// #endif
digitalWrite(gpio, lcd->rsPin, 0);
sendDataCmd(lcd, command);
delay(2);
}
void lcdPut4Command(const struct lcdDataStruct *lcd, unsigned char command)
{
register unsigned char myCommand = command;
register unsigned char i;
digitalWrite(gpio, lcd->rsPin, 0);
for (i = 0; i < 4; ++i)
{
digitalWrite(gpio, lcd->dataPins[i], (myCommand & 1));
myCommand >>= 1;
}
strobe(lcd);
}
/*
* lcdHome: lcdClear:
* Home the cursor or clear the screen.
*********************************************************************************
*/
void lcdHome(struct lcdDataStruct *lcd)
{
#ifdef DEBUG
fprintf(stderr, "lcdHome: lcdPutCommand(%d,%d)\n", lcd, LCD_HOME);
#endif
lcdPutCommand(lcd, LCD_HOME);
lcd->cx = lcd->cy = 0;
delay(5);
}
void lcdClear(struct lcdDataStruct *lcd)
{
// #ifdef DEBUG
// fprintf(stderr, "lcdClear: lcdPutCommand(%d,%d) and lcdPutCommand(%d,%d)\n", lcd, LCD_CLEAR, lcd, LCD_HOME);
// #endif
lcdPutCommand(lcd, LCD_CLEAR);
lcdPutCommand(lcd, LCD_HOME);
lcd->cx = lcd->cy = 0;
delay(5);
}
/*
* lcdPosition:
* Updates the position of the cursor on the display.
* Ignores invalid locations.
*********************************************************************************
*/
void lcdPosition(struct lcdDataStruct *lcd, int x, int y)
{
if ((x > lcd->cols) || (x < 0))
return;
if ((y > lcd->rows) || (y < 0))
return;
lcdPutCommand(lcd, x + (LCD_DGRAM | (y > 0 ? 0x40 : 0x00) /* rowOff [y] */));
lcd->cx = x;
lcd->cy = y;
}
/*
* lcdDisplay: lcdCursor: lcdCursorBlink:
* Turn the display, cursor, cursor blinking on/off
*********************************************************************************
*/
void lcdDisplay(struct lcdDataStruct *lcd, int state)
{
if (state)
lcdControl |= LCD_DISPLAY_CTRL;
else
lcdControl &= ~LCD_DISPLAY_CTRL;
lcdPutCommand(lcd, LCD_CTRL | lcdControl);
}
void lcdCursor(struct lcdDataStruct *lcd, int state)
{
if (state)
lcdControl |= LCD_CURSOR_CTRL;
else
lcdControl &= ~LCD_CURSOR_CTRL;
lcdPutCommand(lcd, LCD_CTRL | lcdControl);
}
void lcdCursorBlink(struct lcdDataStruct *lcd, int state)
{
if (state)
lcdControl |= LCD_BLINK_CTRL;
else
lcdControl &= ~LCD_BLINK_CTRL;
lcdPutCommand(lcd, LCD_CTRL | lcdControl);
}
/*
* lcdPutchar:
* Send a data byte to be displayed on the display. We implement a very
* simple terminal here - with line wrapping, but no scrolling. Yet.
*********************************************************************************
*/
void lcdPutchar(struct lcdDataStruct *lcd, unsigned char data)
{
digitalWrite(gpio, lcd->rsPin, 1);
sendDataCmd(lcd, data);
if (++lcd->cx == lcd->cols)
{
lcd->cx = 0;
if (++lcd->cy == lcd->rows)
lcd->cy = 0;
// inline computation of address
lcdPutCommand(lcd, lcd->cx + (LCD_DGRAM | (lcd->cy > 0 ? 0x40 : 0x00) /* rowOff [lcd->cy] */));
}
}
/*
* lcdPuts:
* Send a string to be displayed on the display
*********************************************************************************
*/
void lcdPuts(struct lcdDataStruct *lcd, const char *string)
{
while (*string)
lcdPutchar(lcd, *string++);
}
/* ======================================================= */
/* SECTION: helper functions */
/* ------------------------------------------------------- */
/* Helper functions for help with game logic */
/* Function to concat two individual digits
Reference: https://stackoverflow.com/questions/12700497/how-to-concatenate-two-integers-in-c*/
int concat(int x, int y)
{
int temp = y;
do
{
x *= 10;
y /= 10;
} while (y != 0);
return x + temp;
}
/* Function to reverse arr[] from start to end*/
void reverse(int arr[], int start, int end)
{
int temp;
while (start < end)
{
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
/* Helper function to show user guess on terminal */
void showGuess(int colorNum, struct lcdDataStruct *lcd)
{
switch (colorNum)
{
case 1:
lcdPuts(lcd, " R");
fprintf(stderr, " R");
break;
case 2:
lcdPuts(lcd, " G");
fprintf(stderr, " G");
break;
case 3:
lcdPuts(lcd, " B");
fprintf(stderr, " B");
break;
}
}
/* Helper function to show user guess on LCD */
void showMatchesLCD(int code, struct lcdDataStruct *lcd)
{
// Variable as index value
int index = 0;
// Temporary array to store encoded values
int *temp = (int *)malloc(2 * sizeof(int));
char *text = (char *)malloc(3 * sizeof(char)); // rifrof
// While loop to split code digits into array
// If passed argument 'code' is not 0, and the current index is less than the length of secret sequence
while (code != 0 && index < seqlen)
{
temp[index] = code % 10;
++index;
code /= 10;
}
// Store digits in respective int values
int approx = temp[0];
int correct = temp[1];
// Print out correct and approximate values to terminal
// printf("Exact: %d Approximate: %d\n\n", correct, approx);
printf("%d exact\n", correct);
printf("%d approximate\n", approx);
// Free temp array
free(temp);
lcdPosition(lcd, 0, 1);
lcdPuts(lcd, "Exact: ");
sprintf(text, "%d", correct);
lcdPosition(lcd, 6, 1);
lcdPuts(lcd, text);
blinkN(gpio, GREEN, correct);
blinkN(gpio, RED, 1);
lcdPosition(lcd, 8, 1);
lcdPuts(lcd, "Approx: ");
sprintf(text, "%d", approx);
lcdPosition(lcd, 15, 1);
lcdPuts(lcd, text);
blinkN(gpio, GREEN, approx);
}
/* ======================================================= */
/* SECTION: game logic */
/* ------------------------------------------------------- */
/* AUX fcts of the game logic */
/* initialise the secret sequence; by default it should be a random sequence */
void initSeq()
{
// Allocating memory for array
theSeq = (int *)malloc(seqlen * sizeof(int));
// Exit program if array is null
if (theSeq == NULL)
{
printf("Array is null i.e., memory not allocated!");
exit(0);
}
// If array is not null
else
{
// Loop through sequence length, and add random values between 1 to 3
for (int i = 0; i < seqlen; ++i)
theSeq[i] = rand() % 3 + 1;
}
}
/* display the sequence on the terminal window, using the format from the sample run in the spec */
void showSeq(int *seq)
{
printf("Secret : ");
for (int i = 0; i < seqlen; ++i)
{
// Switch case statements to take input numbers and display as R, G, B
switch (theSeq[i])
{
case 1:
printf("R ");
break;
case 2:
printf("G ");
break;
case 3:
printf("B ");
break;
}
}
printf("\n");
}
#define NAN1 8
#define NAN2 9
// Count matches in C
int /* or int* */ countMatches(int *seq1, int *seq2)
{
/* *** COMPLETE the code here *** */
// Loop index variables
int i, j, k, m;
// Temporary array for flagging seen colours
int *check = (int *)malloc(seqlen * sizeof(int));
// Variables for holding correct and approximate guesses
int correct = 0, approx = 0;
// Fill initial check flag array with 0's
for (i = 0; i < seqlen; i++)
check[i] = 0;
// Loop through secret sequence and guess sequence to find out correct positions i.e., correct colours in correct positions
for (j = 0; j < seqlen; j++)
{
// If element in sequence 1 matches element in sequence 2
if (seq2[j] == seq1[j])
{
// Modify flag to 1 i.e., seen
check[j] = 1;
// Increment correct entry
correct++;
}
}
// Loop through secret sequence and guess sequence to find out approximate positions i.e., correct colours in wrong positions
for (k = 0; k < seqlen; k++)
{
// If element in sequence 1 matches element in sequence 2
if (seq2[k] == seq1[k])
{
// Don't do anything, continue further
continue;
}
// If elements don't match
else
{
// Iterate through sequence length
for (m = 0; m < seqlen; m++)
{
// Check whether colour has been flagged and whether elements are equal i.e., correct element wrong position
if (!check[m] && m != k && seq2[k] == seq1[m])
{
// Increment approximate entry
approx++;
// Modify flag to 1 i.e., seen
check[m] = 1;
// Break out of current loop
break;
}
}
}
}
// Free check array
free(check);
// Store concatenated correct and approx values (2 numbers encoded into 1)
int ret = concat(correct, approx);
// Return encoded number
return ret;
}
/* show the results from calling countMatches on seq1 and seq1 */
void showMatches(int code, int *seq1, int *seq2, int lcd_format)
{
// Variable as index value
int index = 0;
// Temporary array to store encoded values
int *temp = (int *)malloc(2 * sizeof(int));
// While loop to split code digits into array
// If passed argument 'code' is not 0, and the current index is less than the length of secret sequence
while (code != 0 && index < seqlen)
{
temp[index] = code % 10;
++index;
code /= 10;
}
// Store digits in respective int values
int approx = temp[0];
int correct = temp[1];
// Print out correct and approximate values to terminal
printf("%d exact\n", correct);
printf("%d approximate\n", approx);
// Free temp array
free(temp);
}
/* parse an integer value as a list of digits, and put them into @seq@ */
/* needed for processing command-line with options -s or -u */
void readSeq(int *seq, int val)
{
int i = 0;
// While loop to add integer digit to array passed as argument
while (val != 0 && i < seqlen)
{
seq[i] = val % 10;
++i;
val /= 10;
}
// Since added elements to array will be in reverse order, we reverse the array with a helper function
reverse(seq, 0, seqlen - 1);
}
/* read a guess sequence fron stdin and store the values in arr */
/* only needed for testing the game logic, without button input */
int *readNum(int max)
{
int index = 0;
// Array to store digits of passed argument