/
snake.c
625 lines (573 loc) · 17.9 KB
/
snake.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
/*-------------------------------------------------------------------------
Include files:
--------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/*Rebecca's add*/
#include <asm/uaccess.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <asm/semaphore.h>
#include <linux/sched.h>
#include <asm/ioctl.h>
#include "snake.h"
/*=========================================================================
Constants and definitions:
==========================================================================*/
#define N (4) /* the size of the board TODO: can it change? */
#define M (3) /* the initial size of the snake */
#define K (5) /* the number of turns a snake can survive without eating */
typedef char Player;
/* PAY ATTENTION! i will use the fact that white is positive one and black is negative
one to describe the segments of the snake. for example, if the white snake is 2 segments
long and the black snake is 3 segments long
white snake is 1 2
black snake is -1 -2 -3 */
#define WHITE ( 1) /* id to the white player */
#define BLACK (-1) /* id to the black player */
#define EMPTY ( 0) /* to describe an empty point */
/* to describe a point with food. having the value this big guarantees that there will be no
overlapping between the snake segments' numbers and the food id */
#define FOOD (N*N)
typedef char bool;
#define FALSE (0)
#define TRUE (1)
typedef int Direction;
#define DOWN (2)
#define LEFT (4)
#define RIGHT (6)
#define UP (8)
/* a point in 2d space */
typedef struct {
int x, y;
} Point;
typedef int Matrix[N][N];
typedef int ErrorCode;
#define ERR_OK ((ErrorCode) 0)
#define ERR_BOARD_FULL ((ErrorCode)-1)
#define ERR_SNAKE_IS_TOO_HUNGRY ((ErrorCode)-2)
typedef int WinnerData;
#define WHITE_IS_WINNER (4)
#define BLACK_IS_WINNER (2)
#define A_TIE (5)
//Anna's add
#define NOT_FINISHED (-1)
typedef int ColorData;
#define SNAKE_IS_WHITE (4)
#define SNAKE_IS_BLACK (2)
// Anna's add: structs and fields
typedef struct {
Matrix board;
Player currentPlayer;
WinnerData winner;
bool isFinished;
bool isReleased;
int openCount;
struct semaphore countLock; // lock when check the openCount variable
struct semaphore openLock; // lock when the first player waits for the second one
struct semaphore readWriteLock; // lock when read or write (can't be both on the same time)
struct semaphore whiteLock; // blocks the white player when it isn't his turn
struct semaphore blackLock; // blocks the black player when it isn't his turn
struct semaphore currentLock; //lock when checking the currentPlayer
struct semaphore isFinishedLock; //lock when checking if the game has finished
struct semaphore isReleasedLock; //lock when checking if one of the players released the game
struct semaphore winnerLock; // lock when check or change the winner
} Game;
typedef struct {
Player color;
Game* myGame;
} PlayerS;
//Rebecca's change:
static int maxGames;
static Game* games = NULL;
static int majorNumber; ///< Stores the device number -- determined automatically
//TODO: do we need it?:
static char message[256] = { 0 }; ///< Memory for the string that is passed from userspace
static short size_of_message; ///< Used to remember the size of the string stored
/* magic number for SCMD IOCTL operations */
// The prototype functions for the character driver -- must come before the struct definition
int open_snake(struct inode *, struct file *);
int release_snake(struct inode *, struct file *);
ssize_t read_snake(struct file *, char *, size_t, loff_t *);
ssize_t write_snake(struct file *, const char *, size_t, loff_t *);
static struct file_operations fops = { .open = open_snake, .read = read_snake,
.write = write_snake, .release = release_snake, .llseek = llseek_snake };
// end of Rebecca's change here
bool Init(Matrix*); /* initialize the board. return false if the board is illegal (should not occur, affected by N, M parameters) */
bool Update(Matrix*, Player, char);/* handle all updating to this player. returns whether to continue or not. */
void Print(Matrix*);/* prints the state of the board */
Point GetInputLoc(Matrix*, Player);/* calculates the location that the player wants to go to */
bool CheckTarget(Matrix*, Player, Point);/* checks if the player can move to the specified location */
Point GetSegment(Matrix*, int);/* gets the location of a segment which is numbered by the value */
bool IsAvailable(Matrix*, Point);/* returns if the point wanted is in bounds and not occupied by any snake */
ErrorCode CheckFoodAndMove(Matrix*, Player, Point);/* handle food and advance the snake accordingly */
ErrorCode RandFoodLocation(Matrix*);/* randomize a location for food. return ERR_BOARD_FULL if the board is full */
void AdvancePlayer(Matrix*, Player, Point);/* advance the snake */
void IncSizePlayer(Matrix*, Player, Point);/* advance the snake and increase it's size */
bool IsMatrixFull(Matrix*);/* check if the matrix is full */
int GetSize(Matrix*, Player);/* gets the size of the snake */
/*-------------------------------------------------------------------------
The main program. The program implements a snake game
-------------------------------------------------------------------------*/
//Anna's add start
int open_snake(struct inode *n, struct file *f) {
if (!n || !f) {
return -EINVAL;
}
int count;
int minor = MINOR(n->i_rdev);
down(&(games[minor].countLock));
if (games[minor].openCount == 2) {
up(&(games[minor].countLock));
return -EINVAL; //TODO:check what error code whould be returned
}
games[minor].openCount++;
count = games[minor].openCount;
up(&(games[minor].countLock));
if (count == 1) {
//why is malloc needed? -Rebecca
PlayerS* specWhite = kmalloc(sizeof(PlayerS), GFP_KERNEL);
specWhite->color = WHITE;
specWhite->myGame = &(games[minor]);
f->private_data = (void*) specWhite;
down(&(games[minor].openLock));
} else { // has to be 2
PlayerS* specBlack = kmalloc(sizeof(PlayerS), GFP_KERNEL);
specBlack->color = BLACK;
specBlack->myGame = &(games[minor]);
f->private_data = (void*) specBlack;
up(&(games[minor].openLock));
}
return 0;
}
ssize_t write_snake(struct file *filp, const char *buff, size_t count,
loff_t *offp) {
// check parameters
if (!filp || !offp || count < 0 || (!buff && count != 0)) {
return -EFAULT;
}
if (count == 0) {
return 0;
}
Game* currentGame = ((PlayerS*) (filp->private_data))->myGame;
// check if game finished normally
down(&(currentGame->isFinishedLock));
if (currentGame->isFinished == TRUE) {
up(&(currentGame->isFinishedLock));
return -10;
}
up(&(currentGame->isFinishedLock));
// check if the other player released the game
down(&(currentGame->isReleasedLock));
if (currentGame->isReleasedLock == TRUE) {
up(&(currentGame->isReleasedLock));
return -10;
}
up(&(currentGame->isReleasedLock));
//start of function
char* myBuff = kmalloc(count, GFP_KERNEL);
int size = count;
if (myBuff == NULL) {
return -EFAULT;
}
int result = copy_from_user(myBuff, buff, count);
if (result == count) {
return -EFAULT;
}
size -= result;
PlayerS* currentP = (PlayerS*) (filp->private_data);
for (int i = 0; i < size; i++) {
down(&(currentGame->currentLock));
if (currentP->color == currentGame->currentPlayer) {
up(&(currentGame->currentLock));
} else {
up(&(currentGame->currentLock));
if (currentP->color == WHITE) {
down(&(currentGame->whiteLock));
down(&(currentGame->whiteLock));
} else {
down(&(currentGame->blackLock));
down(&(currentGame->blackLock));
}
}
down(&(currentGame->isFinishedLock));
if (currentGame->isFinished == TRUE) {
up(&(currentGame->isFinishedLock));
return -10;
}
up(&(currentGame->isFinishedLock));
down(&(currentGame->isReleasedLock));
if (currentGame->isReleased == TRUE) {
up(&(currentGame->isReleasedLock));
return -10;
}
up(&(currentGame->isReleasedLock));
down(&(currentGame->readWriteLock));
bool upResult = Update(&(currentGame->board), currentP, myBuff[i]);
up(&(currentGame->readWriteLock));
down(&(currentGame->currentLock));
if (currentP->color == WHITE) {
currentGame->currentPlayer = BLACK;
} else {
currentGame->currentPlayer = WHITE;
}
up(&(currentGame->currentLock));
if (currentP->color == WHITE) {
up(&(currentGame->blackLock));
} else {
up(&(currentGame->whiteLock));
}
if (upResult == FALSE) {
break;
}
}
kfree(myBuff);
return size;
}
// Anna's add end
bool Init(Matrix *matrix) {
int i;
/* initialize the snakes location */
for (i = 0; i < M; ++i) {
(*matrix)[0][i] = WHITE * (i + 1);
(*matrix)[N - 1][i] = BLACK * (i + 1);
}
/* initialize the food location */
/*Rebecca's change - srand*/
if (RandFoodLocation(matrix) != ERR_OK)
return FALSE;
printf(
"instructions: white player is represented by positive numbers, \nblack player is represented by negative numbers\n");
Print(matrix);
return TRUE;
}
bool Update(Matrix *matrix, PlayerS* player, char move) {
//the matrix we got is the board of the current game
ErrorCode e;
Point p = GetInputLoc(matrix, player->color, atoi(move));
Game* currentGame = player->myGame;
//TODO: check why doesn't recognize PlayerS fields
if (!CheckTarget(matrix, player->color, p)) {
// if the move is illegal, out of bounds, or trying to eat a snake
down(&(currentGame->isFinishedLock));
currentGame->isFinished = TRUE;
up(&(currentGame->isFinishedLock));
//set winner
down(&(currentGame->winnerLock));
if (player->color == WHITE) {
currentGame->winner = BLACK_IS_WINNER;
} else {
currentGame->winner = WHITE_IS_WINNER;
}
up(&(currentGame->winnerLock));
return FALSE;
}
e = CheckFoodAndMove(matrix, player->color, p);
//Rebeca's change
if (e == ERR_SNAKE_IS_TOO_HUNGRY) {
down(&(currentGame->isFinishedLock));
currentGame->isFinished = TRUE;
up(&(currentGame->isFinishedLock));
down(&(currentGame->winnerLock));
if (player->color == WHITE) {
currentGame->winner = BLACK_IS_WINNER;
} else {
currentGame->winner = WHITE_IS_WINNER;
}
up(&(currentGame->winnerLock));
return FALSE;
}
//probabely checks if board is full after the snake has moved
if (e == ERR_BOARD_FULL || IsMatrixFull(matrix)) {
down(&(currentGame->isFinishedLock));
currentGame->isFinished = TRUE;
up(&(currentGame->isFinishedLock));
down(&(currentGame->winnerLock));
currentGame->winner = A_TIE;
up(&(currentGame->winnerLock));
return FALSE;
}
return TRUE;
}
Point GetInputLoc(Matrix *matrix, Player player, Direction dir) {
Point p;
if (dir != UP && dir != DOWN && dir != LEFT && dir != RIGHT) {
p.x = -1;
p.y = -1;
return p;
}
p = GetSegment(matrix, player); //gets the point of the player's head
switch (dir) {
case UP:
--p.y;
break;
case DOWN:
++p.y;
break;
case LEFT:
--p.x;
break;
case RIGHT:
++p.x;
break;
}
return p;
}
Point GetSegment(Matrix *matrix, int segment) {
/* just run through all the matrix */
Point p;
for (p.x = 0; p.x < N; ++p.x) {
for (p.y = 0; p.y < N; ++p.y) {
if ((*matrix)[p.y][p.x] == segment)
return p;
}
}
p.x = p.y = -1;
return p;
}
int GetSize(Matrix *matrix, Player player) {
/* check one by one the size */
Point p, next_p;
int segment = 0;
while (TRUE) {
next_p = GetSegment(matrix, segment += player);
if (next_p.x == -1)
break;
p = next_p;
}
return (*matrix)[p.y][p.x] * player;
}
bool CheckTarget(Matrix *matrix, Player player, Point p) {
/* is empty or is the tail of the snake (so it will move the next
to make place) */
return IsAvailable(matrix, p)
|| ((*matrix)[p.y][p.x] == player * GetSize(matrix, player));
}
bool IsAvailable(Matrix *matrix, Point p) {
return
/* is out of bounds */
!(p.x < 0 || p.x > (N - 1) || p.y < 0 || p.y > (N - 1) ||
/* is empty */
((*matrix)[p.y][p.x] != EMPTY && (*matrix)[p.y][p.x] != FOOD));
}
ErrorCode CheckFoodAndMove(Matrix *matrix, Player player, Point p) {
static int white_counter = K;
static int black_counter = K;
/* if the player did come to the place where there is food */
if ((*matrix)[p.y][p.x] == FOOD) {
if (player == BLACK)
black_counter = K;
if (player == WHITE)
white_counter = K;
IncSizePlayer(matrix, player, p);
if (RandFoodLocation(matrix) != ERR_OK)
return ERR_BOARD_FULL;
} else /* check hunger */
{
if (player == BLACK && --black_counter == 0)
return ERR_SNAKE_IS_TOO_HUNGRY;
if (player == WHITE && --white_counter == 0)
return ERR_SNAKE_IS_TOO_HUNGRY;
AdvancePlayer(matrix, player, p);
}
return ERR_OK;
}
void AdvancePlayer(Matrix *matrix, Player player, Point p) {
/* go from last to first so the identifier is always unique */
Point p_tmp, p_tail = GetSegment(matrix, GetSize(matrix, player) * player);
int segment = GetSize(matrix, player) * player;
while (TRUE) {
p_tmp = GetSegment(matrix, segment);
(*matrix)[p_tmp.y][p_tmp.x] += player;
segment -= player;
if (segment == 0)
break;
}
(*matrix)[p_tail.y][p_tail.x] = EMPTY;
(*matrix)[p.y][p.x] = player;
}
void IncSizePlayer(Matrix *matrix, Player player, Point p) {
/* go from last to first so the identifier is always unique */
Point p_tmp;
int segment = GetSize(matrix, player) * player;
while (TRUE) {
p_tmp = GetSegment(matrix, segment);
(*matrix)[p_tmp.y][p_tmp.x] += player;
segment -= player;
if (segment == 0)
break;
}
(*matrix)[p.y][p.x] = player;
}
ErrorCode RandFoodLocation(Matrix *matrix) {
Point p;
do {
/*Rebecca's change*/
get_random_bytes(&p.x, sizeof(int));
p.x = p.x % N;
get_random_bytes(&p.y, sizeof(int));
p.y = p.y % N;
} while (!(IsAvailable(matrix, p) || IsMatrixFull(matrix))); //fixed by Piazza
if (IsMatrixFull(matrix))
return ERR_BOARD_FULL;
(*matrix)[p.y][p.x] = FOOD;
return ERR_OK;
}
bool IsMatrixFull(Matrix *matrix) {
Point p;
for (p.x = 0; p.x < N; ++p.x) {
for (p.y = 0; p.y < N; ++p.y) {
if ((*matrix)[p.y][p.x] == EMPTY || (*matrix)[p.y][p.x] == FOOD)
return FALSE;
}
}
return TRUE;
}
// Rebecca's add
ssize_t read_snake(struct file *filp, char *buff, size_t count, loff_t *offp) {
if (!filp || !offp || count < 0 || (!buff && count != 0)) {
return -EFAULT;
}
if (count == 0) {
return 0;
}
char *local_buff = kmalloc(count, GFP_KERNEL);
Print(&(((PlayerS*) (flip->private_data))->myGame->board), local_buff,
count, &(((PlayerS*) (flip->private_data))->myGame->readWriteLock));
if (copy_to_user(buff, local_buff, count))
// TODO: type of error
return -EINVAL;
kfree(local_buff);
return count;
}
//Rebecca's change
//TODO: case count not long enough
void Print(Matrix *matrix, char *buff, size_t count, struct semaphore *sem) {
int i;
int current = 0;
Point p;
for (i = 0; i < N + 1; ++i) {
buff[current++] = '-';
buff[current++] = '-';
buff[current++] = '-';
}
buff[current++] = '\n';
//TODO: check semaphore location
down(sem);
for (p.y = 0; p.y < N; ++p.y) {
buff[current++] = '|';
for (p.x = 0; p.x < N; ++p.x) {
switch ((*matrix)[p.y][p.x]) {
case FOOD:
buff[current++] = ' ';
buff[current++] = ' ';
buff[current++] = '*';
break;
case EMPTY:
buff[current++] = ' ';
buff[current++] = ' ';
buff[current++] = '.;
break;
default:
buff[current++] = ' ';
//TODO: check if correct
buff[current++] = (*matrix)[p.y][p.x] + '0';
buff[current++] = ' ';
}
}
buff[current++] = ' ';
buff[current++] = '|';
buff[current++] = '\n';
}
//TODO: check semaphore location
up(sem);
for (i = 0; i < N + 1; ++i) {
buff[current++] = '-';
buff[current++] = '-';
buff[current++] = '-';
}
buff[current++] = '\n';
while (current <= count)
buff[current++] = '\0';
}
//Genia's add:
int init_module(int max_games) {
maxGames = max_games;
games = kmalloc(sizeof(Game) * max_games, GFP_KERNEL);
for(int i=0,i<max_games;i++
) {
games[i].board=kmalloc(sizeof(int) * N*N, GFP_KERNEL);
Init(&(games[i].board));
games[i].currentPlayer=WHITE;
games[i].openCount=0;
games[i].isFinished=false;
games[i].isRealesed=false;
games[i].winner=NOT_FINISHED;
sema_init(&(games[i].countLock), 0);
sema_init(&(games[i].openLock), 0);
sema_init(&(games[i].readWriteLock), 0);
sema_init(&(games[i].whiteLock), 0);
sema_init(&(games[i].blackLock), 0);
sema_init(&(games[i].isFinishedLock), 0);
sema_init(&(games[i].isReleasedLock), 0);
sema_init(&(games[i].winnerLock), 0);
}
major = register_chrdev(0, "snake", &fops);
MODULE_PARM(maxGames, "i");
MODULE_PARM(games, "i");
MODULE_PARM(major, "i");
SET_MODULE_OWNER(&fops);
return 0;
}
// Rrebecca's adds:
int ioctl(struct inode *inode, struct file *filp, unsigned int cmd,
unsigned long arg) {
switch (cmd) {
case SNAKE_GET_WINNER:
Game* currentGame =((PlayerS*) (filp->private_data))->myGame;
down(&(currentGame->isFinishedLock));
if (currentGame->isFinished == TRUE) {
up(&(currentGame->isFinishedLock));
return currentGame->winner;
}
case SNAKE_GET_COLOR;
if (((PlayerS*) (filp->private_data))->color == 1)
return SNAKE_IS_WHITE;
if (((PlayerS*) (filp->private_data))->color == -1)
return SNAKE_IS_BLACK;
//TODO: add error
return ERROR;
}
}
int release_snake(struct inode *n, struct file *f) {
if (!n || !f) {
return -EINVAL;
}
Game* currentGame = ((PlayerS*) (filp->private_data))->myGame;
down(¤tGame->isReleasedLock)
currentGame->isReleased = TRUE;
up(¤tGame->isReleasedLock)
}
//TODO: finish
void cleanup_module() {
for(int i=0,i<max_games;i++
) {
Init(&(games[i].board));
games[i].currentPlayer=WHITE;
games[i].openCount=0;
sema_init(&(games[i].countLock), 0);
sema_init(&(games[i].openLock), 0);
sema_init(&(games[i].readWriteLock), 0);
sema_init(&(games[i].whiteLock), 0);
sema_init(&(games[i].blackLock), 0);
sema_init(&(games[i].isFinishedLock), 0);
sema_init(&(games[i].isReleasedLock), 0);
sema_init(&(games[i].winnerLock), 0);
}
Matrix board;
WinnerData winner;
bool isFinished;
kfree(games);
}