How to insert coordinates of a table into an array in PHP - php

I am making the game battleships in PHP and I need to make it so that the computer randomly chooses 5 coordinates(x, y), and they have to be in a straight line (column or row). How do I make it so the coordinates are in a line and how do I connect the coordinates to the table cells?
Here's what I have so far:
<?php
session_start();
$i=0;
$start=1;
$st=65;
$l=0;
$polje=array();
$x=(mt_rand(0, 10));
$y=(mt_rand(0, 10));
for($q=0; $q<5; $q++){
$polje[$l]=array($x, $y);
}
echo "<table id='table'>\n";
while ($i<11){
$ascii=chr($st);
echo "<tr>";
for($k=0; $k<11; $k++, $start++){
if($k==0){
echo "<td>$i</td>";
}
else if($i==0){
echo "<td class='td2'>$ascii</td>";
$ascii++;
}
else{
echo "<td class='td1'> </td>";
}
}
echo "</tr>";
$i++;
}
?>
This is what the table looks like:

I like this kind of challenge.
Of course, there is a lot of ways, better ways to do this, with OOP, but you can get the point.
Read the comments through the code and if you have any doubts feel free to ask.
I did some treatment to avoid ships overlapping each other, and random deployment.
const BOARD_SIZE = 10; //10x10 board
const SUBMARINE = 1;
const DESTROYER = 2;
const BATTLESHIP = 3;
const AIRCRAFTCARRIER = 4;
$ships_available = [];
//populate with some data based on game rule
array_push($ships_available, SUBMARINE);
array_push($ships_available, SUBMARINE);
array_push($ships_available, DESTROYER);
array_push($ships_available, DESTROYER);
array_push($ships_available, DESTROYER);
array_push($ships_available, BATTLESHIP);
array_push($ships_available, BATTLESHIP);
array_push($ships_available, AIRCRAFTCARRIER);
$board = [];
while(count($ships_available) > 0) {
deployShip($board, $ships_available);
}
$lastColumnLetter = chr(ord('A')+ BOARD_SIZE-1);
//print table
echo "<table border='1' align='center'>";
echo "<tr><td></td><td>".implode('</td><td>',range(1, BOARD_SIZE))."</td></tr>";
for($i = 'A'; $i <= $lastColumnLetter; $i++) {
echo "<tr><td>".$i."</td>";
for($j=0; $j < BOARD_SIZE; $j++) {
echo "<td align='center'>";
echo $board[$i][$j] ?: ' ';
echo "</td>";
}
echo "</tr>";
}
echo "</table>";
exit;
function array_merge_custom($array1, $array2) {
foreach($array2 as $key => $value) {
foreach($value as $k => $v) {
$array1[$key][$k] = $v;
}
}
return $array1;
}
function deployShip(&$board, &$ships_available) {
$randomShipKey = array_rand($ships_available);
$ship = $ships_available[$randomShipKey];
$beginCoordinates = getRandomCoordinates();
$coordinates = getShipCoordinates($board, $beginCoordinates, $ship);
if(!$coordinates) {
return false;
}
unset($ships_available[$randomShipKey]);
$board = array_merge_custom($board,$coordinates);
}
function getRowNumberByLetter($letter) {
return array_search($letter, range('A','Z'));
}
function getRowLetterByNumber($number) {
$letters = range('A','Z');
return $letters[$number];
}
function getRandomCoordinates() {
return ['row' => chr(mt_rand(ord('A'), (ord('A') + BOARD_SIZE-1))), 'col' => mt_rand(0,BOARD_SIZE -1)];
}
function getShipCoordinates($board, $beginCoordinates, $ship) {
if(isset($board[$beginCoordinates['row']][$beginCoordinates['col']])) {
return false; //anchor position already taken
}
if($ship == 1) {
$return[$beginCoordinates['row']][$beginCoordinates['col']] = 1;
return $return;
}
$shipArraySize = $ship -1;
$directions = ['left', 'right', 'up', 'down'];
$tries = 10;
while($tries > 0) {
$tries--;
$direction = $directions[array_rand($directions)];
$return = [];
switch($direction) {
case 'left':
if(($beginCoordinates['col'] - $shipArraySize) < 0) { //check if can go left
break;
}
for($colBegin = ($beginCoordinates['col'] - $shipArraySize), $colEnd = $beginCoordinates['col']; $colBegin <= $colEnd; $colBegin++) {
if(!empty($board[$beginCoordinates['row']][$colBegin])) {
break 2;
} else {
$return[$beginCoordinates['row']][$colBegin] = $ship;
}
}
return $return;
case 'right':
if(($beginCoordinates['col'] + $shipArraySize) > BOARD_SIZE -1) { //check if can go right
break;
}
for($colBegin = $beginCoordinates['col'], $colEnd = ($beginCoordinates['col'] + $shipArraySize); $colBegin <= $colEnd; $colBegin++) {
if(!empty($board[$beginCoordinates['row']][$colEnd])) {
break 2;
} else {
$return[$beginCoordinates['row']][$colBegin] = $ship;
}
}
return $return;
case 'up':
if((getRowNumberByLetter($beginCoordinates['row']) - $shipArraySize) < 0) { //check if can go up
break;
}
for($rowBegin = (getRowNumberByLetter($beginCoordinates['row']) - $shipArraySize), $rowEnd = getRowNumberByLetter($beginCoordinates['row']); $rowBegin <= $rowEnd; $rowBegin++) {
if(!empty($board[getRowLetterByNumber($rowBegin)][$beginCoordinates['col']])) {
break 2;
} else {
$return[getRowLetterByNumber($rowBegin)][$beginCoordinates['col']] = $ship;
}
}
return $return;
case 'down':
if((getRowNumberByLetter($beginCoordinates['row']) + $shipArraySize) > BOARD_SIZE -1) { //check if can go down
break;
}
for($rowBegin = getRowNumberByLetter($beginCoordinates['row']), $rowEnd = (getRowNumberByLetter($beginCoordinates['row']) + $shipArraySize); $rowBegin <= $rowEnd; $rowBegin++) {
if(!empty($board[getRowLetterByNumber($rowBegin)][$beginCoordinates['col']])) {
break 2;
} else {
$return[getRowLetterByNumber($rowBegin)][$beginCoordinates['col']] = $ship;
}
}
return $return;
}
}
return false;
}

