Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

hw5 #5

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added .DS_Store
Binary file not shown.
29 changes: 29 additions & 0 deletions HW1.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ChessBoard</title>
<style>
table {
border-collapse: collapse;
margin: auto;
}
tr {
height: 50px;
width: 50px;
}
td {
border: 1px solid #888888;
width: 50px;
height: 50px;
background-color: #EEEEEE;
text-align: center;
font-size: 2em;
}
</style>
</head>
<body>
<table id="game"></table>
<script src="HW1.js"></script>
</body>
</html>
54 changes: 54 additions & 0 deletions HW1.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
"use strict";

const chess = {
gameContainerEl: document.getElementById('game'),
render() {
// Названия колонок
const cols = [0, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 0];
// Названия рядов
const rows = [0, 8, 7, 6, 5, 4, 3, 2, 1, 0];

// Цикл для строк
for (let row = 0; row < 10; row++) {
// Создаем и добавляем строку.
const tr = document.createElement('tr');
this.gameContainerEl.appendChild(tr);

// Добавляем ячейки в строку.
for (let col = 0; col < 10; col++) {
// Создаем и добавляем ячейку.
const td = document.createElement('td');
tr.appendChild(td);

// Если строка/столбец первая или последняя по счету, значит выводим буквы в ней.
// Нули из массива с названиями не выводим.
if (row === 0 && cols[col] !== 0) {
td.innerHTML = cols[col];
} else if (row === 9 && cols[col] !== 0) {
td.innerHTML = cols[col];
} else if (col === 0 && rows[row] !== 0) {
td.innerHTML = rows[row];
} else if (col === 9 && rows[row] !== 0) {
td.innerHTML = rows[row];
}

// Проверяем, надо ли покрасить ячейку, передаем строку и колонку.
if (this.isCellIsBlack(row, col)) {
td.style.backgroundColor = 'grey';
}
}
}
},

// Метод определяет нужно ли покрасить ячейку.
isCellIsBlack(rowNum, colNum) {
if (rowNum > 0 && rowNum < 9 && colNum > 0 && colNum < 9) {
return (rowNum + colNum) % 2;
}
// Если будет остаток, то он даст true в условии, а если не будет, то 0 даст false в условии.

},
};

// Запускаем метод render.
chess.render();
29 changes: 29 additions & 0 deletions HW2.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ChessBoard</title>
<style>
table {
border-collapse: collapse;
margin: auto;
}
tr {
height: 50px;
width: 50px;
}
td {
border: 1px solid #888888;
width: 50px;
height: 50px;
background-color: #EEEEEE;
text-align: center;
font-size: 2em;
}
</style>
</head>
<body>
<table id="game"></table>
<script src="HW2.js"></script>
</body>
</html>
125 changes: 125 additions & 0 deletions HW2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
"use strict";

