This document contains code for a Tetris game implementation. It includes functions for:
- Drawing the game grid and pieces
- Detecting collisions and removing full rows
- Tracking the score, level, and current/next pieces
- Handling game events like pausing, restarting, and detecting a game over state
The core game logic involves randomly generating and moving falling pieces, removing full rows to increase the score, and checking for collisions to end the game.
Este archivo contiene problemas resueltos del curso de ecuaciones diferenciales, cada problema esta resuelto paso a paso para su mejor comprensión del lector
Solucion de problemas de ecuaciones difrenciales hasta 19JAVIERTELLOCAMPOS
Este archivo contiene problemas resueltos del curso de ecuaciones diferenciales, cada problema esta resuelto paso a paso para su mejor comprensión del lector
Solutions manual for calculus an applied approach brief international metric ...Larson612
Solutions Manual for Calculus An Applied Approach Brief International Metric Edition 10th Edition by Larson IBSN 9781337290579
Full download: https://goo.gl/RtxZKH
Este archivo contiene problemas resueltos del curso de ecuaciones diferenciales, cada problema esta resuelto paso a paso para su mejor comprensión del lector
Solucion de problemas de ecuaciones difrenciales hasta 19JAVIERTELLOCAMPOS
Este archivo contiene problemas resueltos del curso de ecuaciones diferenciales, cada problema esta resuelto paso a paso para su mejor comprensión del lector
Solutions manual for calculus an applied approach brief international metric ...Larson612
Solutions Manual for Calculus An Applied Approach Brief International Metric Edition 10th Edition by Larson IBSN 9781337290579
Full download: https://goo.gl/RtxZKH
In this presentation we solve two more examples of implicit differentiation problems. We use a faster, more direct method.
For more lessons visit: http://www.intuitive-calculus.com/implicit-differentiation.html
ASFWS 2012 - Obfuscator, ou comment durcir un code source ou un binaire contr...Cyber Security Alliance
Le projet Obfuscator, mené conjointement par des équipes de l’HEIG-VD et de l’EIA-FR, vise à explorer des techniques de durcissement de logiciel, sous forme de code source ou d’exécutable, contre le reverse-engineering. Le but de cette présentation est de décrire les résultats obtenus. Cet exposé sera structurée en plusieurs parties:
- Rapide présentation de la problématique de la sécurité du logiciel par rapport au reverse-engineering;
- Description de quelques techniques d’obfuscation implémentées sous forme de “passes” pour le compilateur LLVM (substitution de code, injection de branchements factices, applatissement de code, …), et présentation des résultats obtenus ainsi que des difficultés rencontrées.
- Présentation de quelques techniques d’obfuscation de binaires pour processeurs ARM. Méthodes d’insertions de code dans un fichier binaire au format ELF. Présentation de méthodes d’obfuscation sur processeur ARM avec leurs particularités d’implémentation.
College algebra in context 5th edition harshbarger solutions manualAnnuzzi19
College Algebra in Context 5th Edition Harshbarger Solutions Manual
Full download:https://goo.gl/eJxUd2
People also search:
college algebra in context with applications for the managerial life and social sciences
pearson
chegg
Im trying again -Okay, Im in need of some help - this is the c.pdfeyeonsecuritysystems
I\'m trying again -
Okay, I\'m in need of some help - this is the code I have so far for a C++ project on Tetris that
uses the Visual Studio (which is why the #stdafx.h file is in the header). I need to add to this
code to complete the tasks as listed in the assignment. Here\'s the assignment as I recieved it,
followed by the code:
You have already displayed the Tetris Bucket, started dropping the shapes, stopped them at the
bottom of the Bucket, dropped another shape from the top, got the user input and moved/rotated
the shape in response to the user input.
In this assignment, you need to:
1. Determine whether any of the rows are complete.
2. If a row is complete, remove that line and drop all the shapes above the line by one cell.
3. Compute and display the score.
4. Add plenty of narrative comments. Your program must be compilable and executable.
#include \"stdafx.h\"
#include
#include
#include
#include
using namespace std;
#define GAME_INTERVAL 2
#define GO_DOWN 2
#define GO_LEFT 4
#define GO_RIGHT 6
#define GO_ROTATE 5
class TetrisShape
{
public:
char shapeArray[4][4];
int shapeTopLeftX = 6;
int shapeTopLeftY = 0;
void populateShapeArray(int shape);
void rotate();
template
void setShape(char(&shape)[rows][cols]);
TetrisShape(int shape) { populateShapeArray(shape); };
TetrisShape() {};
};
void TetrisShape::rotate()
{
char _shapeArray[4][4];
_shapeArray[0][0] = shapeArray[0][3]; _shapeArray[1][0] = shapeArray[0][2];
_shapeArray[2][0] = shapeArray[0][1]; _shapeArray[3][0] = shapeArray[0][0];
_shapeArray[0][1] = shapeArray[1][3]; _shapeArray[1][1] = shapeArray[1][2];
_shapeArray[2][1] = shapeArray[1][1]; _shapeArray[3][1] = shapeArray[1][0];
_shapeArray[0][2] = shapeArray[2][3]; _shapeArray[1][2] = shapeArray[2][2];
_shapeArray[2][2] = shapeArray[2][1]; _shapeArray[3][2] = shapeArray[2][0];
_shapeArray[0][3] = shapeArray[3][3]; _shapeArray[1][3] = shapeArray[3][2];
_shapeArray[2][3] = shapeArray[3][1]; _shapeArray[3][3] = shapeArray[3][0];
for (int _s = 0; _s < 4; _s++)
{
for (int _a = 0; _a < 4; _a++)
{
shapeArray[_s][_a] = _shapeArray[_s][_a];
}
}
}
void TetrisShape::populateShapeArray(int shape)
{
switch (shape)
{
case 1:
shapeArray[0][0] = \' \'; shapeArray[1][0] = \' \'; shapeArray[2][0] = \' \';
shapeArray[3][0] = \' \';
shapeArray[0][1] = \' \'; shapeArray[1][1] = \'X\'; shapeArray[2][1] = \' \';
shapeArray[3][1] = \' \';
shapeArray[0][2] = \' \'; shapeArray[1][2] = \'X\'; shapeArray[2][2] = \' \';
shapeArray[3][2] = \' \';
shapeArray[0][3] = \' \'; shapeArray[1][3] = \'X\'; shapeArray[2][3] = \'X\';
shapeArray[3][3] = \' \';
break;
case 2:
shapeArray[0][0] = \' \'; shapeArray[1][0] = \'X\'; shapeArray[2][0] = \' \';
shapeArray[3][0] = \' \';
shapeArray[0][1] = \' \'; shapeArray[1][1] = \'X\'; shapeArray[2][1] = \' \';
shapeArray[3][1] = \' \';
shapeArray[0][2] = \' \'; shapeArray[1][2] = \'X\'; shapeArray[2][2] = \' \';
shapeArray[3][2] = \' \';
shapeArray[0][3] = \' \'; shapeArray[1][3] = \'X\'; shapeArray[2][3] = \' \';
shapeArray[.
In this presentation we solve two more examples of implicit differentiation problems. We use a faster, more direct method.
For more lessons visit: http://www.intuitive-calculus.com/implicit-differentiation.html
ASFWS 2012 - Obfuscator, ou comment durcir un code source ou un binaire contr...Cyber Security Alliance
Le projet Obfuscator, mené conjointement par des équipes de l’HEIG-VD et de l’EIA-FR, vise à explorer des techniques de durcissement de logiciel, sous forme de code source ou d’exécutable, contre le reverse-engineering. Le but de cette présentation est de décrire les résultats obtenus. Cet exposé sera structurée en plusieurs parties:
- Rapide présentation de la problématique de la sécurité du logiciel par rapport au reverse-engineering;
- Description de quelques techniques d’obfuscation implémentées sous forme de “passes” pour le compilateur LLVM (substitution de code, injection de branchements factices, applatissement de code, …), et présentation des résultats obtenus ainsi que des difficultés rencontrées.
- Présentation de quelques techniques d’obfuscation de binaires pour processeurs ARM. Méthodes d’insertions de code dans un fichier binaire au format ELF. Présentation de méthodes d’obfuscation sur processeur ARM avec leurs particularités d’implémentation.
College algebra in context 5th edition harshbarger solutions manualAnnuzzi19
College Algebra in Context 5th Edition Harshbarger Solutions Manual
Full download:https://goo.gl/eJxUd2
People also search:
college algebra in context with applications for the managerial life and social sciences
pearson
chegg
Im trying again -Okay, Im in need of some help - this is the c.pdfeyeonsecuritysystems
I\'m trying again -
Okay, I\'m in need of some help - this is the code I have so far for a C++ project on Tetris that
uses the Visual Studio (which is why the #stdafx.h file is in the header). I need to add to this
code to complete the tasks as listed in the assignment. Here\'s the assignment as I recieved it,
followed by the code:
You have already displayed the Tetris Bucket, started dropping the shapes, stopped them at the
bottom of the Bucket, dropped another shape from the top, got the user input and moved/rotated
the shape in response to the user input.
In this assignment, you need to:
1. Determine whether any of the rows are complete.
2. If a row is complete, remove that line and drop all the shapes above the line by one cell.
3. Compute and display the score.
4. Add plenty of narrative comments. Your program must be compilable and executable.
#include \"stdafx.h\"
#include
#include
#include
#include
using namespace std;
#define GAME_INTERVAL 2
#define GO_DOWN 2
#define GO_LEFT 4
#define GO_RIGHT 6
#define GO_ROTATE 5
class TetrisShape
{
public:
char shapeArray[4][4];
int shapeTopLeftX = 6;
int shapeTopLeftY = 0;
void populateShapeArray(int shape);
void rotate();
template
void setShape(char(&shape)[rows][cols]);
TetrisShape(int shape) { populateShapeArray(shape); };
TetrisShape() {};
};
void TetrisShape::rotate()
{
char _shapeArray[4][4];
_shapeArray[0][0] = shapeArray[0][3]; _shapeArray[1][0] = shapeArray[0][2];
_shapeArray[2][0] = shapeArray[0][1]; _shapeArray[3][0] = shapeArray[0][0];
_shapeArray[0][1] = shapeArray[1][3]; _shapeArray[1][1] = shapeArray[1][2];
_shapeArray[2][1] = shapeArray[1][1]; _shapeArray[3][1] = shapeArray[1][0];
_shapeArray[0][2] = shapeArray[2][3]; _shapeArray[1][2] = shapeArray[2][2];
_shapeArray[2][2] = shapeArray[2][1]; _shapeArray[3][2] = shapeArray[2][0];
_shapeArray[0][3] = shapeArray[3][3]; _shapeArray[1][3] = shapeArray[3][2];
_shapeArray[2][3] = shapeArray[3][1]; _shapeArray[3][3] = shapeArray[3][0];
for (int _s = 0; _s < 4; _s++)
{
for (int _a = 0; _a < 4; _a++)
{
shapeArray[_s][_a] = _shapeArray[_s][_a];
}
}
}
void TetrisShape::populateShapeArray(int shape)
{
switch (shape)
{
case 1:
shapeArray[0][0] = \' \'; shapeArray[1][0] = \' \'; shapeArray[2][0] = \' \';
shapeArray[3][0] = \' \';
shapeArray[0][1] = \' \'; shapeArray[1][1] = \'X\'; shapeArray[2][1] = \' \';
shapeArray[3][1] = \' \';
shapeArray[0][2] = \' \'; shapeArray[1][2] = \'X\'; shapeArray[2][2] = \' \';
shapeArray[3][2] = \' \';
shapeArray[0][3] = \' \'; shapeArray[1][3] = \'X\'; shapeArray[2][3] = \'X\';
shapeArray[3][3] = \' \';
break;
case 2:
shapeArray[0][0] = \' \'; shapeArray[1][0] = \'X\'; shapeArray[2][0] = \' \';
shapeArray[3][0] = \' \';
shapeArray[0][1] = \' \'; shapeArray[1][1] = \'X\'; shapeArray[2][1] = \' \';
shapeArray[3][1] = \' \';
shapeArray[0][2] = \' \'; shapeArray[1][2] = \'X\'; shapeArray[2][2] = \' \';
shapeArray[3][2] = \' \';
shapeArray[0][3] = \' \'; shapeArray[1][3] = \'X\'; shapeArray[2][3] = \' \';
shapeArray[.
Need to make a ReversiOthello Board game in JAVAThe board size ca.pdfflashfashioncasualwe
Need to make a Reversi/Othello Board game in JAVA
The board size can be N x N (so 4x4 is default, and it could be larger like 5x5, 6x6 etc. NEEDS
TO BE ABLE TO WORK WITH ODD SIZE)
Player 1 is going to be you and your going to be the black tiles, and the AI is going to be the
white tiles. Black tiles will start the game, and then white will go after them, then back to black,
repeat. The players must put a disc of their color on an empty square, adjacent to their
opponent\'s disc. Any of the oppponents tiles in between the tile put down, and another of your
tiles will cause them to flip to your color. The winner is decided when the board is completely
filled or no viable moves are left, and whoever has the most pieces.
This program is meant to be simple design (no GUI or big interface designs), broken into
multiple classes (can be extension\'s off the class or abstract interface off each other), and the
user will be entering the coordinates of where to put the pieces (so just using scanner method)?.
The start of the game must always have 4 tiles put down in the center (so the center can change
depending on the size of the board), and the gameplay would look something like this
Again, coding done in JAVA is what I\'m looking for.
Scenario in which the game ends early.
JAVA code BW Success: Black move at C1, 0) BW Score: Black: 4, White: 1 Success: White
move at C2, 0D
Solution
package Reversi_Othello_GameReversiOthello;
import java.awt.*;
import java.applet.*;
public class Reversi_Othello_GameReversiOthello extends Applet implements Runnable {
Thread runner; // declare a thread for this GameReversiOthello
boolean black_shown = false; // flag to signal pause
boolean show_em = false;
final int BLACK = 1; // declare state of each square
final int WHITE = 2;
final int EMPTY = 0;
final int OFFBOARD = -1;
final static int GameReversiOthello[][] = new int[10][10]; //10x10 matrix of squares
protected int Count_Black = 0;
protected int Count_White = 0;
Event evt;
int x, y;
public void start() // create a thread and start it
{
if (runner == null) {
black_shown = false;
runner = new Thread(this);
runner.start();
}
}
public void stop() // stop the thread
{
if (runner != null) {
runner.stop();
runner = null;
black_shown = false;
}
}
public synchronized void run() // initialize screen
{
setBackground(Color.green);
for (int i = 0; i < 10; i++) // initialize off-board squares
{
GameReversiOthello[i][0] = OFFBOARD;
GameReversiOthello[i][9] = OFFBOARD;
GameReversiOthello[0][i] = OFFBOARD;
GameReversiOthello[9][i] = OFFBOARD;
}
for (int i = 1; i < 9; i++) // initialize GameReversiOthello board to be empty
{
for (int j = 1; j < 9; j++) {
GameReversiOthello[i][j] = EMPTY;
}
}
GameReversiOthello[4][4] = WHITE; // except for initial set up
GameReversiOthello[5][4] = BLACK;
GameReversiOthello[4][5] = BLACK;
GameReversiOthello[5][5] = WHITE;
while (runner != null) // signal thread to wait after painting
{ // black and before white responds
while (!black_shown) {
try {
w.
write the TODO part of the program.docxannetnash8266
write the //TODO part of the program:
/***************************************************************************
* scramble.c
*
* Problem Set 3
*
* Implements Scramble with CS50.
*
* Usage: scramble [#]
*
* where # is an optional grid number.
***************************************************************************/
#include [removed]
#include [removed]
#include [removed]
#include [removed]
#include [removed]
#include [removed]
// duration of a game in seconds
#define DURATION 30
// grid's dimensions
#define DIMENSION 4
// maximum number of words in any dictionary
#define WORDS 172806
// maximum number of letters in any word
#define LETTERS 29
// default dictionary
// http://www.becomeawordgameexpert.com/wordlists.htm
#define DICTIONARY "words"
// for logging
FILE* log;
// grid
char grid[DIMENSION][DIMENSION];
// flags with which we can mark grid's letters while searching for words
bool marks[DIMENSION][DIMENSION];
// defines a word as having an array of letters plus a flag
// indicating whether word has been found on grid
typedef struct
{
bool found;
char letters[LETTERS + 1];
}
word;
// defines a dictionary as having a size and an array of words
struct
{
int size;
word words[WORDS];
}
dictionary;
// prototypes
void clear(void);
bool crawl(string letters, int x, int y);
void draw(void);
bool find(string s);
void initialize(void);
bool load(string s);
bool lookup(string s);
void scramble(void);
// This is Scramble.
int main(int argc, string argv[])
{
// ensure proper usage
if (argc > 2)
{
printf("Usage: %s [#]\n", basename(argv[0]));
return 1;
}
// seed pseudorandom number generator
if (argc == 2)
{
int seed = atoi(argv[1]);
if (seed <= 0)
{
printf("Invalid grid.\n");
return 1;
}
srand(seed);
}
else
srand(time(NULL));
// determine path to dictionary
string directory = dirname(argv[0]);
char path[strlen(directory) + 1 + strlen(DICTIONARY) + 1];
sprintf(path, "%s/%s", directory, DICTIONARY);
// load dictionary
if (!load(path))
{
printf("Could not open dictionary.\n");
return 1;
}
// initialize the grid
initialize();
// initialize user's score
int score = 0;
// calculate time of game's end
int end = time(NULL) + DURATION;
// open log
log = fopen("log.txt", "w");
if (log == NULL)
{
printf("Could not open log.\n");
return 1;
}
// accept words until timer expires
while (true)
{
// clear the screen
clear();
// draw the current state of the grid
draw();
// log board
for (int row = 0; row < DIMENSION; row++)
{
for (int col = 0; col [removed]= end)
.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.ArrayList;
public class Checkers extends JPanel {
public static void main(String[] args) {
JFrame window = new JFrame(\"Checkers\");
Checkers content = new Checkers();
window.setContentPane(content);
window.pack();
Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();
window.setLocation( (screensize.width - window.getWidth())/2,
(screensize.height - window.getHeight())/2 );
window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
window.setResizable(false);
window.setVisible(true);
}
private JButton newGameButton; // Button for starting a new game.
private JButton resignButton; // Button that a player can use to end
// the game by resigning.
private JLabel message; // Label for displaying messages to the user.
public Checkers() {
setLayout(null); // I will do the layout myself.
setPreferredSize( new Dimension(350,250) );
setBackground(new Color(0,150,0)); // Dark green background.
/* Create the components and add them to the applet. */
Board board = new Board(); // Note: The constructor for the
// board also creates the buttons
// and label.
add(board);
add(newGameButton);
add(resignButton);
add(message);
/* Set the position and size of each component by calling
its setBounds() method. */
board.setBounds(20,20,164,164); // Note: size MUST be 164-by-164 !
newGameButton.setBounds(210, 60, 120, 30);
resignButton.setBounds(210, 120, 120, 30);
message.setBounds(0, 200, 350, 30);
} // end constructor
private static class CheckersMove {
int fromRow, fromCol; // Position of piece to be moved.
int toRow, toCol; // Square it is to move to.
CheckersMove(int r1, int c1, int r2, int c2) {
// Constructor. Just set the values of the instance variables.
fromRow = r1;
fromCol = c1;
toRow = r2;
toCol = c2;
}
boolean isJump() {
// Test whether this move is a jump. It is assumed that
// the move is legal. In a jump, the piece moves two
// rows. (In a regular move, it only moves one row.)
return (fromRow - toRow == 2 || fromRow - toRow == -2);
}
} // end class CheckersMove.
private class Board extends JPanel implements ActionListener, MouseListener {
CheckersData board; // The data for the checkers board is kept here.
// This board is also responsible for generating
// lists of legal moves.
boolean gameInProgress; // Is a game currently in progress?
/* The next three variables are valid only when the game is in progress. */
int currentPlayer; // Whose turn is it now? The possible values
// are CheckersData.RED and CheckersData.BLACK.
int selectedRow, selectedCol; // If the current player has selected a piece to
// move, these give the row and column
// containing that piece. If no piece is
// yet selected, then selectedRow is -1.
CheckersMove[] legalMoves; // An array containing the legal moves for the
// current player.
Board() {
setBackground(Color.BLACK);
addMouseListener(this);
resignButton = new JButton(\"Resign\");
resignButton.addActionListener(this);
newGameBu.
Create a C program that implements The Game of Life cellular auto.pdfarihantsherwani
Create a C program that implements \"The Game of Life\" cellular automata (CA) simulation. A
few comments: You will want 2 two-dimensional arrays. One that holds the current state of the
\"universe\" and second that is generated from the first using the Game of Life rules, which are
given below. After the computations for filling the second array are complete, the contents of the
second array can be copied back to the first. You can make the array as big as you want, but you
should probably use 20 times 20 as a minimum. As discussed in class, the outside boundary of
the \"universe\" can be a bit tricky. To keep it simple for this exercise, you can assume that the
outside boundary cells are always \"dead\". You can use whatever character (or number) that
you want to represent the \"living\" cells. The dead cells should probably be spaces. The rules
for whether a particular cell lives or dies are determined by the 8 surrounding cells. If a particular
cell is alive, then: If only 0 or 1 of the surrounding cells are alive, the cell dies. (It\'s lonely.) If
4 or more of the surrounding cells are alive, the cell dies. (Too much competition.) If 2 or 3 of
the surrounds cells are alive, the cell stays alive. If a particular cell is dead, then it comes to life
if exactly 3 of the surround cells are alive. You will have to pick some starting configuration for
the universe. An easy thing to do is fill the array randomly, and then let things go and see what
evolves. Write your program as described above and demo the operation to your TA. Then try
some modifications. First, try using a different starting configurations. Look here for some
ideas:. Gosper\'s Glider Gun is a famous one. Or try a simple spaceship or oscillator. Then try
changing the rules determining life and death. A common variation is to include a \"birth\" when
6 neighboring cells are alive in addition to the \"3-cell\" birth. Finally, there will be a short quiz
covering 2D arrays. This exercise should be very familiar.
Solution
#include #include #include #include #include #include #include #define ROWS 60 #define
COLS 60 #define OFF 0 #define ON 1 #define BLACK 8, 0, 0, 0, 0 #define scr_width 600
#define scr_height 600 #define cell_width (scr_width / ROWS) #define cell_height (scr_height /
COLS) We must hold two copies of the board so that we can analyze board and make *
changes to temp when killing/creating cells so that we don\'t cause changes * to the board to
affect the following cells. */ char board[ROWS][COLS]; char temp[ROWS][COLS];
SDL_Rect cells[ROWS][COLS]; /* Stores positions of each cell for blits. */ void
randomize_board(void); void initialize_grid(SDL_Surface* screen); void
blit_board(SDL_Surface* bcell, SDL_Surface* screen); int num_neighbours(int x, int y); void
update_board(void); int clear_board(SDL_Surface* screen, Uint32 color); int
clear_cell(SDL_Surface* screen, int x, int y, Uint32 color); void initialize_cells_array(void); int
main(void) { SDL_Init(SDL_INIT_VIDEO).
In Java using Eclipse, Im suppose to write a class that encapsulat.pdfanjandavid
In Java using Eclipse, I\'m suppose to write a class that encapsulates a tic tac toe board using two
dimensional arrays. It should only involve the human player vs. the computer, and should
randomly select who should use \'X\' or \'O\' and whether the human player or the computer
should go first. Verify that all moves by the human player are to a valid space on the tic-tac-toe
board, and an incorrect choice should not halt or terminate the game. Below is my Java program
that is currently a work in progress. Can you help me remodify it? Thanks.
import java.util.Scanner;
public class LeavinesTicTacToe
{
public static Scanner sc = new Scanner(System.in);
public static void main(String[] args)
{
final int SIZE = 3;
char[][] board = new char[SIZE][SIZE]; // game board
resetBoard(board); // initialize the board (with \' \' for all cells)
// First, welcome message and display the board.
System.out.println(\"===== WELCOME TO THE TIC-TAC-TOE GAME!! =====\ \");
showBoard(board);
// Then ask the user which symbol (x or o) he/she wants to play.
System.out.print(\" Which symbol do you want to play, \\\"x\\\" or \\\"o\\\"? \");
char userSymbol = sc.next().toLowerCase().charAt(0);
char compSymbol = (userSymbol == \'x\') ? \'o\' : \'x\';
// Also ask whether or not the user wants to go first.
System.out.println();
System.out.print(\" Do you want to go first (y/n)? \");
char ans = sc.next().toLowerCase().charAt(0);
int turn; // 0 -- the user, 1 -- the computer
int remainCount = SIZE * SIZE; // empty cell count
// THE VERY FIRST MOVE.
if (ans == \'y\') {
turn = 0;
userPlay(board, userSymbol); // user puts his/her first tic
}
else {
turn = 1;
compPlay(board, compSymbol); // computer puts its first tic
}
// Show the board, and decrement the count of remaining cells.
showBoard(board);
remainCount--;
// Play the game until either one wins.
boolean done = false;
int winner = -1; // 0 -- the user, 1 -- the computer, -1 -- draw
while (!done && remainCount > 0) {
// If there is a winner at this time, set the winner and the done flag to true.
done = isGameWon(board, turn, userSymbol, compSymbol); // Did the turn won?
if (done)
winner = turn; // the one who made the last move won the game
else {
// No winner yet. Find the next turn and play.
turn = (turn + 1 ) % 2;
if (turn == 0)
userPlay(board, userSymbol);
else
compPlay(board, compSymbol);
// Show the board after one tic, and decrement the rem count.
showBoard(board);
remainCount--;
}
}
// Winner is found. Declare the winner.
if (winner == 0)
System.out.println(\"\ ** YOU WON. CONGRATULATIONS!! **\");
else if (winner == 1)
System.out.println(\"\ ** YOU LOST.. Maybe next time :) **\");
else
System.out.println(\"\ ** DRAW... **\");
}
public static void resetBoard(char[][] brd)
{
for (int i = 0; i < brd.length; i++)
for (int j = 0; j < brd[0].length; j++)
brd[i][j] = \' \';
}
public static void showBoard(char[][] brd)
{
int numRow = brd.length;
int numCol = brd[0].length;
System.out.println();
// First write the column he.
In Java using Eclipse, Im suppose to write a class that encapsulat.pdf
tetris
1. #ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include <sstream>
/* As Tetris runs on a standard 10x20 grid (displayed), each pixel has
width represented by a float value of 0.09f */
int score = 0;
int grid[10][22];
int nextPiece = 0;
int currShape[4][4];
int temp[4][4];
int horz = 0;
int vert = 0;
int ticks = 0;
int level = 1;
int gameOver = 0;
int gamePause = -1;
void drawWord(std::string word, int pos_x, int pos_y, float scale,
float red, float green, float blue) {
glColor3f(red, green, blue);
// Set the input color
glMatrixMode(GL_PROJECTION);
// Move into projection mode
glPushMatrix();
// push a matrix onto the stack
glLoadIdentity();
// load the identity matrix
glMatrixMode(GL_MODELVIEW);
// switch into model view
glPushMatrix();
// push a new matrix onto the stack
glLoadIdentity();
gluOrtho2D(0, 512, 0, 512);
// set our window co-ordinates
glTranslatef(pos_x, pos_y, 0.0f);
// translate by the inputted values
glScalef(scale, scale, 1.0f);
// scale based on inputted scale
int length = word.size();
// find the size of the word
for(int i=0; i<length; i++)
glutStrokeCharacter(GLUT_STROKE_ROMAN, word[i]);
//type out each letter in the word
glPopMatrix();
2. glMatrixMode(GL_PROJECTION);
glPopMatrix();
// pop matrices in order to reset the changes and
complete function
}
std::string makeString(int value) {
std::stringstream convert;
convert << value;
return convert.str();
// convert an int into a string
}
void writeScore() {
// for each method, use drawWord to draw what we need
in this postion
drawWord("Score",390,400,0.3f,1.0f,0.0f,0.2f);
drawWord(makeString(score),390,365,0.2f,1.0f,1.0f,1.0f);
}
void writeLevel() {
drawWord("Level",390,256,0.3f,0.0f,0.5f,0.0f);
drawWord(makeString(level),430,225,0.2f,1.0f,1.0f,1.0f);
}
void drawNextPiece() {
float red = 0.0f;
float green = 0.0f;
float blue = 0.0f;
int nextGrid[4][4];
// reset the next piece tracker
for(int x = 0; x < 4; x++) {
for(int y =0; y < 4; y++) {
nextGrid[x][y] = 0;
}
}
switch(nextPiece) {
// based on our chosen next piece, fill in the relevant values in
our 4x4 array and set the colour
case 0: red = 1.0f; nextGrid[1][0] = 1; nextGrid[1][1] =
1; nextGrid[1][2] = 1; nextGrid[1][3] = 1; break;
case 1: blue = 1.0f; nextGrid[1][1] = 1;
nextGrid[1][2] = 1; nextGrid[2][2] = 1; nextGrid[2][1] = 1;
break;
case 2: green = 1.0f; red = 1.0f;
nextGrid[0][2] = 1; nextGrid[1][1] = 1; nextGrid[1][2] = 1;
nextGrid[2][1] = 1; break;
3. case 3: green = 1.0f; nextGrid[0][1] = 1;
nextGrid[1][1] = 1; nextGrid[1][2] = 1; nextGrid[2][2] = 1;
break;
case 4: red = 1.0f; green = 0.5f;
nextGrid[1][0] = 1; nextGrid[1][1] = 1; nextGrid[1][2] = 1;
nextGrid[2][0] = 1; break;
case 5: green = 1.0f; blue = 1.0f;
nextGrid[2][0] = 1; nextGrid[2][1] = 1; nextGrid[2][2] = 1;
nextGrid[1][0] = 1; break;
case 6: red = 0.5f; blue = 0.5f; nextGrid[0][1] =
1; nextGrid[1][1] = 1; nextGrid[2][1] = 1; nextGrid[1][2] = 1;
break;
}
for(int x = 0; x < 4; x++) {
// for each filled part of our 2d array, we draw a solid
cube and wire grid on screen
for(int y = 0; y < 4; y++) {
if(nextGrid[x][y] == 1) {
// As in drawGrid method, with alternate translation values (see
below)
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glTranslatef((-
0.8125f+(x*0.075f)),(0.1375f+(y*0.075f)),0.0f);
glColor3f(red,green,blue);
glutSolidCube(0.075f);
glColor3f(0.0f,0.0f,0.0f);
glutWireCube(0.075f);
glPopMatrix();
glMatrixMode(GL_PROJECTION);
glPopMatrix();
}
}
}
}
void showNext() {
// we draw a box to enclose our nextPiece and draw the word and
piece required also
drawWord("Next",30,400,0.3f,0.0f,0.0f,1.0f);
glLineWidth(0.2f);
glColor3f(1.0f,1.0f,1.0f);
glBegin(GL_LINE_LOOP);
glVertex2f(-0.9f, 0.45f);
glVertex2f(-0.5f, 0.45f);
glVertex2f(-0.5f,0.05f);
glVertex2f(-0.9f,0.05f);
glEnd();
drawNextPiece();
4. }
void startGrid() {
// initialise a blank grid
for(int x = 0; x < 10; x++) {
for(int y = 0; y < 22; y++) {
grid[x][y] = 0;
}
}
}
void drawGrid() {
// draw our tetris board based on our 2d array
float red;
float green;
float blue;
for(int y = 0; y < 20; y++) {
for(int x = 0; x < 10; x++) {
red = 0.0f;
green = 0.0f;
blue = 0.0f;
switch(grid[x][y]) {
// set the colour based on the value of the array at this point
case 0: break;
case 1: red = 0.8f; green = 0.8f; blue =
0.8f; break;
case 2: red = 1.0f; break;
case 3: blue = 1.0f; break;
case 4: red = 1.0f; green = 1.0f; break;
case 5: green = 1.0f; break;
case 6: red = 1.0f; green = 0.5f; break;
case 7: green = 1.0f; blue = 1.0f;
break;
case 8: red = 0.5f; blue = 0.5f; break;
}
if(grid[x][y] != 0) {
// if we find a non-blank space, we must draw
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glTranslatef((-0.405f+(x*0.09f)),(-
0.855f+(y*0.09f)),0.0f); // we translate by our bottom left
values corner for x and y, plus the change in x and y defined by the
array position
glColor3f(red,green,blue);
glutSolidCube(0.09f);
// we draw a solid cube of required colour, with single pixel
size
glColor3f(0.0f,0.0f,0.0f);
5. glutWireCube(0.09f);
// we then draw the black wire frame to show it as a pixel
glPopMatrix();
// we undo the translation by popping the matrix off the stack
glMatrixMode(GL_PROJECTION);
glPopMatrix();
}
}
}
}
void newPiece() {
nextPiece = rand() % 7;
// to randomly choose a piece, we pick a random number
between 0 and 6
}
void drawPiece() {
for(int y = 0; y < 20; y++) {
// this resets all non "dead-block" values in the board,
i.e. erases our live piece
for(int x = 0; x < 10; x++) {
if(grid[x][y] != 1)
grid[x][y] = 0;
}
}
for(int y = 0; y < 4; y++) {
// this then draws the piece into our 2d array, based on
the current shape array and the tracked vertical and horizontal
for(int x = 0; x < 4; x++) {
// values of our bottom left corner
if((horz+x >= 0) && (horz+x < 10) && (vert+y >= 0) && (vert+y <
20)) {
if(grid[horz + x][vert + y] != 1)
grid[horz + x][vert + y] = currShape[x][y];
}
}
}
}
void testGameOver() {
for(int y = 0; y < 4; y++) {
// if our piece is blocked from entering the grid, we state
it as game over
for(int x = 0; x < 4; x++) {
if((currShape[x][y] != 0) & (grid[horz + x][vert + y] == 1)) {
gameOver = 1;
gamePause = 1;
// we put the game into a state of pause to stop idle and user
input
6. }
}
}
}
void drawNewPiece() {
// this will add our next piece into our current piece array
for(int y = 0; y < 4; y++) {
// we first reset our current piece array
for(int x = 0; x < 4; x++) {
currShape[x][y] = 0;
}
}
switch (nextPiece) {
// then set the relevant values of our array
case 0: currShape[0][2] = 2; currShape[1][2] = 2;
currShape[2][2] = 2; currShape[3][2] = 2; break;
case 1: currShape[1][2] = 3; currShape[1][1] = 3;
currShape[2][2] = 3; currShape[2][1] = 3; break;
case 2: currShape[0][2] = 4; currShape[1][1] = 4;
currShape[1][2] = 4; currShape[2][1] = 4; break;
case 3: currShape[0][1] = 5; currShape[1][1] = 5;
currShape[1][2] = 5; currShape[2][2] = 5; break;
case 4: currShape[1][0] = 6; currShape[1][1] = 6;
currShape[1][2] = 6; currShape[2][0] = 6; break;
case 5: currShape[1][0] = 7; currShape[2][0] = 7;
currShape[2][1] = 7; currShape[2][2] = 7; break;
case 6: currShape[0][1] = 8; currShape[1][1] = 8;
currShape[2][1] = 8; currShape[1][2] = 8; break;
}
horz = 3;
// we must also reset the tracked position of our bottom left
corner
vert = 17;
testGameOver();
// we test if the piece can be inserted into our grid
if(gameOver == 0) {
drawPiece();
// if the piece can be drawn in, we add it to the board and
generate our new "next" piece
newPiece();
}
}
void display() {
glClear(GL_COLOR_BUFFER_BIT);
// we clear the display
glColor3f(1.0f, 1.0f, 1.0f); // set RGB values of colour to draw
glLineWidth(3.0f);
glBegin(GL_LINES);
// and draw the outline of the grid in white
7. glVertex2f(0.45f,0.9f);
glVertex2f(0.45f,-0.9f);
glVertex2f(0.45f,-0.9f);
glVertex2f(-0.45f,-0.9f);
glVertex2f(-0.45f,-0.9f);
glVertex2f(-0.45f,0.9f);
glEnd();
writeScore();
writeLevel();
showNext();
drawGrid();
drawWord("Press 'q' to quit, 'p' to pause and 'r' to
restart",120,10,0.1f,0.0f,1.0f,1.0f); // this adds some feature
instructions on the bottom of the screen
if(gameOver == 1) {
// if the game is over, draw this in
drawWord("Game",10,150,0.3f,1.0f,0.5f,0.0f);
drawWord("Over",25,120,0.3f,1.0f,0.5f,0.0f);
}
else if(gamePause == 1)
// if we are paused but not over, draw this in
drawWord("Paused",10,150,0.3f,1.0f,0.5f,0.0f);
else if(((ticks % 4500) <= 20) && (ticks > 20)) {
// if we are set to level up, show this message for 20
ticks
drawWord("Level",380,150,0.3f,0.3f,0.3f,1.0f);
drawWord("Up",400,100,0.3f,0.3f,0.3f,1.0f);
}
glutSwapBuffers();
}
int detect() {
// detect if a piece is colliding
int test = 0;
for(int y = 0; y < 20; y++) {
for(int x = 0; x < 10; x++) {
if((grid[x][y] != 0) & (grid[x][y] != 1)) {
// if we have found our live piece
if(y == 0) {
// if we have hit the floor, collision found
test = 1;
}
else if(grid[x][y-1] == 1) {
// if we are resting on a dead block, collision found
test = 1;
}
}
}
}
return test;
}
8. void removeRow(int y) {
// when a row is removed, this function grabs the rows
above to drop them down
for(int a = y; a < 19; a++) {
for(int x = 0; x < 10; x++) {
grid[x][a] = grid[x][(a+1)];
}
}
}
void testScore() {
// this tests for scoring rows
int change = 0;
// track the row changes
for(int y = 0; y < 20; y++) {
int test = 0;
for(int x = 0; x < 10; x++) {
if(grid[x][y] != 1)
// if we find a non-dead block, then we have no score for
this row
test = 1;
}
if(test == 0) {
// if this row scores, remove it, decrease y (to check row above
after change) and increase row change by 1
removeRow(y);
y--;
change++;
}
}
switch(change) {
// our score change is based on how many rows are removed
this sweep
case 1: score += (40*level); break;
case 2: score += (100*level); break;
case 3: score += (300*level); break;
case 4: score += (1200*level); break;
}
}
void idle() {
glutPostRedisplay();
// our idle function controls the display
if(gamePause == -1) {
// if we have not paused the game
9. ticks++;
// increase our number of ticks
if((ticks % 4500) == 0) {
// every 4500 ticks, increase the level to a maximum of 10
if(level < 10)
level++;
}
if((ticks % (int)(60/level)) == 0) {
// This controls the speed based on level. Every (60/level)
ticks, we move down a row
int count = 0;
int collision = detect();
if(collision == 0) {
// If we will not collide, decrease the y co-ord and draw
the piece into its new position
vert--;
drawPiece();
}
else {
for(int y = 0; y < 20; y++) {
// If we do collide, then turn each live piece into a dead
piece before resetting the collision
for(int x = 0; x < 10; x++) {
if((grid[x][y] != 0) & (grid[x][y] != 1)) {
grid[x][y] = 1;
count++;
if(count == 4)
collision = 0;
}
}
}
}
testScore();
// As a new dead block has been added, test to see if this scores
if(count == 4)
drawNewPiece();
// If we added a dead block, we need to draw in our new piece
}
}
}
void restart() {
// A restart function for the game, resetting all variables and
the board and pieces
level = 1;
score = 0;
gameOver = 0;
10. gamePause = -1;
startGrid();
newPiece();
drawNewPiece();
}
void drop() {
// A method to drop until we collide
int collision = 0;
int count = 0;
while(collision == 0) {
// Until we find a collision, continue to drop and update the
piece
vert--;
drawPiece();
collision = detect();
}
for(int y = 0; y < 20; y++) {
// Once we have the colision, turn our live piece into a
dead block
for(int x = 0; x < 10; x++) {
if((grid[x][y] != 0) & (grid[x][y] != 1)) {
grid[x][y] = 1;
count++;
if(count == 4)
collision = 0;
}
}
}
testScore();
// Again, we test score and draw in our new piece
drawNewPiece();
}
void keyboard(unsigned char key, int x, int y) {
// 4 functions. A quit, restart, piece drop and pause built
into the game
switch(key) {
case 'q': exit(1); break;
case 'r': restart(); break;
case ' ': if((gamePause == -1) && (detect() == 0)) drop();
break;
case 'p': if(gameOver == 0) gamePause*=-1; break;
}
}
int wallLeft() {
// Detect a block on the left
11. int test = 0;
for(int y = 0; y < 20; y++) {
for(int x = 0; x < 10; x++) {
if((grid[x][y] != 0) & (grid[x][y] != 1)) {
if(x == 0) {
// If we are against the left side of the grid, we cannot move
test = 1;
}
else if(grid[x-1][y] == 1) {
// Or if a dead piece lies to the left of us, we cannot
move
test = 1;
}
}
}
}
return test;
}
int wallRight() {
// As above, but with inversion to look to our right
int test = 0;
for(int y = 0; y < 20; y++) {
for(int x = 0; x < 10; x++) {
if((grid[x][y] != 0) & (grid[x][y] != 1)) {
if(x == 9) {
test = 1;
}
else if(grid[x+1][y] == 1) {
test = 1;
}
}
}
}
return test;
}
void moveLeft() {
// If there is no left collision, move the piece left and update
int collision = wallLeft();
if(collision == 0)
horz--;
drawPiece();
}
void moveRight() {
// As above, but with inversion to move right
int collision = wallRight();
if(collision == 0)
horz++;
drawPiece();
12. }
int rTest() {
// This is to test the validity of a rotation
int test = 0;
for(int x = 0; x < 4; x++) {
for(int y = 0; y < 4; y++) {
if(temp[x][y] != 0) {
if((horz + x < 0) || (horz + x > 9) || (vert + y < 0) ||
(vert + y > 19)) // If our rotation takes us out of range,
the rotation fails so must be blocked
test = 1;
else if(grid[horz + x][vert + y] == 1)
// Or if we would overwrite a dead piece, we again
block the rotation
test = 1;
}
}
}
return test;
}
void rotate() {
for(int x = 0; x < 4; x++) {
// Roatate our current shape 90 degrees and into a
temporary 2D array for testing
for(int y = 0; y < 4; y++) {
temp[y][3-x] = currShape[x][y];
}
}
if(rTest() == 0) {
// If our rotation is not blocked, copy over our temporary array
into our current shape
for(int x = 0; x < 4; x++) {
for(int y = 0; y < 4; y++) {
currShape[x][y] = temp[x][y];
}
}
drawPiece();
// In either case, we can update our current piece
}
}
void moveDown() {
// A function to move down on the user input
int collision = detect();
int count = 0;
if(collision == 0) {
// If we have no collision, we can move down and update the piece
13. vert--;
drawPiece();
}
else {
// If we do collide, then as above we make our live block dead,
test for score and generate a new piece
for(int y = 0; y < 20; y++) {
for(int x = 0; x < 10; x++) {
if((grid[x][y] != 0) & (grid[x][y] != 1)) {
grid[x][y] = 1;
count++;
if(count == 4)
collision = 0;
}
}
}
testScore();
if(count == 4)
drawNewPiece();
}
}
void special(int key, int x, int y) {
// Move or rotate the live piece based on the user arrow
input
if(gamePause == -1) {
switch(key) {
case GLUT_KEY_LEFT: moveLeft(); break;
case GLUT_KEY_RIGHT: moveRight(); break;
case GLUT_KEY_UP: rotate(); break;
case GLUT_KEY_DOWN: moveDown(); break;
}
}
}
int main(int argc, char* argv[]) {
// A method to initialise our window and set our display
and idle functions, as well as setting up the start of the board
startGrid();
srand(time(NULL));
// Ensure a truly random sequence by basing it off of the time
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGBA);
glutInitWindowSize(512,512);
glutInitWindowPosition(20,20);
glutCreateWindow("Tetris");
glClearColor(0.0f,0.0f,0.0f,1.0f);
glutDisplayFunc(display);