Related

How to export data in excel dynamically using PHPSpreadsheet/PHPExcel in PHP?

I have some data which I am trying to export in an excel sheet with help of PHP, data is dynamic so I am facing difficulties while exporting them. I have tried both in PHPExcel (which is deprecated) and in PHPSpreadsheet too. I have tried lots of solutions given in the community but no help!
How to print data dynamically in excel using PHP?
Data needs to print from column number = 36 (AK) and Row = 2
Data that needs to export:
MongoDB\Model\BSONDocument Object
(
[storage:ArrayObject:private] => Array
(
[dd1] => PWC>Yes,Deloitte>Yes,Media Type>Category A,Coverage Type>Quote,Service Line>TAX,Score>5
[dd2] => Service Line>Personal tax
)
)
though [dd1] contains labels and values too, like PWC[this is lable] >Yes [this is value], that's why I explode label and value separately.
Also, I have printed the labels in the first row already that's why I explode the value of the below code and also made a check if ($temp[0] == $labels[$i]) then only print value.
Completed Code:
$cols = 36;
for ($i = 0; $i < count($labels); $i++) {
if ($result["qualification"]["dd1"] != "") {
$found = false;
for ($j = 0; $j < count($dd1); $j++) {
$temp = explode(">", $dd1[$j]);
//need to check the weather labels of the header and these labels are the same? then only print
if ($temp[0] == $labels[$i]) {
$name = explode(">", $dd1[$j]);
$sheet->setCellValueByColumnAndRow($cols+1, $j+1, $name[1]);
$found = true;
break;
}
}
if (!$found)
$sheet->setCellValueByColumnAndRow($cols+1, $j+1 , "");
} else
$sheet->setCellValueByColumnAndRow($cols+1 , $j+1 , "");
if ($result["qualification"]["dd2"] != "") {
$found = false;
for ($j = 0; $j < count($dd2); $j++) {
$temp = explode(">", $dd2[$j]);
if ($temp[0] == $labels[$i]) {
$name = explode(">", $dd2[$j]);
$sheet->setCellValueByColumnAndRow( $cols, $j + 2, $name[1] );
$found = true;
break;
}
}
if (!$found)
$sheet->setCellValueByColumnAndRow($cols, $j+1 , "");
} else {
$sheet->setCellValueByColumnAndRow($cols , $j+1 , "");
}
$cols = $cols + 2;
}
I have tried lots of methods but no help but I made something in the HTML table which is working fine, unfortunately, I do not need an HTML table to excel because it has a lot of format issues and cons.
for reference only-
Here is the same working snippet in HTML Table:
$inn_table = "";
if($result['qualification']['dd1']!="") {
$dd1 = explode(",",$result['qualification']['dd1']);
}
if($result['qualification']['dd2']!=""){
$dd2 = explode(",",$result['qualification']['dd2']);
}
for($i=0;$i<count($labels);$i++) {
if($result['qualification']['dd1']!="") {
$found=false;
for($j=0;$j<count($dd1);$j++) {
$temp = explode(">",$dd1[$j]);
if($temp[0]==$labels[$i]) {
$name = explode(">",$dd1[$j]);
$inn_table .= '<td>'.$name[1].'</td>';
$found=true;
break;
}
}
if(!$found)
$inn_table .= "<td> </td>";
}
else
$inn_table .= "<td> </td>";
if($result['qualification']['dd2']!="") {
$found=false;
// echo '<pre>ass';print_r($dd2);
for($j=0;$j<count($dd2);$j++) {
$temp = explode(">",$dd2[$j]);
if($temp[0]==$labels[$i]) {
$name = explode(">",$dd2[$j]);
$inn_table .= '<td>'.$name[1].'</td>';
$found=true;
break;
}
}
if(!$found)
$inn_table .= '<td> </td>';
}
else{
//if(count($dd2Array)>0){
$inn_table .= '<td> </td>';
//}
}
} //end of for($i=0;$i<count($labels);$i++)
echo $inn_table;
echo "</tr>";