const chess = {
gameContainerEl: document.getElementById('game'),
figures: [
{name: 'p', color: 'W', pos: 'a2'},
{name: 'p', color: 'W', pos: 'b2'},
{name: 'p', color: 'W', pos: 'c2'},
{name: 'p', color: 'W', pos: 'd2'},
{name: 'p', color: 'W', pos: 'e2'},
{name: 'p', color: 'W', pos: 'f2'},
{name: 'p', color: 'W', pos: 'g2'},
{name: 'p', color: 'W', pos: 'h2'},
{name: 'R', color: 'W', pos: 'a1'},
{name: 'R', color: 'W', pos: 'h1'},
{name: 'H', color: 'W', pos: 'b1'},
{name: 'H', color: 'W', pos: 'g1'},
{name: 'B', color: 'W', pos: 'c1'},
{name: 'B', color: 'W', pos: 'f1'},
{name: 'Q', color: 'W', pos: 'd1'},
{name: 'K', color: 'W', pos: 'e1'},
{name: 'p', color: 'B', pos: 'a7'},
{name: 'p', color: 'B', pos: 'b7'},
{name: 'p', color: 'B', pos: 'c7'},
{name: 'p', color: 'B', pos: 'e7'},
{name: 'p', color: 'B', pos: 'd7'},
{name: 'p', color: 'B', pos: 'f7'},
{name: 'p', color: 'B', pos: 'g7'},
{name: 'p', color: 'B', pos: 'h7'},
{name: 'R', color: 'B', pos: 'a8'},
{name: 'R', color: 'B', pos: 'h8'},
{name: 'H', color: 'B', pos: 'b8'},
{name: 'H', color: 'B', pos: 'g8'},
{name: 'B', color: 'B', pos: 'c8'},
{name: 'B', color: 'B', pos: 'f8'},
{name: 'Q', color: 'B', pos: 'd8'},
{name: 'K', color: 'B', pos: 'e8'},
],
figureHtml: {
pW: '&#9817;',
RW: '&#9814;',
HW: '&#9816;',
BW: '&#9815;',
QW: '&#9813;',
KW: '&#9812;',
pB: '&#9823;',
RB: '&#9820;',
HB: '&#9822;',
BB: '&#9821;',
QB: '&#9819;',
KB: '&#9818;',
},


render() {
// Названия колонок
const cols = [0, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 0];
// Названия рядов
const rows = [0, 8, 7, 6, 5, 4, 3, 2, 1, 0];


// Цикл для строк
for (let row = 0; row < 10; row++) {
// Создаем и добавляем строку.
const tr = document.createElement('tr');
this.gameContainerEl.appendChild(tr);

// Добавляем ячейки в строку.
for (let col = 0; col < 10; col++) {
// Создаем и добавляем ячейку.
const td = document.createElement('td');
tr.appendChild(td);

// Если строка/столбец первая или последняя по счету, значит выводим буквы в ней.
// Нули из массива с названиями не выводим.
if (row === 0 && cols[col] !== 0) {
td.innerHTML = cols[col];
} else if (row === 9 && cols[col] !== 0) {
td.innerHTML = cols[col];
} else if (col === 0 && rows[row] !== 0) {
td.innerHTML = rows[row];
} else if (col === 9 && rows[row] !== 0) {
td.innerHTML = rows[row];
}

// Проверяем, надо ли покрасить ячейку, передаем строку и колонку.
if (this.isCellIsBlack(row, col)) {
td.style.backgroundColor = 'grey';
}

if (row > 0 && row < 3 && col > 0 && col < 9) {
td.innerHTML = this.renderFigure(rows[row], cols[col]);
} else if (row > 6 && row < 9 && col > 0 && col < 9) {
td.innerHTML = this.renderFigure(rows[row], cols[col]);
}
}
}
},

// Метод определяет нужно ли покрасить ячейку.
isCellIsBlack(rowNum, colNum) {
if (rowNum > 0 && rowNum < 9 && colNum > 0 && colNum < 9) {
return (rowNum + colNum) % 2;
}
// Если будет остаток, то он даст true в условии, а если не будет, то 0 даст false в условии.
},

renderFigure(rowNum, colNum) {
for (let figure = 0; figure < this.figures.length; figure++) {
// Берем одну фигуру, для примера первую.
const usedFigure = this.figures[figure];
// Получаем имя фигуры и цвет в одну строку.
const figureHtmlProperty = usedFigure.name + usedFigure.color;
// Получаем код фигуры из this.figureHtml используя строку из названия фигуры и ее цвета.
const figureCode = this.figureHtml[figureHtmlProperty];
if (usedFigure.pos === colNum + rowNum) {
return figureCode;
}
}
}
};

