The document describes the code for a falling block game. It includes functions for initializing the game board, attempting to move or rotate the current block, fixing blocks to the board, and adding new blocks. It stores the board state in two representations - a bitfield for each row, and a display structure including colors. It also defines internal functions for checking for completed rows, adding new blocks, and collision detection between blocks.
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.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.
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).
Here is the code for youimport java.util.Scanner; import java.u.pdfanithareadymade
Here is the code for you:
import java.util.Scanner;
import java.util.Random;
public class TicTacToeGame {
static char[] [] board = new char[3][3];
static Scanner input=new Scanner(System.in);
//Object of Stats class to maintain statistics
static Stats stat = new Stats();
/**
* Prints the TicTacToe board
* @param arr: The board so far
*/
public static void printBoard(char [][] arr){
System.out.println();
for (int i=0; i<3; i++)
{
for (int j=0; j<3; j++)
{
System.out.print(arr[i][j]);
if(j!=2)
//Print the | for readable output
System.out.print(\" \" + \"|\" + \" \");
}
System.out.println();
if(i!=2) {
System.out.print(\"_ _ _ \"); // Print _ for readability
System.out.println();;
}
}
}
/**
* Clear the TicTacToe board before starting a new game
* @param arr: The board so far
*/
public static void clearBoard(char [][] arr){
for (int i=0; i<3; i++)
{
for (int j=0; j<3; j++)
{
arr[i][j]=\' \';
}
}
}
/** Determines if the player with the specified token wins
*
* @param symbol: Specifies whether the player is X or O
* @return true if player has won, false otherwise
*/
public static boolean isWon(char symbol) {
for (int i = 0; i < 3; i++) //horizontal
if (board[i][0] == symbol
&& board[i][1] == symbol
&& board[i][2] == symbol) {
return true;
}
//TODO!!! Also check for vertical and the two diagonals
for (int i = 0; i < 3; i++) //vertical
if (board[0][i] == symbol
&& board[1][i] == symbol
&& board[2][i] == symbol) {
return true;
}
//Leading diagonal
if (board[0][0] == symbol
&& board[1][1] == symbol
&& board[2][2] == symbol) {
return true;
}
//Trailing diagonal
if (board[0][2] == symbol
&& board[1][1] == symbol
&& board[2][0] == symbol) {
return true;
}
return false;
}
/** Determines if the cell is occupied
*
* @param row: Row of the cell to be checked
* @param col: Column of the cell to be checked
* @return true if the cell is occupied, false otherwise
*/
public static boolean isOccupied(int row, int col){
if (board[row][col]!=\' \') return false;
else return true;
}
/** Determines who starts the game
*/
public static int whoStarts(){
//TODO: Randomly chooses between 0 and 1 and returns the choice
return (int)(Math.random() + 0.5 );
}
/** takes care of the human\'s move
* 1. Prompt for a cell, then column
* 2. Puts a symbol (X or O) on the board
* 3. Prints the updated board
* 4. If a human wins: prints, updates stats and returns true
* 5. If not a win yet, returns false */
public static boolean humanTurn(char symbol){
//Prompt for a cell. User must enter
//row and column with a space in between.
System.out.print(\"\ \ Enter your move: (row column): \" );
int row = input.nextInt();
int col = input.nextInt();
//TODO!!! Mark user move in the board, print
//the board and check if user has won!
board[row][col] = symbol;
printBoard(board);
if(isWon(symbol))
return true;
return false;
}
/** takes care of the computer\'s move
* 1. Generates numbers until finds an empty cell
* 2. Puts a symbol (X or O) on the board
* 3. Prints the updated board
* 4. If a comp .
Hi there I am having difficulty in finalizing my Tetris game , below.pdffonecomp
Hi there I am having difficulty in finalizing my Tetris game , below I posted the codes for the
classes and I need the rest six pieces to be done. Can anybody help me here. It is a java code and
must use the code I posted bellow. Thanks,
Completing Tetris
[Description: shapes]
Overview
You will be completing the game Tetris. The features needed are
1. Adding the other 6 pieces
2. Adding the ability to rotate the pieces
Concepts
The purpose of this assignment is to gain experience with the following new concepts:
inheritance/class hierarchy
dynamic dispatch
algorithms
If you were not able to complete homework 1, please come see me to get a working solution.
Implementation Requirements
OTHER PIECES: The first step in the assignment is to add the other six pieces. Lets think a little
about the planning though; we don\'t want the Game class to have to know about all 7 different
piece types (we wouldn\'t want Game to have 7 different instance variables, 1 for each type. How
would it keep track of which one was current?) Instead, Game should know about 1 type (a super
type) and let dynamic dispatch do the work for us.
So to start, we need to redesign (or refactor) the current code. To do this, we want a super class
that contains everything common to all pieces; then sub classes for the individual pieces and
their individual needs. So what is the same about all the pieces?
the state currently handled by LPiece is common to all pieces
all the behaviors currently in LPiece are common to all pieces (except the constructor of course)
What is different about each piece:
How each individual playing piece is constructed
The implementation of how each rotates (the second feature for this assignment)
1) Therefore, start by breaking up the LPiece.java class into a super class and sub class. At this
point, test your program. It should run as it did before.
2) Now its time to add the other game pieces. You will need to figure out how to initialize the
pieces. This will be similar to how the L-shaped piece was done, and, in fact, you may find it
helpful to start each new class by copying the code from a previous shape and modifying it. The
pieces should be initialized in the following orientations:
[Description: shapes]
In the Game class, the piece instance variable must have a new type. What do you think it should
be?
You\'ll need to modify the Game class so that it doesn\'t always instantiate an LPiece piece, but
randomly chooses which shape to instantiate. (I strongly recommend creating 1 new shape at a
time and testing.)
ROTATION: The current tetris piece needs to be able to rotate in quarter turns clockwise each
time the \'r\' key is pressed. As an example see the figure below illustrating how the L-shaped
piece rotates:
[Description: Lrotate]
Here is where dynamic dispatch will come in handy since each shape class must have its own
rotate implementation.
Update the existing classes (super and sub classes) to enable dynamic dispatch to work properly.
Modify.
StackInterface An interface for the ADT stack. Do not modif.pdfARCHANASTOREKOTA
StackInterface
/**
An interface for the ADT stack.
Do not modify this file
*/
package PJ2;
public interface StackInterface
{
/** Gets the current number of data in this stack.
@return the integer number of entries currently in the stack*/
public int size();
/** Adds a new data to the top of this stack.
@param aData an object to be added to the stack */
public void push(T aData);
/** Removes and returns this stack\'s top data.
@return either the object at the top of the stack or,
if the stack is empty before the operation, null */
public T pop();
/** Retrieves this stack\'s top data.
@return either the data at the top of the stack or
null if the stack is empty */
public T peek();
/** Detects whether this stack is empty.
@return true if the stack is empty */
public boolean empty();
/** Removes all data from this stack */
public void clear();
} // end StackInterface
SimpleLinkedStack.java
/**
A class of stacks whose entries are stored in a chain of nodes.
Implement all methods in SimpleLinkedStack class using
the inner Node class.
Main Reference : text book or class notes
Do not change or add data fields
Do not add new methods
You may access Node object fields directly, i.e. data and next
*/
package PJ2;
public class SimpleLinkedStack implements StackInterface
{
// Data fields
private Node topNode; // references the first node in the chain
private int count; // number of data in this stack
public SimpleLinkedStack()
{
// add stataments
} // end default constructor
public void push(T newData)
{
// add stataments
} // end push
public T peek()
{
// add stataments
return null;
} // end peek
public T pop()
{
// add stataments
return null;
} // end pop
public boolean empty()
{
// add stataments
return false;
} // end empty
public int size()
{
// add stataments
return -1;
} // end isEmpty
public void clear()
{
// add stataments
} // end clear
public String toString()
{
// add stataments
// note: data class in stack must implement toString() method
// return a list of data in Stack, separate them with \',\'
return \"\";
}
/****************************************************
private inner node class
Do not modify this class!!
you may access data and next directly
***************************************************/
private class Node
{
private T data; // entry in list
private Node next; // link to next node
private Node (T dataPortion)
{
data = dataPortion;
next = null; // set next to NULL
} // end constructor
private Node (T dataPortion, Node nextNode)
{
data = dataPortion;
next = nextNode; // set next to refer to nextNode
} // end constructor
} // end Node
/****************************************************
Do not modify: Stack test
****************************************************/
public static void main (String args[])
{
System.out.println(\"\ \"+
\"*******************************************************\ \"+
\"Sample Expected output:\ \"+
\"\ \"+
\"OK: stack is empty\ \"+
\"Push 3 data: 10, 30, 50\ \"+
\"Print stack [50,30,10,]\ \"+
\"OK: sta.
AvlTree.h
#ifndef AVL_TREE_H
#define AVL_TREE_H
#include "dsexceptions.h"
#include <iostream> // For NULL
#include <queue> // For level order printout
#include <vector>
#include <algorithm> // For max() function
using namespace std;
// AvlTree class
//
// CONSTRUCTION: with ITEM_NOT_FOUND object used to signal failed finds
//
// ******************PUBLIC OPERATIONS*********************
// Programming Assignment Part I
// bool empty( ) --> Test for empty tree @ root
// int size( ) --> Quantity of elements in tree
// int height( ) --> Height of the tree (null == -1)
// void insert( x ) --> Insert x
// void insert( vector<T> ) --> Insert whole vector of values
// void remove( x ) --> Remove x (unimplemented)
// bool contains( x ) --> Return true if x is present
// Comparable findMin( ) --> Return smallest item
// Comparable findMax( ) --> Return largest item
// boolean isEmpty( ) --> Return true if empty; else false
// void printTree( ) --> Print tree in sorted (in) order
// void printPreOrder( ) --> Print tree in pre order
// void printPostOrder( ) --> Print tree in post order
// void printInOrder( ) --> Print tree in *in* order
// Programming Assignment Part II (microassignment)
// void makeEmpty( ) --> Remove and delete all items
// void ~AvlTree( ) --> Big Five Destructor
// AvlTree(const AvlTree &other) --> BigFive Copy Constructor
// AvlTree(const AvlTree &&other) --> BigFive Move Constructor
// AvlTree &operator= ( AvlTree & other ) --> Big Five Copy *assignment* operator
// AvlTree &operator= ( AvlTree && other ) --> Big Five Move *assignment* operator
// void printLevelOrder( ) --> Print tree in LEVEL order :-)
// ******************ERRORS********************************
// Throws UnderflowException as warranted
template <typename Comparable>
class AvlTree
{
public:
/**
* Basic constructor for an empty tree
*/
AvlTree( ) : root( NULL )
{
//cout << " [d] AvlTree constructor called. " << endl;
}
/**
* Vector of data initializer (needed for move= operator rvalue)
*/
AvlTree( vector<Comparable> vals ) : root( NULL )
{
insert(vals);
}
//*******************************************************************************************
// START AVL TREES PART II - TODO: Implement
// Other functions to look for include: clone, makeEmpty, printLevelOrder
/**
* Destroy contents of the AvlTree object - Big Five Destructor
*/
~AvlTree( )
{
//cout << " [d] AvlTree Destructor called. " << endl;
// Empty out the AVL Tree and destroy all nodes (makeEmpty?)
}
/**
* Copy other to new object - Big Five Copy Constructor
*/
AvlTree( const AvlTree &other ) : root( NULL )
{
cout << " [d] Copy Constructor Called." << endl;
// Copy contents of other to ourselves (maybe clone?)
// Get a deep copy of other's tree
}
/* ...
-- USING UNITY TRYING TO CREATE A CLICK TO PATH- THAT YOU CLICK ON AND.pdfganisyedtrd
// USING UNITY TRYING TO CREATE A CLICK TO PATH, THAT YOU CLICK ON AND
THE AGENT/AVATAR FOLLOWS THE BEST PATH TO GET THERE
// AT THE SAME TIME THERE IS A GUARD CHASING THE AGENT USING
AWARENESS AND PAHTFINDING.
//THIS IS THE MapManager.cs the Agent.cs I could upload it
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
// Custom struct to hold the per-tile information needed for the A* pathing search
public struct grid_cell
{
public bool visited;
public bool isBlocked;
public Vector2Int parent;
public float g, h, f;
}
public class MapManager : MonoBehaviour
{
// fixed map size for simplicity - map file must match
public const int WIDTH = 12;
public const int HEIGHT = 12;
// need to know tile size (color for debugging)
private Vector2 TILE_SIZE;
private Color TILE_COLOR;
// prefab tiles (and debugging labels)
public GameObject[] _tilePrefabs;
public GameObject _labelPrefab;
public GameObject _uiCanvas;
// A* pathfinding array and queue
private grid_cell[,] _map = new grid_cell[WIDTH, HEIGHT];
private List<KeyValuePair<float, Vector2Int>> _openList = new List<KeyValuePair<float,
Vector2Int>>();
// references to tile spriterenderers and tile labels for debugging
private SpriteRenderer[,] _tiles = new SpriteRenderer[WIDTH, HEIGHT];
private Text[,] _labels = new Text[WIDTH, HEIGHT];
// steps is a convenient way to generate the 8 children of a grid square
private Vector2Int[] _steps = new Vector2Int[8];
void Start()
{
TILE_SIZE = _tilePrefabs[0].transform.GetComponent<SpriteRenderer>()
.bounds.extents * 2;
// load map and create tiles
readMapFile();
// for debugging, store the color of an unblocked tile (for changing them back)
TILE_COLOR = _tiles[0,0].color;
// store "step" vectors for the four cardinal directions
_steps[0].x = -1; _steps[0].y = 0;
_steps[1].x = 0; _steps[1].y = -1;
_steps[2].x = 0; _steps[2].y = 1;
_steps[3].x = 1; _steps[3].y = 0;
// and the four diagonal directions
_steps[4].x = 1; _steps[4].y = 1;
_steps[5].x = 1; _steps[5].y = -1;
_steps[6].x = -1; _steps[6].y = 1;
_steps[7].x = -1; _steps[7].y = -1;
}
/*********************************************************************************************
Collision with blocked tiles (walls)
- called by agents
- returns a response vector indicating the amount to "push" the agent out of the walls
- (0,0) indicates no collisions happening
*/
public Vector2 checkBlockedCollision(Vector2 pos, Vector2 extents)
{
// convert the world position that we're checking to the coordinates of a grid cell
Vector2Int posGC = vectorToGC(pos);
// loop over the diagonal steps to check the diagonally-adjacent cells
// check those first, because a diagonal collision implies two cardinal direction collisions
for (int si=4;si<_steps.Length;si++) {
// for each diagonal neighbor
Vector2Int step = _steps[si];
Vector2Int neighbor = posGC + step;
// if it's not on the map or not blocked, then no collision possible
if (!onMap(neighbor)) continue;
if.
/**
* @author Derek Harter
* @cwid 123 45 678
* @class
* @ide Visual Studio Community 2017
* @date
* @assg C++ Stacks videos
*
* @description A Stack ADT with two concrete impelementation
* examples: an array based stack implementaiton (AStack), and
* a linked list based implementation (LStack).
*/
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
//-------------------------------------------------------------------------
/** stack (base class)
* The basic definition of the Stack Abstract Data Type (ADT)
* and stack operations. All declared functions here are
* virtual, they must be implemented by concrete derived
* classes.
*/
template <class T>
class Stack
{
public:
/** clear
* Method to clear out or empty any items on stack,
* put stack back to empty state.
* Postcondition: Stack is empty.
*/
virtual void clear() = 0;
/** isEmpty
* Function to determine whether the stack is empty. Needed
* because it is undefined to pop from empty stack. This
* function will not change the state of the stack (const).
*
* @returns bool true if stack is empty, false otherwise.
*/
virtual bool isEmpty() const = 0;
/** push
* Add a new item onto top of stack.
*
* @param newItem The item of template type T to push on top of
* the current stack.
*/
virtual void push(const T& newItem) = 0;
/** top
* Return the top item from the stack. Note in this ADT, peeking
* at the top item does not remove the top item. Some ADT combine
* top() and pop() as one operation. It is undefined to try and
* peek at the top item of an empty stack. Derived classes should
* throw an exception if this is attempted.
*
* @returns T Returns the top item from stack.
*/
virtual T top() const = 0;
/** pop
* Remove the item from the top of the stack. It is undefined what
* it means to try and pop from an empty stack. Derived classes should
* throw an exception if pop() from empty is attempted.
*/
virtual void pop() = 0;
/** size
* Accessor method to provide the current size of the stack.
*/
virtual int size() const = 0;
/** tostring
* Represent stack as a string
*/
virtual string tostring() const = 0;
// operload operators, mostly to support boolean comparison between
// two stacks for testing
bool operator==(const Stack<T>& rhs) const;
virtual const T& operator[](int index) const = 0;
// overload output stream operator for all stacks using tostring()
template <typename U>
friend ostream& operator<<(ostream& out, const Stack<U>& aStack);
};
/** Stack equivalence
* Compare two given stacks to determine if they are equal or not.
* stacks are equal if they are both of the same size, and each corresponding
* item on each stack is equal at the same position on the stack.
* This function relies on overloaded operator[] to access items on stack
* by index for the comparis.
Given the following ADT definition of a stack to use stack .docxshericehewat
Given the following ADT definition of a stack to use:
/** stack (base class)
* The basic definition of the Stack Abstract Data Type (ADT)
* and stack operations. All declared functions here are
* virtual, they must be implemented by concrete derived
* classes.
*/
template <class T>
class Stack
{
public:
/** clear
* Method to clear out or empty any items on stack,
* put stack back to empty state.
* Postcondition: Stack is empty.
*/
virtual void clear() = 0;
/** isEmpty
* Function to determine whether the stack is empty. Needed
* because it is undefined to pop from empty stack. This
* function will not change the state of the stack (const).
*
* @returns bool true if stack is empty, false otherwise.
*/
virtual bool isEmpty() const = 0;
/** push
* Add a new item onto top of stack.
*
* @param newItem The item of template type T to push on top of
* the current stack.
*/
virtual void push(const T& newItem) = 0;
/** top
* Return the top item from the stack. Note in this ADT, peeking
* at the top item does not remove the top item. Some ADT combine
* top() and pop() as one operation. It is undefined to try and
* peek at the top item of an empty stack. Derived classes should
* throw an exception if this is attempted.
*
* @returns T Returns the top item from stack.
*/
virtual T top() const = 0;
/** pop
* Remove the item from the top of the stack. It is undefined what
* it means to try and pop from an empty stack. Derived classes should
* throw an exception if pop() from empty is attempted.
*/
virtual void pop() = 0;
/** size
* Accessor method to provide the current size of the stack.
*
* @returns int The current size (number of items) on the stack.
*/
virtual int size() const = 0;
};
perform the following tasks by writing code that uses a stack to accomplish the task. You will
need to create a stack of the needed type, then use the methods of the stack abstraction (push,
top, pop, etc.) to solve the given task asked for.
Question 7 (5 points)
Given a stack of integers, calculate the sum of the integer values. Also, the stack should still be
unchanged after you have calculated the sum Hint: take the items off the stack to sum them up
and keep them on a second temporary stack so you can put them all back on after you have
calculated the sum.
ANSWER FOR NUMBER 7:
int sumStackOfIntegers(Stack<int> currentStack) {
Stack<int> tempStack;
int sum = 0;
while(!currentStack.isEmpty()) {
int temp = currentStack.top();
tempStack.push(temp);
currentStack.pop();
sum += temp;
}
while(!tempStack.isEmpty()) {
int temp = tempStack.top();
currentStack.push(temp);
tempStack.pop();
}
return sum;
}
Stack Implementation
Given the following linked list implementation of a Stack ADT (this is the same implementation
you used in Assignment 10), add the asked for additional member methods to the linked list stack
implementation.
/** Node
* A basic node contaning an item and a link to t ...
Using the provided table interface table.h and the sample linked lis.pdfconnellalykshamesb60
Using the provided table interface table.h and the sample linked list code linkedList.c, complete
an implementation of the Table ADT. Make sure that you apply the concepts of design by
contract (DbC) to your implementation.
Once you have fully implemented the table, create a main.c file that implements a testing
framework for your table.
Your table implementation must ensure that values inserted are unique, and internally sorted
within a linked list.
table.h
linkedList.c
Solution
khsdg
#include
#include
typedef enum BOOL { false, true } bool;
// Linked list node definition
typedef struct Node node;
struct Node
{
int number;
node *next;
};
static node *top = NULL;
// used to track where we are for the list traversal methods
static node *traverseNode = NULL;
// \"destroy\" will deallocate all nodes in a linked list object
// and will set \"top\" to NULL.
void destroy()
{
node *curr = top;
node *temp = NULL;
while ( curr != NULL )
{
// flip order to see it blow up...
temp = curr;
curr = curr->next;
free( temp );
}
top = NULL;
}
// \"build\" will create an ordered linked list consisting
// of the first \"size\" even integers.
void build( int size )
{
node *newNode = NULL;
int i = 0;
// make sure we don\'t have a list yet
destroy();
for ( i=size ; i>0 ; i-- )
{
newNode = malloc( sizeof( node ) );
newNode->number = i*2;
newNode->next = top;
top = newNode;
}
}
// starts a list traversal by getting the data at top.
// returns false if top == NULL.
bool firstNode( int *item )
{
bool result = false;
if ( top )
{
*item = top->number;
traverseNode = top->next;
result = true;
}
return result;
}
// gets the data at the current traversal node and increments the traversal.
// returns false if we\'re at the end of the list.
bool nextNode( int *item )
{
bool result = false;
if ( traverseNode )
{
*item = traverseNode->number;
traverseNode = traverseNode->next;
result = true;
}
return result;
}
// \"print\" will output an object\'s entire linked list
// to the standard output device -- one \"number\" per line.
void print()
{
int value;
if ( firstNode( &value ) )
{
do
{
printf( \"%d\ \", value );
} while ( nextNode( &value ) );
}
}
int main( int argc, char *argv[] )
{
build( 10 );
print();
destroy();
build( 5 );
build( 20 );
print();
destroy();
return 0;
}.
1- The design of a singly-linked list below is a picture of the functi (1).pdfafgt2012
1. The design of a singly-linked list
below is a picture of the function that needs to be used
below is the code of the above picture:
#include <string>
#include <iostream>
#include <cmath>
#include <cstdio>
#include <algorithm>
using namespace std;
#define defaultSize 100
void Assert(bool val, string s)
{
if (!val)
{ // Assertion failed -- close the program
cout << "Assertion Failed: " << s << endl;
exit(-1);
}
}
template <typename E>
class Link {
public:
E element; // Value for this node
Link *next; // Pointer to next node in list
// Constructors
Link(const E& elemval, Link<E>* nextval = NULL)
{ element = elemval; next = nextval; }
Link(Link<E>* nextval =NULL) { next = nextval; }
};
template <typename E>
class LList: public Link<E> {
private:
Link<E>* head;// Intialization helper method
Link<E>* tail;// Pointer to last element
Link<E>* curr;// Access to current element
int cnt;// Size of list
void init(){// Intialization helper method
curr = tail = head = new Link<E>;
cnt = 0;
}
void removeall() {// Return link nodes to free store
while(head != NULL) {
curr = head;
head = head->next;
delete curr;
}
}
public:
LList(int size=defaultSize) { init(); }// Constructor
~LList() { removeall(); }// Destructor
void print() const;// Print list contents
void clear() { removeall(); init(); }// Clear list
// Insert "it" at current position
void insert(const E& it) {
curr->next = new Link<E>(it, curr->next);
if (tail == curr) tail = curr->next; // New tail
cnt++;
}
void append(const E& it) { // Append "it" to list
tail = tail->next = new Link<E>(it, NULL);
cnt++;
}
// Remove and return current element
E remove() {
Assert(curr->next != NULL, "No element");
E it = curr->next->element; // Remember value
Link<E>* ltemp = curr->next; // Remember link node
if (tail == curr->next) tail = curr; // Reset tail
curr->next = curr->next->next; // Remove from list
delete ltemp; // Reclaim space
cnt--; // Decrement the count
return it;
}
void moveToStart()// Place curr at list start
{ curr = head; }
void moveToEnd() // Place curr at list end
{ curr = tail; }
void prev(){
if (curr == head) return;
Link<E>* temp = head;
while (temp->next!=curr) temp=temp->next;
curr = temp;
}
void next(){ if (curr != tail) curr = curr->next; }
int length() const { return cnt; }
int currPos() const {
Link<E>* temp = head;
int i;
for (i=0; curr != temp; i++)
temp = temp->next;
return i;
}
void moveToPos(int pos){
Assert ((pos>=0)&&(pos<=cnt), "Position out of range");
curr = head;
for(int i=0; i<pos; i++) curr = curr->next;
}
const E& getValue() const {
Assert(curr->next != NULL, "No value");
return curr->next->element;
}
};
completed this code to fulfill the requirement below:
Write a function to insert an integer into a singly-linked list of elements arranged from largest to
smallest. Requires that elements remain ordered after insertion.
2. The design of array-based stack
below is a picture of the function that needs to be used
below is the code of the above picture:
#include <string.h>
#.
Im looking for coding help I dont really need this to be explained.pdfcontact41
I'm looking for coding help I don't really need this to be explained
I'm currently trying to draw a grid and a cube but I also need that cube to rotate
issue is I've been given so much information at once and there are so many missing pieces
mostly do to it not being explained or I've forgotten how to do it that I'm just at a lost
Here's my current code
Defines.h
#pragma once
#define Width 500
#define Height 500
#define NumPixels (Width * Height)
unsigned colorArray[NumPixels];
void ColorBuffer(unsigned int color)
{
for (unsigned int i = 0; i < NumPixels; i++)
{
colorArray[i] = color;
}
}
void drawPixel(unsigned int x, unsigned int y, unsigned int color)
{
unsigned int index = convertCoords(x, y);
colorArray[index] = color;
}
struct Float4
{
union
{
struct
{
float V[4];
};
struct
{
float x;
float y;
float z;
float w;
};
};
};
struct Matrix4x4
{
union
{
struct
{
float V[16];
};
struct
{
float xx;
float xy;
float xz;
float xw;
float yx;
float yy;
float yz;
float yw;
float zx;
float zy;
float zz;
float zw;
float wx;
float wy;
float wz;
float ww;
};
struct
{
Float4 AxisX;
Float4 AxisY;
Float4 AxisZ;
Float4 AxisW;
};
};
};
struct Vertex {
Float4 Position;
unsigned int color;
};
MyMath.h
#pragma once
#include "Defines.h"
float DotProduct(Float4 v1, Float4 v2)
{
return (v1.x * v2.x) + (v1.y * v2.y) + (v1.z * v2.z) + (v1.w * v2.w);
}
Matrix4x4 MultiplyMatrixByMatrix(const matrix& m1, const matrix& m2)
{
Matrix4x4 mOut;
mOut.xx = DotProduct(m1.Row0, m2.Column0);
mOut.xy = DotProduct(m1.Row0, m2.Column1);
mOut.xz = DotProduct(m1.Row0, m2.Column2);
mOut.xw = DotProduct(m1.Row0, m2.Column3);
mOut.yx = DotProduct(m1.Row1, m2.Column0);
mOut.yy = DotProduct(m1.Row1, m2.Column1);
mOut.yz = DotProduct(m1.Row1, m2.Column2);
mOut.yw = DotProduct(m1.Row1, m2.Column3);
mOut.zx = DotProduct(m1.Row2, m2.Column0);
mOut.zy = DotProduct(m1.Row2, m2.Column1);
mOut.zz = DotProduct(m1.Row2, m2.Column2);
mOut.zw = DotProduct(m1.Row2, m2.Column3);
mOut.wx = DotProduct(m1.Row3, m2.Column0);
mOut.wy = DotProduct(m1.Row3, m2.Column1);
mOut.wz = DotProduct(m1.Row3, m2.Column2);
mOut.ww = DotProduct(m1.Row3, m2.Column3);
return mOut;
}
unsigned int convertCoords(unsigned int x, unsigned int y)
{
return y * Width + x;
}
RasterFunc.h
#pragma once
#include "Shaders.h"
// Draws a line using one of the line equations.
void DrawLine(const Vertex& start, const Vertex& end)
{
// Copy input data and send through shaders
Vertex copy_start = start;
Vertex copy_end = end;
// Use vertex shader to modify incoming copies only.
if (VertexShader)
{
VertexShader(copy_start);
VertexShader(copy_end);
}
// original plotting variables adapted to use new cartesian data
SCREEN_XY screen_start = CartesianToScreen(copy_start);
SCREEN_XY screen_end = CartesianToScreen(copy_end);
// Standard line drawing code follows using integer coordinates...
for (numPixels)
{
A_PIXEL copyColor = currColor; // Just like a Vertex, copy original.
if (PixelShader) PixelShader(copyColor); // Modify copy.
PlotPixel(currX, c.
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).
Here is the code for youimport java.util.Scanner; import java.u.pdfanithareadymade
Here is the code for you:
import java.util.Scanner;
import java.util.Random;
public class TicTacToeGame {
static char[] [] board = new char[3][3];
static Scanner input=new Scanner(System.in);
//Object of Stats class to maintain statistics
static Stats stat = new Stats();
/**
* Prints the TicTacToe board
* @param arr: The board so far
*/
public static void printBoard(char [][] arr){
System.out.println();
for (int i=0; i<3; i++)
{
for (int j=0; j<3; j++)
{
System.out.print(arr[i][j]);
if(j!=2)
//Print the | for readable output
System.out.print(\" \" + \"|\" + \" \");
}
System.out.println();
if(i!=2) {
System.out.print(\"_ _ _ \"); // Print _ for readability
System.out.println();;
}
}
}
/**
* Clear the TicTacToe board before starting a new game
* @param arr: The board so far
*/
public static void clearBoard(char [][] arr){
for (int i=0; i<3; i++)
{
for (int j=0; j<3; j++)
{
arr[i][j]=\' \';
}
}
}
/** Determines if the player with the specified token wins
*
* @param symbol: Specifies whether the player is X or O
* @return true if player has won, false otherwise
*/
public static boolean isWon(char symbol) {
for (int i = 0; i < 3; i++) //horizontal
if (board[i][0] == symbol
&& board[i][1] == symbol
&& board[i][2] == symbol) {
return true;
}
//TODO!!! Also check for vertical and the two diagonals
for (int i = 0; i < 3; i++) //vertical
if (board[0][i] == symbol
&& board[1][i] == symbol
&& board[2][i] == symbol) {
return true;
}
//Leading diagonal
if (board[0][0] == symbol
&& board[1][1] == symbol
&& board[2][2] == symbol) {
return true;
}
//Trailing diagonal
if (board[0][2] == symbol
&& board[1][1] == symbol
&& board[2][0] == symbol) {
return true;
}
return false;
}
/** Determines if the cell is occupied
*
* @param row: Row of the cell to be checked
* @param col: Column of the cell to be checked
* @return true if the cell is occupied, false otherwise
*/
public static boolean isOccupied(int row, int col){
if (board[row][col]!=\' \') return false;
else return true;
}
/** Determines who starts the game
*/
public static int whoStarts(){
//TODO: Randomly chooses between 0 and 1 and returns the choice
return (int)(Math.random() + 0.5 );
}
/** takes care of the human\'s move
* 1. Prompt for a cell, then column
* 2. Puts a symbol (X or O) on the board
* 3. Prints the updated board
* 4. If a human wins: prints, updates stats and returns true
* 5. If not a win yet, returns false */
public static boolean humanTurn(char symbol){
//Prompt for a cell. User must enter
//row and column with a space in between.
System.out.print(\"\ \ Enter your move: (row column): \" );
int row = input.nextInt();
int col = input.nextInt();
//TODO!!! Mark user move in the board, print
//the board and check if user has won!
board[row][col] = symbol;
printBoard(board);
if(isWon(symbol))
return true;
return false;
}
/** takes care of the computer\'s move
* 1. Generates numbers until finds an empty cell
* 2. Puts a symbol (X or O) on the board
* 3. Prints the updated board
* 4. If a comp .
Hi there I am having difficulty in finalizing my Tetris game , below.pdffonecomp
Hi there I am having difficulty in finalizing my Tetris game , below I posted the codes for the
classes and I need the rest six pieces to be done. Can anybody help me here. It is a java code and
must use the code I posted bellow. Thanks,
Completing Tetris
[Description: shapes]
Overview
You will be completing the game Tetris. The features needed are
1. Adding the other 6 pieces
2. Adding the ability to rotate the pieces
Concepts
The purpose of this assignment is to gain experience with the following new concepts:
inheritance/class hierarchy
dynamic dispatch
algorithms
If you were not able to complete homework 1, please come see me to get a working solution.
Implementation Requirements
OTHER PIECES: The first step in the assignment is to add the other six pieces. Lets think a little
about the planning though; we don\'t want the Game class to have to know about all 7 different
piece types (we wouldn\'t want Game to have 7 different instance variables, 1 for each type. How
would it keep track of which one was current?) Instead, Game should know about 1 type (a super
type) and let dynamic dispatch do the work for us.
So to start, we need to redesign (or refactor) the current code. To do this, we want a super class
that contains everything common to all pieces; then sub classes for the individual pieces and
their individual needs. So what is the same about all the pieces?
the state currently handled by LPiece is common to all pieces
all the behaviors currently in LPiece are common to all pieces (except the constructor of course)
What is different about each piece:
How each individual playing piece is constructed
The implementation of how each rotates (the second feature for this assignment)
1) Therefore, start by breaking up the LPiece.java class into a super class and sub class. At this
point, test your program. It should run as it did before.
2) Now its time to add the other game pieces. You will need to figure out how to initialize the
pieces. This will be similar to how the L-shaped piece was done, and, in fact, you may find it
helpful to start each new class by copying the code from a previous shape and modifying it. The
pieces should be initialized in the following orientations:
[Description: shapes]
In the Game class, the piece instance variable must have a new type. What do you think it should
be?
You\'ll need to modify the Game class so that it doesn\'t always instantiate an LPiece piece, but
randomly chooses which shape to instantiate. (I strongly recommend creating 1 new shape at a
time and testing.)
ROTATION: The current tetris piece needs to be able to rotate in quarter turns clockwise each
time the \'r\' key is pressed. As an example see the figure below illustrating how the L-shaped
piece rotates:
[Description: Lrotate]
Here is where dynamic dispatch will come in handy since each shape class must have its own
rotate implementation.
Update the existing classes (super and sub classes) to enable dynamic dispatch to work properly.
Modify.
StackInterface An interface for the ADT stack. Do not modif.pdfARCHANASTOREKOTA
StackInterface
/**
An interface for the ADT stack.
Do not modify this file
*/
package PJ2;
public interface StackInterface
{
/** Gets the current number of data in this stack.
@return the integer number of entries currently in the stack*/
public int size();
/** Adds a new data to the top of this stack.
@param aData an object to be added to the stack */
public void push(T aData);
/** Removes and returns this stack\'s top data.
@return either the object at the top of the stack or,
if the stack is empty before the operation, null */
public T pop();
/** Retrieves this stack\'s top data.
@return either the data at the top of the stack or
null if the stack is empty */
public T peek();
/** Detects whether this stack is empty.
@return true if the stack is empty */
public boolean empty();
/** Removes all data from this stack */
public void clear();
} // end StackInterface
SimpleLinkedStack.java
/**
A class of stacks whose entries are stored in a chain of nodes.
Implement all methods in SimpleLinkedStack class using
the inner Node class.
Main Reference : text book or class notes
Do not change or add data fields
Do not add new methods
You may access Node object fields directly, i.e. data and next
*/
package PJ2;
public class SimpleLinkedStack implements StackInterface
{
// Data fields
private Node topNode; // references the first node in the chain
private int count; // number of data in this stack
public SimpleLinkedStack()
{
// add stataments
} // end default constructor
public void push(T newData)
{
// add stataments
} // end push
public T peek()
{
// add stataments
return null;
} // end peek
public T pop()
{
// add stataments
return null;
} // end pop
public boolean empty()
{
// add stataments
return false;
} // end empty
public int size()
{
// add stataments
return -1;
} // end isEmpty
public void clear()
{
// add stataments
} // end clear
public String toString()
{
// add stataments
// note: data class in stack must implement toString() method
// return a list of data in Stack, separate them with \',\'
return \"\";
}
/****************************************************
private inner node class
Do not modify this class!!
you may access data and next directly
***************************************************/
private class Node
{
private T data; // entry in list
private Node next; // link to next node
private Node (T dataPortion)
{
data = dataPortion;
next = null; // set next to NULL
} // end constructor
private Node (T dataPortion, Node nextNode)
{
data = dataPortion;
next = nextNode; // set next to refer to nextNode
} // end constructor
} // end Node
/****************************************************
Do not modify: Stack test
****************************************************/
public static void main (String args[])
{
System.out.println(\"\ \"+
\"*******************************************************\ \"+
\"Sample Expected output:\ \"+
\"\ \"+
\"OK: stack is empty\ \"+
\"Push 3 data: 10, 30, 50\ \"+
\"Print stack [50,30,10,]\ \"+
\"OK: sta.
AvlTree.h
#ifndef AVL_TREE_H
#define AVL_TREE_H
#include "dsexceptions.h"
#include <iostream> // For NULL
#include <queue> // For level order printout
#include <vector>
#include <algorithm> // For max() function
using namespace std;
// AvlTree class
//
// CONSTRUCTION: with ITEM_NOT_FOUND object used to signal failed finds
//
// ******************PUBLIC OPERATIONS*********************
// Programming Assignment Part I
// bool empty( ) --> Test for empty tree @ root
// int size( ) --> Quantity of elements in tree
// int height( ) --> Height of the tree (null == -1)
// void insert( x ) --> Insert x
// void insert( vector<T> ) --> Insert whole vector of values
// void remove( x ) --> Remove x (unimplemented)
// bool contains( x ) --> Return true if x is present
// Comparable findMin( ) --> Return smallest item
// Comparable findMax( ) --> Return largest item
// boolean isEmpty( ) --> Return true if empty; else false
// void printTree( ) --> Print tree in sorted (in) order
// void printPreOrder( ) --> Print tree in pre order
// void printPostOrder( ) --> Print tree in post order
// void printInOrder( ) --> Print tree in *in* order
// Programming Assignment Part II (microassignment)
// void makeEmpty( ) --> Remove and delete all items
// void ~AvlTree( ) --> Big Five Destructor
// AvlTree(const AvlTree &other) --> BigFive Copy Constructor
// AvlTree(const AvlTree &&other) --> BigFive Move Constructor
// AvlTree &operator= ( AvlTree & other ) --> Big Five Copy *assignment* operator
// AvlTree &operator= ( AvlTree && other ) --> Big Five Move *assignment* operator
// void printLevelOrder( ) --> Print tree in LEVEL order :-)
// ******************ERRORS********************************
// Throws UnderflowException as warranted
template <typename Comparable>
class AvlTree
{
public:
/**
* Basic constructor for an empty tree
*/
AvlTree( ) : root( NULL )
{
//cout << " [d] AvlTree constructor called. " << endl;
}
/**
* Vector of data initializer (needed for move= operator rvalue)
*/
AvlTree( vector<Comparable> vals ) : root( NULL )
{
insert(vals);
}
//*******************************************************************************************
// START AVL TREES PART II - TODO: Implement
// Other functions to look for include: clone, makeEmpty, printLevelOrder
/**
* Destroy contents of the AvlTree object - Big Five Destructor
*/
~AvlTree( )
{
//cout << " [d] AvlTree Destructor called. " << endl;
// Empty out the AVL Tree and destroy all nodes (makeEmpty?)
}
/**
* Copy other to new object - Big Five Copy Constructor
*/
AvlTree( const AvlTree &other ) : root( NULL )
{
cout << " [d] Copy Constructor Called." << endl;
// Copy contents of other to ourselves (maybe clone?)
// Get a deep copy of other's tree
}
/* ...
-- USING UNITY TRYING TO CREATE A CLICK TO PATH- THAT YOU CLICK ON AND.pdfganisyedtrd
// USING UNITY TRYING TO CREATE A CLICK TO PATH, THAT YOU CLICK ON AND
THE AGENT/AVATAR FOLLOWS THE BEST PATH TO GET THERE
// AT THE SAME TIME THERE IS A GUARD CHASING THE AGENT USING
AWARENESS AND PAHTFINDING.
//THIS IS THE MapManager.cs the Agent.cs I could upload it
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;
// Custom struct to hold the per-tile information needed for the A* pathing search
public struct grid_cell
{
public bool visited;
public bool isBlocked;
public Vector2Int parent;
public float g, h, f;
}
public class MapManager : MonoBehaviour
{
// fixed map size for simplicity - map file must match
public const int WIDTH = 12;
public const int HEIGHT = 12;
// need to know tile size (color for debugging)
private Vector2 TILE_SIZE;
private Color TILE_COLOR;
// prefab tiles (and debugging labels)
public GameObject[] _tilePrefabs;
public GameObject _labelPrefab;
public GameObject _uiCanvas;
// A* pathfinding array and queue
private grid_cell[,] _map = new grid_cell[WIDTH, HEIGHT];
private List<KeyValuePair<float, Vector2Int>> _openList = new List<KeyValuePair<float,
Vector2Int>>();
// references to tile spriterenderers and tile labels for debugging
private SpriteRenderer[,] _tiles = new SpriteRenderer[WIDTH, HEIGHT];
private Text[,] _labels = new Text[WIDTH, HEIGHT];
// steps is a convenient way to generate the 8 children of a grid square
private Vector2Int[] _steps = new Vector2Int[8];
void Start()
{
TILE_SIZE = _tilePrefabs[0].transform.GetComponent<SpriteRenderer>()
.bounds.extents * 2;
// load map and create tiles
readMapFile();
// for debugging, store the color of an unblocked tile (for changing them back)
TILE_COLOR = _tiles[0,0].color;
// store "step" vectors for the four cardinal directions
_steps[0].x = -1; _steps[0].y = 0;
_steps[1].x = 0; _steps[1].y = -1;
_steps[2].x = 0; _steps[2].y = 1;
_steps[3].x = 1; _steps[3].y = 0;
// and the four diagonal directions
_steps[4].x = 1; _steps[4].y = 1;
_steps[5].x = 1; _steps[5].y = -1;
_steps[6].x = -1; _steps[6].y = 1;
_steps[7].x = -1; _steps[7].y = -1;
}
/*********************************************************************************************
Collision with blocked tiles (walls)
- called by agents
- returns a response vector indicating the amount to "push" the agent out of the walls
- (0,0) indicates no collisions happening
*/
public Vector2 checkBlockedCollision(Vector2 pos, Vector2 extents)
{
// convert the world position that we're checking to the coordinates of a grid cell
Vector2Int posGC = vectorToGC(pos);
// loop over the diagonal steps to check the diagonally-adjacent cells
// check those first, because a diagonal collision implies two cardinal direction collisions
for (int si=4;si<_steps.Length;si++) {
// for each diagonal neighbor
Vector2Int step = _steps[si];
Vector2Int neighbor = posGC + step;
// if it's not on the map or not blocked, then no collision possible
if (!onMap(neighbor)) continue;
if.
/**
* @author Derek Harter
* @cwid 123 45 678
* @class
* @ide Visual Studio Community 2017
* @date
* @assg C++ Stacks videos
*
* @description A Stack ADT with two concrete impelementation
* examples: an array based stack implementaiton (AStack), and
* a linked list based implementation (LStack).
*/
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
//-------------------------------------------------------------------------
/** stack (base class)
* The basic definition of the Stack Abstract Data Type (ADT)
* and stack operations. All declared functions here are
* virtual, they must be implemented by concrete derived
* classes.
*/
template <class T>
class Stack
{
public:
/** clear
* Method to clear out or empty any items on stack,
* put stack back to empty state.
* Postcondition: Stack is empty.
*/
virtual void clear() = 0;
/** isEmpty
* Function to determine whether the stack is empty. Needed
* because it is undefined to pop from empty stack. This
* function will not change the state of the stack (const).
*
* @returns bool true if stack is empty, false otherwise.
*/
virtual bool isEmpty() const = 0;
/** push
* Add a new item onto top of stack.
*
* @param newItem The item of template type T to push on top of
* the current stack.
*/
virtual void push(const T& newItem) = 0;
/** top
* Return the top item from the stack. Note in this ADT, peeking
* at the top item does not remove the top item. Some ADT combine
* top() and pop() as one operation. It is undefined to try and
* peek at the top item of an empty stack. Derived classes should
* throw an exception if this is attempted.
*
* @returns T Returns the top item from stack.
*/
virtual T top() const = 0;
/** pop
* Remove the item from the top of the stack. It is undefined what
* it means to try and pop from an empty stack. Derived classes should
* throw an exception if pop() from empty is attempted.
*/
virtual void pop() = 0;
/** size
* Accessor method to provide the current size of the stack.
*/
virtual int size() const = 0;
/** tostring
* Represent stack as a string
*/
virtual string tostring() const = 0;
// operload operators, mostly to support boolean comparison between
// two stacks for testing
bool operator==(const Stack<T>& rhs) const;
virtual const T& operator[](int index) const = 0;
// overload output stream operator for all stacks using tostring()
template <typename U>
friend ostream& operator<<(ostream& out, const Stack<U>& aStack);
};
/** Stack equivalence
* Compare two given stacks to determine if they are equal or not.
* stacks are equal if they are both of the same size, and each corresponding
* item on each stack is equal at the same position on the stack.
* This function relies on overloaded operator[] to access items on stack
* by index for the comparis.
Given the following ADT definition of a stack to use stack .docxshericehewat
Given the following ADT definition of a stack to use:
/** stack (base class)
* The basic definition of the Stack Abstract Data Type (ADT)
* and stack operations. All declared functions here are
* virtual, they must be implemented by concrete derived
* classes.
*/
template <class T>
class Stack
{
public:
/** clear
* Method to clear out or empty any items on stack,
* put stack back to empty state.
* Postcondition: Stack is empty.
*/
virtual void clear() = 0;
/** isEmpty
* Function to determine whether the stack is empty. Needed
* because it is undefined to pop from empty stack. This
* function will not change the state of the stack (const).
*
* @returns bool true if stack is empty, false otherwise.
*/
virtual bool isEmpty() const = 0;
/** push
* Add a new item onto top of stack.
*
* @param newItem The item of template type T to push on top of
* the current stack.
*/
virtual void push(const T& newItem) = 0;
/** top
* Return the top item from the stack. Note in this ADT, peeking
* at the top item does not remove the top item. Some ADT combine
* top() and pop() as one operation. It is undefined to try and
* peek at the top item of an empty stack. Derived classes should
* throw an exception if this is attempted.
*
* @returns T Returns the top item from stack.
*/
virtual T top() const = 0;
/** pop
* Remove the item from the top of the stack. It is undefined what
* it means to try and pop from an empty stack. Derived classes should
* throw an exception if pop() from empty is attempted.
*/
virtual void pop() = 0;
/** size
* Accessor method to provide the current size of the stack.
*
* @returns int The current size (number of items) on the stack.
*/
virtual int size() const = 0;
};
perform the following tasks by writing code that uses a stack to accomplish the task. You will
need to create a stack of the needed type, then use the methods of the stack abstraction (push,
top, pop, etc.) to solve the given task asked for.
Question 7 (5 points)
Given a stack of integers, calculate the sum of the integer values. Also, the stack should still be
unchanged after you have calculated the sum Hint: take the items off the stack to sum them up
and keep them on a second temporary stack so you can put them all back on after you have
calculated the sum.
ANSWER FOR NUMBER 7:
int sumStackOfIntegers(Stack<int> currentStack) {
Stack<int> tempStack;
int sum = 0;
while(!currentStack.isEmpty()) {
int temp = currentStack.top();
tempStack.push(temp);
currentStack.pop();
sum += temp;
}
while(!tempStack.isEmpty()) {
int temp = tempStack.top();
currentStack.push(temp);
tempStack.pop();
}
return sum;
}
Stack Implementation
Given the following linked list implementation of a Stack ADT (this is the same implementation
you used in Assignment 10), add the asked for additional member methods to the linked list stack
implementation.
/** Node
* A basic node contaning an item and a link to t ...
Using the provided table interface table.h and the sample linked lis.pdfconnellalykshamesb60
Using the provided table interface table.h and the sample linked list code linkedList.c, complete
an implementation of the Table ADT. Make sure that you apply the concepts of design by
contract (DbC) to your implementation.
Once you have fully implemented the table, create a main.c file that implements a testing
framework for your table.
Your table implementation must ensure that values inserted are unique, and internally sorted
within a linked list.
table.h
linkedList.c
Solution
khsdg
#include
#include
typedef enum BOOL { false, true } bool;
// Linked list node definition
typedef struct Node node;
struct Node
{
int number;
node *next;
};
static node *top = NULL;
// used to track where we are for the list traversal methods
static node *traverseNode = NULL;
// \"destroy\" will deallocate all nodes in a linked list object
// and will set \"top\" to NULL.
void destroy()
{
node *curr = top;
node *temp = NULL;
while ( curr != NULL )
{
// flip order to see it blow up...
temp = curr;
curr = curr->next;
free( temp );
}
top = NULL;
}
// \"build\" will create an ordered linked list consisting
// of the first \"size\" even integers.
void build( int size )
{
node *newNode = NULL;
int i = 0;
// make sure we don\'t have a list yet
destroy();
for ( i=size ; i>0 ; i-- )
{
newNode = malloc( sizeof( node ) );
newNode->number = i*2;
newNode->next = top;
top = newNode;
}
}
// starts a list traversal by getting the data at top.
// returns false if top == NULL.
bool firstNode( int *item )
{
bool result = false;
if ( top )
{
*item = top->number;
traverseNode = top->next;
result = true;
}
return result;
}
// gets the data at the current traversal node and increments the traversal.
// returns false if we\'re at the end of the list.
bool nextNode( int *item )
{
bool result = false;
if ( traverseNode )
{
*item = traverseNode->number;
traverseNode = traverseNode->next;
result = true;
}
return result;
}
// \"print\" will output an object\'s entire linked list
// to the standard output device -- one \"number\" per line.
void print()
{
int value;
if ( firstNode( &value ) )
{
do
{
printf( \"%d\ \", value );
} while ( nextNode( &value ) );
}
}
int main( int argc, char *argv[] )
{
build( 10 );
print();
destroy();
build( 5 );
build( 20 );
print();
destroy();
return 0;
}.
1- The design of a singly-linked list below is a picture of the functi (1).pdfafgt2012
1. The design of a singly-linked list
below is a picture of the function that needs to be used
below is the code of the above picture:
#include <string>
#include <iostream>
#include <cmath>
#include <cstdio>
#include <algorithm>
using namespace std;
#define defaultSize 100
void Assert(bool val, string s)
{
if (!val)
{ // Assertion failed -- close the program
cout << "Assertion Failed: " << s << endl;
exit(-1);
}
}
template <typename E>
class Link {
public:
E element; // Value for this node
Link *next; // Pointer to next node in list
// Constructors
Link(const E& elemval, Link<E>* nextval = NULL)
{ element = elemval; next = nextval; }
Link(Link<E>* nextval =NULL) { next = nextval; }
};
template <typename E>
class LList: public Link<E> {
private:
Link<E>* head;// Intialization helper method
Link<E>* tail;// Pointer to last element
Link<E>* curr;// Access to current element
int cnt;// Size of list
void init(){// Intialization helper method
curr = tail = head = new Link<E>;
cnt = 0;
}
void removeall() {// Return link nodes to free store
while(head != NULL) {
curr = head;
head = head->next;
delete curr;
}
}
public:
LList(int size=defaultSize) { init(); }// Constructor
~LList() { removeall(); }// Destructor
void print() const;// Print list contents
void clear() { removeall(); init(); }// Clear list
// Insert "it" at current position
void insert(const E& it) {
curr->next = new Link<E>(it, curr->next);
if (tail == curr) tail = curr->next; // New tail
cnt++;
}
void append(const E& it) { // Append "it" to list
tail = tail->next = new Link<E>(it, NULL);
cnt++;
}
// Remove and return current element
E remove() {
Assert(curr->next != NULL, "No element");
E it = curr->next->element; // Remember value
Link<E>* ltemp = curr->next; // Remember link node
if (tail == curr->next) tail = curr; // Reset tail
curr->next = curr->next->next; // Remove from list
delete ltemp; // Reclaim space
cnt--; // Decrement the count
return it;
}
void moveToStart()// Place curr at list start
{ curr = head; }
void moveToEnd() // Place curr at list end
{ curr = tail; }
void prev(){
if (curr == head) return;
Link<E>* temp = head;
while (temp->next!=curr) temp=temp->next;
curr = temp;
}
void next(){ if (curr != tail) curr = curr->next; }
int length() const { return cnt; }
int currPos() const {
Link<E>* temp = head;
int i;
for (i=0; curr != temp; i++)
temp = temp->next;
return i;
}
void moveToPos(int pos){
Assert ((pos>=0)&&(pos<=cnt), "Position out of range");
curr = head;
for(int i=0; i<pos; i++) curr = curr->next;
}
const E& getValue() const {
Assert(curr->next != NULL, "No value");
return curr->next->element;
}
};
completed this code to fulfill the requirement below:
Write a function to insert an integer into a singly-linked list of elements arranged from largest to
smallest. Requires that elements remain ordered after insertion.
2. The design of array-based stack
below is a picture of the function that needs to be used
below is the code of the above picture:
#include <string.h>
#.
Im looking for coding help I dont really need this to be explained.pdfcontact41
I'm looking for coding help I don't really need this to be explained
I'm currently trying to draw a grid and a cube but I also need that cube to rotate
issue is I've been given so much information at once and there are so many missing pieces
mostly do to it not being explained or I've forgotten how to do it that I'm just at a lost
Here's my current code
Defines.h
#pragma once
#define Width 500
#define Height 500
#define NumPixels (Width * Height)
unsigned colorArray[NumPixels];
void ColorBuffer(unsigned int color)
{
for (unsigned int i = 0; i < NumPixels; i++)
{
colorArray[i] = color;
}
}
void drawPixel(unsigned int x, unsigned int y, unsigned int color)
{
unsigned int index = convertCoords(x, y);
colorArray[index] = color;
}
struct Float4
{
union
{
struct
{
float V[4];
};
struct
{
float x;
float y;
float z;
float w;
};
};
};
struct Matrix4x4
{
union
{
struct
{
float V[16];
};
struct
{
float xx;
float xy;
float xz;
float xw;
float yx;
float yy;
float yz;
float yw;
float zx;
float zy;
float zz;
float zw;
float wx;
float wy;
float wz;
float ww;
};
struct
{
Float4 AxisX;
Float4 AxisY;
Float4 AxisZ;
Float4 AxisW;
};
};
};
struct Vertex {
Float4 Position;
unsigned int color;
};
MyMath.h
#pragma once
#include "Defines.h"
float DotProduct(Float4 v1, Float4 v2)
{
return (v1.x * v2.x) + (v1.y * v2.y) + (v1.z * v2.z) + (v1.w * v2.w);
}
Matrix4x4 MultiplyMatrixByMatrix(const matrix& m1, const matrix& m2)
{
Matrix4x4 mOut;
mOut.xx = DotProduct(m1.Row0, m2.Column0);
mOut.xy = DotProduct(m1.Row0, m2.Column1);
mOut.xz = DotProduct(m1.Row0, m2.Column2);
mOut.xw = DotProduct(m1.Row0, m2.Column3);
mOut.yx = DotProduct(m1.Row1, m2.Column0);
mOut.yy = DotProduct(m1.Row1, m2.Column1);
mOut.yz = DotProduct(m1.Row1, m2.Column2);
mOut.yw = DotProduct(m1.Row1, m2.Column3);
mOut.zx = DotProduct(m1.Row2, m2.Column0);
mOut.zy = DotProduct(m1.Row2, m2.Column1);
mOut.zz = DotProduct(m1.Row2, m2.Column2);
mOut.zw = DotProduct(m1.Row2, m2.Column3);
mOut.wx = DotProduct(m1.Row3, m2.Column0);
mOut.wy = DotProduct(m1.Row3, m2.Column1);
mOut.wz = DotProduct(m1.Row3, m2.Column2);
mOut.ww = DotProduct(m1.Row3, m2.Column3);
return mOut;
}
unsigned int convertCoords(unsigned int x, unsigned int y)
{
return y * Width + x;
}
RasterFunc.h
#pragma once
#include "Shaders.h"
// Draws a line using one of the line equations.
void DrawLine(const Vertex& start, const Vertex& end)
{
// Copy input data and send through shaders
Vertex copy_start = start;
Vertex copy_end = end;
// Use vertex shader to modify incoming copies only.
if (VertexShader)
{
VertexShader(copy_start);
VertexShader(copy_end);
}
// original plotting variables adapted to use new cartesian data
SCREEN_XY screen_start = CartesianToScreen(copy_start);
SCREEN_XY screen_end = CartesianToScreen(copy_end);
// Standard line drawing code follows using integer coordinates...
for (numPixels)
{
A_PIXEL copyColor = currColor; // Just like a Vertex, copy original.
if (PixelShader) PixelShader(copyColor); // Modify copy.
PlotPixel(currX, c.
Similar to game.c Written by Peter Sutton. Game board da.docx (20)
Introduction to AI for Nonprofits with Tapp NetworkTechSoup
Dive into the world of AI! Experts Jon Hill and Tareq Monaur will guide you through AI's role in enhancing nonprofit websites and basic marketing strategies, making it easy to understand and apply.
Francesca Gottschalk - How can education support child empowerment.pptxEduSkills OECD
Francesca Gottschalk from the OECD’s Centre for Educational Research and Innovation presents at the Ask an Expert Webinar: How can education support child empowerment?
Model Attribute Check Company Auto PropertyCeline George
In Odoo, the multi-company feature allows you to manage multiple companies within a single Odoo database instance. Each company can have its own configurations while still sharing common resources such as products, customers, and suppliers.
Acetabularia Information For Class 9 .docxvaibhavrinwa19
Acetabularia acetabulum is a single-celled green alga that in its vegetative state is morphologically differentiated into a basal rhizoid and an axially elongated stalk, which bears whorls of branching hairs. The single diploid nucleus resides in the rhizoid.
Safalta Digital marketing institute in Noida, provide complete applications that encompass a huge range of virtual advertising and marketing additives, which includes search engine optimization, virtual communication advertising, pay-per-click on marketing, content material advertising, internet analytics, and greater. These university courses are designed for students who possess a comprehensive understanding of virtual marketing strategies and attributes.Safalta Digital Marketing Institute in Noida is a first choice for young individuals or students who are looking to start their careers in the field of digital advertising. The institute gives specialized courses designed and certification.
for beginners, providing thorough training in areas such as SEO, digital communication marketing, and PPC training in Noida. After finishing the program, students receive the certifications recognised by top different universitie, setting a strong foundation for a successful career in digital marketing.
Biological screening of herbal drugs: Introduction and Need for
Phyto-Pharmacological Screening, New Strategies for evaluating
Natural Products, In vitro evaluation techniques for Antioxidants, Antimicrobial and Anticancer drugs. In vivo evaluation techniques
for Anti-inflammatory, Antiulcer, Anticancer, Wound healing, Antidiabetic, Hepatoprotective, Cardio protective, Diuretics and
Antifertility, Toxicity studies as per OECD guidelines
Operation “Blue Star” is the only event in the history of Independent India where the state went into war with its own people. Even after about 40 years it is not clear if it was culmination of states anger over people of the region, a political game of power or start of dictatorial chapter in the democratic setup.
The people of Punjab felt alienated from main stream due to denial of their just demands during a long democratic struggle since independence. As it happen all over the word, it led to militant struggle with great loss of lives of military, police and civilian personnel. Killing of Indira Gandhi and massacre of innocent Sikhs in Delhi and other India cities was also associated with this movement.
game.c Written by Peter Sutton. Game board da.docx
1. /*
* game.c
*
* Written by Peter Sutton.
*
* Game board data is stored in an array of rowtype (which is
wide enough
* to hold a bit for each column). The bits of the rowtype
* represent whether that square is occupied or not (a 1
indicates
* occupied). The least significant BOARD_WIDTH bits are
used. The
* least significant bit is on the right.
*/
#include "game.h"
#include "blocks.h"
#include "score.h"
#include "ledmatrix.h"
/*
* Function prototypes.
* game.h has the prototypes for functions in this module which
* are available externally, and because we include "game.h"
above
* we do not need to repeat those prototypes.
*
* The prototypes below are for the internal functions - not
* accessible outside this module - so declared static.
* The implementations of these functions are at the bottom
* of the file - after the implementations of the publicly
* available functions.
*/
static void check_for_completed_rows(void);
static uint8_t add_random_block(void);
static uint8_t block_collides(FallingBlock block);
static void remove_current_block_from_board_display(void);
2. static void add_current_block_to_board_display(void);
/*
* Global variables.
* We keep two representations of the board:
* - an array of "rowtype" rows (which has one bit per
column
* which indicates whether the given position is occupied or
not). This
* representation does NOT include the current dropping
block.
* - an array of corresponding LED matrix columns (a row of
the game
* will be displayed on a column). This records colour
information
* for each position. This DOES include the current dropping
block.
* For both representations, the array is indexed from row 0.
* For "board" - column 0 (bit 0) is on the right
* For "board_display" - element 0 within each MatrixColumn
is on the left
*/
rowtype board[BOARD_ROWS];
MatrixColumn board_display[BOARD_ROWS];
FallingBlock current_block; // Current dropping block - there
will
// always be one if the game is being played
/*
* Initialise board - all the row data will be empty (0) and we
* create an initial random block and add it to the top of the
board.
*/
void init_game(void) {
// Clear the LED matrix
ledmatrix_clear();
for(uint8_t row=0; row < BOARD_ROWS; row++) {
board[row] = 0;
3. for(uint8_t col=0; col < MATRIX_NUM_ROWS; col++) {
board_display[row][col] = 0;
}
}
// Adding a random block will update the "current_block"
and
// add it to the board. With an empty board this will always
// succeed so we ignore the return value - this is indicated
// by the (void) cast. This function will update the display
// for the required rows.
(void)add_random_block();
}
/*
* Copy board to LED display for the rows given.
* Note that each "row" in the board corresponds to a column
for
* the LED matrix.
*/
void update_rows_on_display(uint8_t row_start, uint8_t
num_rows) {
uint8_t row_end = row_start + num_rows - 1;
for(uint8_t row_num = row_start; row_num <= row_end;
row_num++) {
ledmatrix_update_column(row_num,
board_display[row_num]);
}
}
/*
* Attempt to move the current block to the left or right.
* This succeeds if
* (1) the block isn't all the way to the side, and
* (2) the board contains no blocks in that position.
* Returns 1 if move successful, 0 otherwise.
*/
uint8_t attempt_move(int8_t direction) {
// Make a copy of the current block - we carry out the
4. // operations on the copy and copy it over to the
current_block
// if all is successful
FallingBlock tmp_block = current_block;
if(direction == MOVE_LEFT) {
if(!move_block_left(&tmp_block)) {
// Block was too far left - can't be moved
return 0;
}
} else {
// Attempt a move to the right
if(!move_block_right(&tmp_block)) {
// Block was too far right - can't be moved
return 0;
}
}
// The temporary block wasn't at the edge and has been
moved
// Now check whether it collides with any blocks on the
board.
if(block_collides(tmp_block)) {
// Block will collide with other blocks so the move can't
be
// made.
return 0;
}
// Block won't collide with other blocks so we can lock in
the move.
// First remove the current block from the display, update the
current
// block, then add it back to the board display
remove_current_block_from_board_display();
current_block = tmp_block;
5. add_current_block_to_board_display();
// Update the rows which are affected
update_rows_on_display(current_block.row,
current_block.height);
return 1;
}
/*
* Attempt to drop the current block by one row. This succeeds
unless there
* are squares blocked on the row below or we're at the bottom
of
* the board. Returns 1 if drop succeeded, 0 otherwise.
* (If the drop fails, the caller should add the block to the
board.)
*/
uint8_t attempt_drop_block_one_row(void) {
/*
* Check if the block has reached the bottom of the board.
* If so, do nothing and return false
*/
if(current_block.row + current_block.height >=
BOARD_ROWS) {
return 0;
}
/* Create a temporary block as a copy of the current block.
* Move it down 1 row and check whether it collides with
* any fixed blocks.
*/
FallingBlock tmp_block = current_block;
tmp_block.row += 1;
if(block_collides(tmp_block)) {
// Block will collide if moved down - so we can't move it
return 0;
}
6. // Move would succeed - so we make it happen
remove_current_block_from_board_display();
current_block = tmp_block;
add_current_block_to_board_display();
// Update the rows which are affected - starting from the row
before
// where the current block is.
update_rows_on_display(current_block.row - 1,
current_block.height + 1);
// Move was successful - indicate so
return 1;
}
/*
* Attempt to rotate the block clockwise 90 degrees. Returns 1
if the
* rotation is successful, 0 otherwise (e.g. a block on the board
* blocks the rotation or the block is too close to the left edge to
* rotate).
*/
uint8_t attempt_rotation(void) {
// Make a copy of the current block - we carry out the
// operations on the copy and copy it back to the
current_block
// if all is successful
FallingBlock tmp_block = current_block;
if(!rotate_block(&tmp_block)) {
// Block was too far left to rotate - abort
return 0;
}
// The temporary block has been rotated.
// Now check whether it collides with any blocks on the
7. board.
if(block_collides(tmp_block)) {
// Block will collide with other blocks so the rotate can't
be
// made.
return 0;
}
// Block won't collide with other blocks so we can lock in
the move.
// First determine the number of rows affected (to be
redrawn) -
// will be maximum of those in block before and after
rotation
uint8_t rows_affected = tmp_block.heigh t;
if(current_block.height > tmp_block.height) {
rows_affected = current_block.height;
}
// Second remove the current block from the display, update
the current
// block to the rotated version, then add it back to the board
display
remove_current_block_from_board_display();
current_block = tmp_block;
add_current_block_to_board_display();
update_rows_on_display(current_block.row, rows_affected);
// Rotation has happened - return true
return 1;
}
/*
* Add current block to board at its current position. We do this
using a
* bitwise OR for each row that contains the block. No display
update is
8. * required. We then attempt to add a new block to the top of
the board.
* If this suceeds, we return 1, otherwise we return 0 (meaning
game over).
*/
uint8_t fix_block_to_board_and_add_new_block(void) {
for(uint8_t row = 0; row < current_block.height; row++) {
uint8_t board_row = current_block.row + row;
board[board_row] |=
(current_block.pattern[row] <<
current_block.column);
}
check_for_completed_rows();
return add_random_block();
}
//////////////////////////////////////////////////////////////////////////
// Internal functions below
//////////////////////////////////////////////////////////////////////////
/* Function to check for completed rows on the board and
remove them.
* Higher rows are shifted down to occupy the removed rows.
Empty (black)
* rows are introduced at the top of the board. Both the boar d
and
* board_display representations are updated. If any rows are
complete and
* removed then we update the LED matrix. (Each row on the
board corresponds
* to a column on the LED matrix.)
*/
static void check_for_completed_rows(void) {
/* YOUR CODE HERE */
/* Suggested approach is to iterate over all the rows (0 to
* BOARD_ROWS -1) in the board and check if the row is all
ones
9. * i.e. matches ((1 << BOARD_WIDTH) - 1).
* If a row of all ones is found, the rows above the current
* one should all be moved down one position and a zero
(black)
* row inserted at the top.
* Repeat this process if more than one completed row is
* found. If any completed rows ar found and removed then
the
* relevant rows of the display must also be updated.
*
* Note that both representations of the board must be
updated:
* - board - which is the bitmap representation
* - board_display - which has the colours for each position in
the row
* (You may find functions in ledmatrix.h useful for
manipulating
* an LED matrix column structure - which corresponds to a
row in the game.)
*
* EXAMPLE OF MOVES REQUIRED
* If rows 11 and 13 are completed (all ones in the
* board representation), then
* rows 14 and 15 at the bottom will remain unchanged
* old row 12 becomes row 13
* old row 10 becomes row 12
* old row 9 becomes row 11
* ...
* old row 0 becomes row 2
* row 1 (second top row) is set to 0 (black)
* row 0 (top row) is set to 0 (black)
*/
}
/*
* Add random block, return false (0) if we can't add the block
10. - this
* means the game is over, otherwise we return 1.
*/
static uint8_t add_random_block(void) {
current_block = generate_random_block();
// Check if the block will collide with the fixed blocks on the
board
if(block_collides(current_block)) {
/* Block will collide. We don't add the block - just return
0 -
* the game is over.
*/
return 0;
}
/* Block won't collide with fixed blocks on the board so
* we update our board display.
*/
add_current_block_to_board_display();
// Update the display for the rows which are affected
update_rows_on_display(current_block.row,
current_block.height);
// The addition succeeded - return true
return 1;
}
/*
* Check whether the given block collides (intersects with) with
* the fixed blocks on the board. Return 1 if it does collide, 0
* otherwise.
*/
static uint8_t block_collides(FallingBlock block) {
// We work out the bit patterns for the block in each row
// and use a bitwise AND to determine whether there is an
// intersection or not
11. for(uint8_t row = 0; row < block.height; row++) {
rowtype bit_pattern_for_row = block.pattern[row] <<
block.column;
// The bit pattern to check this against will be that on the
board
// at the position where the block is located
if(bit_pattern_for_row & board[block.row + row]) {
// This row collides - we can stop now
return 1;
}
}
return 0; // No collisions detected
}
/*
* Remove the current block from the display structure
*/
static void remove_current_block_from_board_display(void) {
for(uint8_t row = 0; row < current_block.height; row++) {
uint8_t board_row = row + current_block.row;
for(uint8_t col = 0; col < current_block.width; col++) {
if(current_block.pattern[row] & (1 << col)) {
// This position in the block is occupied - zero it out
// in the display
uint8_t board_column = col + current_block.column;
uint8_t display_column = BOARD_WIDTH -
board_column - 1;
board_display[board_row][display_column] = 0;
}
}
}
}
/*
* Add the current block to the display structure
*/
static void add_current_block_to_board_display(void) {
for(uint8_t row = 0; row < current_block.height; row++) {
12. uint8_t board_row = row + current_block.row;
for(uint8_t col = 0; col < current_block.width; col++) {
if(current_block.pattern[row] & (1 << col)) {
// This position in the block is occupied - add it to
// the board display
uint8_t board_column = col + current_block.column;
uint8_t display_column = BOARD_WIDTH -
board_column - 1;
board_display[board_row][display_column] =
current_block.colour;
}
}
}
}
Solution
#include "game.h"
#include "blocks.h"
#include "score.h"
#include "ledmatrix.h"
static void check_for_completed_rows(void);
static uint8_t add_random_block(void);
static uint8_t block_collides(FallingBlock block);
static void remove_current_block_from_board_display(void);
static void add_current_block_to_board_display(void);
14. if(direction == MOVE_LEFT) {
if(!move_block_left(&tmp_block)) {
// Block was too far left - can't be moved
return 0;
}
} else {
// Attempt a move to the right
if(!move_block_right(&tmp_block)) {
// Block was too far right - can't be moved
return 0;
}
}
// The temporary block wasn't at the edge and has been moved
// Now check whether it collides with any blocks on the board.
if(block_collides(tmp_block)) {
return 0;
}
remove_current_block_from_board_display();
current_block = tmp_block;
add_current_block_to_board_display();
// Update the rows which are affected
update_rows_on_display(current_block.row,
15. current_block.height);
return 1;
}
uint8_t attempt_drop_block_one_row(void)
{
if(current_block.row + current_block.height >=
BOARD_ROWS) {
return 0;
}
FallingBlock tmp_block = current_block;
tmp_block.row += 1;
if(block_collides(tmp_block)) {
// Block will collide if moved down - so we can't move it
return 0;
}
// Move would succeed - so we make it happen
remove_current_block_from_board_display();
current_block = tmp_block;
add_current_block_to_board_display();
update_rows_on_display(current_block.row - 1,
current_block.height + 1);
16. return 1;
}
uint8_t attempt_rotation(void) {
FallingBlock tmp_block = current_block;
if(!rotate_block(&tmp_block)) {
// Block was too far left to rotate - abort
return 0;
}
if(block_collides(tmp_block)) {
return 0;
}
uint8_t rows_affected = tmp_block.height;
if(current_block.height > tmp_block.height) {
rows_affected = current_block.height;
}
remove_current_block_from_board_display();
current_block = tmp_block;
add_current_block_to_board_display();
update_rows_on_display(current_block.row, rows_affected);
// Rotation has happened - return true
17. return 1;
}
If this suceeds, we return 1, otherwise we return 0 (meaning
game over).
uint8_t fix_block_to_board_and_add_new_block(void) {
for(uint8_t row = 0; row < current_block.height; row++) {
uint8_t board_row = current_block.row + row;
board[board_row] |=
(current_block.pattern[row] << current_block.colu mn);
}
check_for_completed_rows();
return add_random_block();
}
static void check_for_completed_rows(void) {
/* YOUR CODE HERE */
/* Suggested approach is to iterate over all the rows (0 to
* BOARD_ROWS -1) in the board and check if the row is all
ones
* i.e. matches ((1 << BOARD_WIDTH) - 1).
* If a row of all ones is found, the rows above the current
* one should all be moved down one position and a zero (black)
* row inserted at the top.
* Repeat this process if more than one completed row is
* found. If any completed rows ar found and removed then the
18. * relevant rows of the display must also be updated.
*
* Note that both representations of the board must be updated:
* - board - which is the bitmap representation
* - board_display - which has the colours for each position in
the row
* (You may find functions in ledmatrix.h useful for
manipulating
* an LED matrix column structure - which corresponds to a row
in the game.)
*
* EXAMPLE OF MOVES REQUIRED
* If rows 11 and 13 are completed (all ones in the
* board representation), then
* rows 14 and 15 at the bottom will remain unchanged
* old row 12 becomes row 13
* old row 10 becomes row 12
* old row 9 becomes row 11
* ...
* old row 0 becomes row 2
* row 1 (second top row) is set to 0 (black)
* row 0 (top row) is set to 0 (black)
*/
}
19. static uint8_t add_random_block(void) {
current_block = generate_random_block();
// Check if the block will collide with the fixed blocks on the
board
if(block_collides(current_block)) {
return 0;
}
add_current_block_to_board_display();
// Update the display for the rows which are affected
update_rows_on_display(current_block.row,
current_block.height);
// The addition succeeded - return true
return 1;
}
static uint8_t block_collides(FallingBlock block) {
for(uint8_t row = 0; row < block.height; row++) {
rowtype bit_pattern_for_row = block.pattern[row] <<
block.column;
if(bit_pattern_for_row & board[block.row + row]) {
// This row collides - we can stop now
return 1;
}
20. }
return 0; // No collisions detected
}
static void remove_current_block_from_board_display(void) {
for(uint8_t row = 0; row < current_block.height; row++) {
uint8_t board_row = row + current_block.row;
for(uint8_t col = 0; col < current_block.width; col++) {
if(current_block.pattern[row] & (1 << col)) {
// This position in the block is occupied - zero it out
// in the display
uint8_t board_column = col + current_block.column;
uint8_t display_column = BOARD_WIDTH - board_column -
1;
board_display[board_row][display_column] = 0;
}
}
}
}
static void add_current_block_to_board_display(void) {
for(uint8_t row = 0; row < current_block.height; row++) {
uint8_t board_row = row + current_block.row;
for(uint8_t col = 0; col < current_block.width; col++) {
if(current_block.pattern[row] & (1 << col)) {
uint8_t board_column = col + current_block.column;
uint8_t display_column = BOARD_WIDTH - board_column -