Printing prime numbers from an user's input php

I'm trying ta make a program that will ask the user for a number and then show all the prime numbers between 0 to this number in an array.
<?php
class SmallerPrimes{
public function __construct($file){
$this->input_filename = $file;
}
public function Main(){
$smaller_than = (int)$this->readString()[0];
$result = array();
/* YOUR CODE HERE */
function isPrime($n)
{
if ($n <= 1)
return false;
for ($i = 2; $i < $n; $i++)
if ($n % $i == 0)
return false;
return true;
}
function printPrime($n)
{
for ($i = 2; $i <= $n; $i++)
{
if (isPrime($i))
echo $i . " ";
}
}
$n = 7;
printPrime($n);
/*end of your code here */
return $result;
}
public function readString(){
$file = fopen($this->input_filename, "r");
$line = array();
while (!feof($file)){
array_push($line, str_replace(PHP_EOL, "", fgets($file)));
}
return $line;
}
}
$o = new SmallerPrimes($argv[1]);
echo implode(" ", $o->Main()) . PHP_EOL;
This code work, but with a $n fixed.
I don't know how to use an input who ask the user a number
It's a code who verify itself and show us when it's ok
The code that i have to complete is this one (we only have this at first):
class SmallerPrimes{
public function __construct($file){
$this->input_filename = $file;
}
public function Main(){
$smaller_than = (int)$this->readString()[0];
$result = array();
/* YOUR CODE HERE */
return $result;
}
public function readString(){
$file = fopen($this->input_filename, "r");
$line = array();
while (!feof($file)){
array_push($line, str_replace(PHP_EOL, "", fgets($file)));
}
return $line;
}
}
$o = new SmallerPrimes($argv[1]);
echo implode(" ", $o->Main()) . PHP_EOL;
This is your script:
<?php
class SmallerPrimes{
public function __construct($file){
$this->input_filename = $file;
}
public function Main(){
$smaller_than = (int)$this->readString()[0];
$result = array();
function isPrime($n) {
if ($n <= 1) return false;
for ($i = 2; $i < $n; $i++) if ($n % $i == 0) return false;
return true;
}
function printPrime($n) {
for ($i = 2; $i < $n; $i++) if (isPrime($i)) $result[] = $i;
return $result;
}
$result = printPrime($smaller_than);
return $result;
}
public function readString(){
$file = fopen($this->input_filename, "r");
$line = array();
while (!feof($file)){
array_push($line, str_replace(PHP_EOL, "", fgets($file)));
}
return $line;
}}
$o = new SmallerPrimes($argv[1]);
echo implode(" ", $o->Main()) . PHP_EOL;
function getSmallerPrimes($smaller_than) {
if ($smaller_than <= 2) {
return [];
}
$result = [2];
$sqrt = sqrt($smaller_than);
for ($n = 3; $n < $smaller_than; $n += 2) {
$isPrime = true;
foreach($result as $prime) {
if ($n % $prime == 0) {
$isPrime = false;
break;
}
if ($prime > $sqrt) {
break;
}
}
if ($isPrime) {
$result[] = $n;
}
}
return $result;
}
$input = 23;
echo implode(' ', getSmallerPrimes($input));
Result: 2 3 5 7 11 13 17 19