// Запускаем метод render.
chess.render();
// chess.renderFigure();
41 changes: 41 additions & 0 deletions HW3.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Форма</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css"
integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">
<style>
.form-wrap {
margin: auto;
padding: 20px;
max-width: 800px;
}
</style>
</head>
<body>
<div class="form-wrap">
<form class="my-form" action="">
<div class="form-row">
<div class="form-group col-md-6">
<input type="text" name="name" class="form-control" placeholder="Имя">
</div>
<div class="form-group col-md-6">
<input type="text" name="phone" class="form-control" placeholder="Телефон" id="phone">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6">
<input type="password" name="password" class="form-control" placeholder="Пароль" id="password">
</div>
<div class="form-group col-md-6">
<input type="password" name="password_repeat" class="form-control" placeholder="Повторите пароль"
id="password_repeat">
</div>
</div>
<button type="submit" class="btn btn-primary">Отправить</button>
</form>
</div>
<script src="HW3.js"></script>
</body>
</html>
96 changes: 96 additions & 0 deletions HW3.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
"use strict";

//функция для ошибки
//если есть элемент ошибки то идем дальше, если его нет то мы создаем его задавая имя номер (для расположения) и текст

function createError(num, name, text) {
const errorExisit = document.getElementById(name);
if (!errorExisit) {
const allert = document.createElement('div'); // создаем элемент
document.querySelectorAll('.form-group')[num].appendChild(allert); // добавляем в документ
allert.id = name; // задаем id (необходим для последующего удаления)
allert.innerHTML = text; // записываем тест
allert.style.fontSize = '10px'; //задаем внешний вид
allert.style.color = 'red';
}
}

//функция для удаления элемента (ошибки)

function deleteElement(name) {
const del = document.getElementById(name); //создаем элемент по id
if (del) { //если он создался
del.remove(); // удаляем
}
}

//проверка имени

function checkName() {
const name = document.querySelector('.form-control'); // создаем элемент
if (name.value.length < 1 || name.value.length > 50) { // проверяем
createError('0', 'nameAllert', 'Имя должно содержать как минимум 1 символ, не более 50 символов');
// создаем ошибку если проверка не прошла
name.style.border = '1px solid red'; // задаем стиль
return false; //возвращаем ошибку
} else { // если проверка пройдена
name.style.border = '1px solid green'; //задаем стиль
deleteElement('nameAllert'); // удаляем ошибку
return true;
}
}

//все остальные функции по аналогии с checkName

function checkPhone() {
const phone = document.querySelectorAll('.form-control')[1];
if (phone.value.length !== 11 || isNaN(phone.value / 0)) {
createError('1', 'phoneAllert', 'Телефон должен содержать 11 цифр');
phone.style.border = '1px solid red';
return false;
} else {
phone.style.border = '1px solid green';
deleteElement('phoneAllert');
return true;
}
}

function checkPassword() {
const password = document.querySelectorAll('.form-control')[2];
if (password.value.length < 5) {
createError('2', 'passwordAllert', 'Пароль должно содержать как минимум 5 символов');
password.style.border = '1px solid red';
return false;
} else {
password.style.border = '1px solid green';
deleteElement('passwordAllert');
return true;
}
}

function confirmPassword() {
const password = document.querySelectorAll('.form-control')[2];
const passwordRepeat = document.querySelectorAll('.form-control')[3];
if (passwordRepeat.value !== password.value) {
createError('3', 'passwordRepeatAllert', 'Пароль не совпадает');
passwordRepeat.style.border = '1px solid red';
return false;
} else {
passwordRepeat.style.border = '1px solid green';
deleteElement('passwordRepeatAllert');
return true;
}
}

//проверяем

const validation = document.querySelector('form'); //задаем переменную для валидации по тегу form
validation.addEventListener('submit', function (event) {
const password = !checkPassword(); //дадаем пременной значение отрицательное выдаваемому функцией
const phone = !checkPhone();//дадаем пременной значение отрицательное выдаваемому функцией
const name = !checkName();//дадаем пременной значение отрицательное выдаваемому функцией
const confirm = !confirmPassword();//дадаем пременной значение отрицательное выдаваемому функцией
if (name || confirm || password || phone) { //проверяем по переменным выпадение ошибок
event.preventDefault(); // если ошибки есть то останавливаем
}
});