PHP Check if 2 variables are the same, like a test

I need help to check if variables (from a database) are the same, like a test.
First I was using just "==", but I saw this: http://php.net/manual/en/language.operators.comparison.php , and now I'm using "===". But it still doesn't work.
My code:
$uids = array();
$trues = array();
while ($row = mysqli_fetch_assoc($result)) {
array_push($uids, $row['UID']);
} while ($row1 = mysqli_fetch_assoc($result1)) {
array_push($uids, $row1['UID']);
} while ($row2 = mysqli_fetch_assoc($result2)) {
array_push($uids, $row2['UID']);
}
for ($i = 0; $i < count($uids); $i++) {
$r = 0;
if ($row['question1'] === $row['uAnswer1']) {
$r++;
} else {
$r = $r;
} if ($row['question2'] === $row['uAnswer2']) {
$r++;
} else {
$r = $r;
} if ($row['question3'] === $row['uAnswer3']) {
$r++;
} else {
$r = $r;
} if ($row['question4'] === $row['uAnswer4']) {
$r++;
} else {
$r = $r;
} if ($row['question5'] === $row['uAnswer5']) {
$r++;
} else {
$r = $r;
} if ($row['question6'] === $row['uAnswer6']) {
$r++;
} else {
$r = $r;
} if ($row['question7'] === $row['uAnswer7']) {
$r++;
} else {
$r = $r;
} if ($row['question8'] === $row['uAnswer8']) {
$r++;
} else {
$r = $r;
} if ($row['question9'] === $row['uAnswer9']) {
$r++;
} else {
$r = $r;
} if ($row['question10'] === $row['uAnswer10']) {
$r++;
} else {
$r = $r;
}
array_push($trues, $r);
echo $uids[$i] . " [" . $r . "]<br>";
}
print_r($trues);
}
What the result is: https://hastebin.com/uxitoyoyib.php
So it actually says everything is right, but I know that it isn't. Can you help me with this?
Thanks!
Compare variables like
if ( strtolower(trim($row['question5'])) === strtolower(trim($row['uAnswer5'])) )
Remove spaces if added with strings, convert the string in lowercase to the exact match of both strings.
use
if ($row['question4'] == $row['uAnswer4']) {
//do something
}
and try to print your 2 variable.
You can use the strcmp() or strcasecmp() functions or the === operator.

In PHPExcel i merger three cell and having foreach loop. Result next value not printed after merge

$periodOne=array(array('SNO','Appraisal','TOT','AVG','CLS TOT','CLS AVG','DIFF'));
$rowID = 7;
foreach($periodOne as $rowArray) {
$columnID = 'A';
foreach($rowArray as $columnValue) {
$this->setActiveSheetIndex(0)->mergeCells('B7:D7');
$this->getActiveSheet()->setCellValue($columnID.$rowID,$columnValue);
$columnID++;
}
$rowID++;
}
$periodOne=array(array('SNO','Appraisal','TOT','AVG','CLS TOT','CLS AVG','DIFF'));
$rowID = 7;
foreach($periodOne as $rowArray) {
$columnID = 'A';
foreach($rowArray as $columnValue) {
if($columnID.$rowID == 'C7')
{
$columnID = 'E';
$this->getActiveSheet()->setCellValue($columnID.$rowID,$columnValue);
}
else
{
$this->getActiveSheet()->setCellValue($columnID.$rowID,$columnValue);
}
$columnID++;
}
$rowID++;
}

base64 in PHP Otp Library

I trying to make some simple library for encrypting files in PHP with OTP method. My problem is that some chars in decrypted code are different than original. I worked on it almost one week but without result. Is there problem with base64 chars or with encoding/decoding mechanism ?
Many thanks for the answers.
final class Otp
{
private static $charSet = array('+','/','0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L',
'M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r',
's','t','u','v','w','x','y','z');
public static function encryptFile($originalFilePath, $encryptedFilePath, $keyFilePath)
{
if(!self::existsFile($keyFilePath) || !self::existsFile($encryptedFilePath)) {
if($originalFileData = self::existsFile($originalFilePath)) {
$originalFileBase64Data = base64_encode($originalFileData);
$originalFileBase64DataLength = strlen($originalFileBase64Data) - 1;
$originalFileBase64DataArray = str_split($originalFileBase64Data);
$encryptedData = NULL;
$encryptedDataKey = NULL;
for ($i = 0; $i <= $originalFileBase64DataLength; $i++) {
$randKey = rand(0, sizeOf(self::$charSet) - 1);
$arrayKey = array_search($originalFileBase64DataArray[$i], self::$charSet);
if($randKey > $arrayKey) {
$str = '-' . ($randKey - $arrayKey);
} elseif($randKey < $arrayKey) {
$str = ($randKey + $arrayKey);
} else {
$str = $randKey;
}
$encryptedData .= self::$charSet[$randKey];
$encryptedDataKey .= $str. ';';
}
$encryptedDataString = $encryptedData;
$encryptedDataKeyString = $encryptedDataKey;
if(!self::existsFile($keyFilePath)) {
file_put_contents($keyFilePath, $encryptedDataKeyString);
}
if(!self::existsFile($encryptedFilePath)) {
file_put_contents($encryptedFilePath, $encryptedDataString);
}
return 'OK';
} else {
return 'Source file not exists';
}
} else {
return 'Encrypted data already exists';
}
}
public static function decryptFile($encryptedFilePath, $keyFilePath, $decryptedFilePath)
{
$keyFileData = self::existsFile($keyFilePath);
$encryptedFileData = self::existsFile($encryptedFilePath);
$encryptedFileDataLength = strlen($encryptedFileData) - 1;
if($encryptedFileData && $keyFileData) {
$encryptedFileDataArray = str_split($encryptedFileData);
$keyFileDataArray = explode(';', $keyFileData);
$decryptedData = NULL;
for ($i = 0; $i <= $encryptedFileDataLength; $i++) {
$poziciaaktualneho = array_search($encryptedFileDataArray[$i], self::$charSet);
$poziciasifrovana = $keyFileDataArray[$i];
if($poziciasifrovana < 0) {
$move = $poziciasifrovana + $poziciaaktualneho;
} elseif($poziciasifrovana > 0) {
$move = $poziciasifrovana - $poziciaaktualneho;
} else {
$move = '0';
}
$decryptedData .= self::$charSet[$move];
}
if(!self::existsFile($decryptedFilePath)) {
file_put_contents($decryptedFilePath, base64_decode($decryptedData));
return 'OK';
} else {
return 'Decrypted data already exists';
}
}
}
private static function existsFile($filePath)
{
$fileData = #file_get_contents($filePath);
if($fileData) {
return $fileData;
}
return FALSE;
}
}
$originalFilePath = 'original.jpg';
$keyFilePath = 'Otp_Key_' . $originalFilePath;
$encryptedFilePath = 'Otp_Data_' . $originalFilePath;
$decryptedFilePath = 'Otp_Decrypted_' . $originalFilePath;
echo Otp::encryptFile($originalFilePath, $encryptedFilePath, $keyFilePath);
echo Otp::decryptFile($encryptedFilePath, $keyFilePath, $decryptedFilePath);
The problem seems to be only happening when $poziciaaktualneho is equal to $poziciasifrovana and so by adding another if statement on line 78 to check for this and instead set $move equal to $poziciasifrovana I was able to fix the problem. The below script should work:
final class Otp
{
private static $charSet = array('+','/','0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L',
'M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r',
's','t','u','v','w','x','y','z');
public static function encryptFile($originalFilePath, $encryptedFilePath, $keyFilePath)
{
if(!self::existsFile($keyFilePath) || !self::existsFile($encryptedFilePath)) {
if($originalFileData = self::existsFile($originalFilePath)) {
$originalFileBase64Data = base64_encode($originalFileData);
$originalFileBase64DataLength = strlen($originalFileBase64Data) - 1;
$originalFileBase64DataArray = str_split($originalFileBase64Data);
$encryptedData = NULL;
$encryptedDataKey = NULL;
for ($i = 0; $i <= $originalFileBase64DataLength; $i++) {
$randKey = rand(0, sizeOf(self::$charSet) - 1);
$arrayKey = array_search($originalFileBase64DataArray[$i], self::$charSet);
if($randKey > $arrayKey) {
$str = '-' . ($randKey - $arrayKey);
} elseif($randKey < $arrayKey) {
$str = ($randKey + $arrayKey);
} else {
$str = $randKey;
}
$encryptedData .= self::$charSet[$randKey];
$encryptedDataKey .= $str. ';';
}
$encryptedDataString = $encryptedData;
$encryptedDataKeyString = $encryptedDataKey;
if(!self::existsFile($keyFilePath)) {
file_put_contents($keyFilePath, $encryptedDataKeyString);
}
if(!self::existsFile($encryptedFilePath)) {
file_put_contents($encryptedFilePath, $encryptedDataString);
}
return 'OK';
} else {
return 'Source file not exists';
}
} else {
return 'Encrypted data already exists';
}
}
public static function decryptFile($encryptedFilePath, $keyFilePath, $decryptedFilePath)
{
$keyFileData = self::existsFile($keyFilePath);
$encryptedFileData = self::existsFile($encryptedFilePath);
$encryptedFileDataLength = strlen($encryptedFileData) - 1;
if($encryptedFileData && $keyFileData) {
$encryptedFileDataArray = str_split($encryptedFileData);
$keyFileDataArray = explode(';', $keyFileData);
$decryptedData = NULL;
for ($i = 0; $i <= $encryptedFileDataLength; $i++) {
$poziciaaktualneho = array_search($encryptedFileDataArray[$i], self::$charSet);
$poziciasifrovana = $keyFileDataArray[$i];
if ($poziciasifrovana == $poziciaaktualneho) {
$move = $poziciasifrovana;
} elseif($poziciasifrovana < 0) {
$move = $poziciasifrovana + $poziciaaktualneho;
} elseif($poziciasifrovana > 0) {
$move = $poziciasifrovana - $poziciaaktualneho;
} else {
$move = '0';
}
$decryptedData .= self::$charSet[$move];
}
if(!self::existsFile($decryptedFilePath)) {
file_put_contents($decryptedFilePath, base64_decode($decryptedData));
return 'OK';
} else {
return 'Decrypted data already exists';
}
}
}
private static function existsFile($filePath)
{
$fileData = #file_get_contents($filePath);
if($fileData) {
return $fileData;
}
return FALSE;
}
}
$originalFilePath = 'original.jpg';
$keyFilePath = 'Otp_Key_' . $originalFilePath;
$encryptedFilePath = 'Otp_Data_' . $originalFilePath;
$decryptedFilePath = 'Otp_Decrypted_' . $originalFilePath;
echo Otp::encryptFile($originalFilePath, $encryptedFilePath, $keyFilePath);
echo Otp::decryptFile($encryptedFilePath, $keyFilePath, $decryptedFilePath);
Warning: I would not recommend using my solution in an enterprise setting if at all since I do not know why this fixes your script or what was
originally wrong with it and it is most likely not air tight.

Categories