Javascript.RU

Создать новую тему Ответ
 
Опции темы Искать в теме
  #11 (permalink)  
Старый 16.01.2017, 14:24
Аватар для ksa
ksa ksa на форуме
CacheVar
Отправить личное сообщение для ksa Посмотреть профиль Найти все сообщения от ksa
 
Регистрация: 19.08.2010
Сообщений: 14,118

Сообщение от Dilettante_Pro
А вот этот - нерабочий...
Так там дело опять не в window.onload...
Ты просто не правильно определяешь, нужный тебе, элемент страницы...
Ответить с цитированием
  #12 (permalink)  
Старый 16.01.2017, 17:09
Интересующийся
Отправить личное сообщение для strange.tany Посмотреть профиль Найти все сообщения от strange.tany
 
Регистрация: 15.01.2017
Сообщений: 16

ksa,
черт, косяки идут из-за того что я пытаюсь сократить программу. window.onload не работает в этой программе(может ли это быть вызвано размером программы) :
<!doctype html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<title>Battleship</title>
	<style>
		body {
			background-color: black;
		}
		div#board {
			position: relative;
			width: 751px;
			height: 740px;
			margin: auto;
			background: url("board.gif") no-repeat;
		}
		div#messageArea {
			position: absolute;
			top: 0px;
			left: 0px;
			color: rgb(190, 241, 29);
			font-size: 2em;
		}
		div#sankInformation {
			position: absolute;
			bottom: 0px;
			right: 0px;
			color: rgb(190, 241, 29);
			font-size: 2em;
		}
		.hit {
			background: url("ship.png") no-repeat center center;
		}
		.miss {
			background: url("miss.png") no-repeat center center;
		}
		table {
			position: absolute;
			left: 81px;
			top: 55px;
		}
		td {
			width: 55px;
			height: 54.95px;
		}
		form {
			position: absolute;
			bottom: 0px;
			left: 0px;
			padding: 15px;
			background-color: rgb(83, 175, 19);
		}
		form input {
			background-color: rgb(152, 207, 113);
			border-color: rgb(83, 175, 19);
			font-size: 1em;
		}
		img#next{
			position: absolute;
			right: 0px;
			bottom: 362px;
			}
	</style>
	<script>
		window.onload = function() {
		alert("функция запустилась");
			var next = document.getElementById("next");	
				next.onclick = newStyle;
		};
			function newStyle() {
				this.src = "button2.png";
		};
	</script>
	</head>
	<body>
		<div id="board">
		<div id="messageArea"></div>
		<table>
			<tr>
				<td id="00"></td> <td id="01"></td> <td id="02"></td> <td id="03"></td>
				<td id="04"></td> <td id="05"></td> <td id="06"></td> <td id="07"></td>
				<td id="08"></td> <td id="09"></td>
			</tr>
			<tr>
				<td id="10"></td> <td id="11"></td> <td id="12"></td> <td id="13"></td>
				<td id="14"></td> <td id="15"></td> <td id="16"></td> <td id="17"></td>
				<td id="18"></td> <td id="19"></td>
			</tr>
			<tr>
				<td id="20"></td> <td id="21"></td> <td id="22"></td> <td id="23"></td>
				<td id="24"></td> <td id="25"></td> <td id="26"></td> <td id="27"></td>
				<td id="28"></td> <td id="29"></td>
			</tr>
			<tr>
				<td id="30"></td> <td id="31"></td> <td id="32"></td> <td id="33"></td>
				<td id="34"></td> <td id="35"></td> <td id="36"></td> <td id="37"></td>
				<td id="38"></td> <td id="39"></td>
			</tr>
			<tr>
				<td id="40"></td> <td id="41"></td> <td id="42"></td> <td id="43"></td>
				<td id="44"></td> <td id="45"></td> <td id="46"></td> <td id="47"></td>
				<td id="48"></td> <td id="49"></td>
			</tr>
			<tr>
				<td id="50"></td> <td id="51"></td> <td id="52"></td> <td id="53"></td>
				<td id="54"></td> <td id="55"></td> <td id="56"></td> <td id="57"></td>
				<td id="58"></td> <td id="59"></td>
			</tr>
			<tr>
				<td id="60"></td> <td id="61"></td> <td id="62"></td> <td id="63"></td>
				<td id="64"></td> <td id="65"></td> <td id="66"></td> <td id="67"></td>
				<td id="68"></td> <td id="69"></td>
			</tr>
			<tr>
				<td id="70"></td> <td id="71"></td> <td id="72"></td> <td id="73"></td>
				<td id="74"></td> <td id="75"></td> <td id="76"></td> <td id="77"></td>
				<td id="78"></td> <td id="79"></td>
			</tr>
			<tr>
				<td id="80"></td> <td id="81"></td> <td id="82"></td> <td id="83"></td>
				<td id="84"></td> <td id="85"></td> <td id="86"></td> <td id="87"></td>
				<td id="88"></td> <td id="89"></td>
			</tr>
			<tr>
				<td id="90"></td> <td id="91"></td> <td id="92"></td> <td id="93"></td>
				<td id="94"></td> <td id="95"></td> <td id="96"></td> <td id="97"></td>
				<td id="98"></td> <td id="99"></td>
			</tr>
		</table>
		<form>
			<input type="text" id="guessInput" placeholder="A0">
			<input type="button" id="fireButton" value="Fire!">
		</form>
		<div id="sankInformation"></div>
		<img id="next" src="button.png">
		</div>
			<script src="battleship.js"></script>
	</body>
</html>

Последний раз редактировалось strange.tany, 16.01.2017 в 17:37.
Ответить с цитированием
  #13 (permalink)  
Старый 16.01.2017, 17:58
Профессор
Отправить личное сообщение для Dilettante_Pro Посмотреть профиль Найти все сообщения от Dilettante_Pro
 
Регистрация: 27.11.2015
Сообщений: 2,899

strange.tany,
Работает... Нажмите на картинку с красной стрелочкой.
Единственное изменение - закомментировал загрузку скрипта <script src="battleship.js"></script>
Может, там что не так
<!doctype html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<title>Battleship</title>
	<style>
		body {
			background-color: black;
		}
		div#board {
			position: relative;
			width: 751px;
			height: 740px;
			margin: auto;
			background: url("http://javascript.ru/cat/list/dom.gif") no-repeat;
		}
		div#messageArea {
			position: absolute;
			top: 0px;
			left: 0px;
			color: rgb(190, 241, 29);
			font-size: 2em;
		}
		div#sankInformation {
			position: absolute;
			bottom: 0px;
			right: 0px;
			color: rgb(190, 241, 29);
			font-size: 2em;
		}
		.hit {
			background: url("http://javascript.ru/cat/list/libs.jpg") no-repeat center center;
		}
		.miss {
			background: url("http://javascript.ru/cat/list/mobile.jpg") no-repeat center center;
		}
		table {
			position: absolute;
			left: 81px;
			top: 55px;
		}
		td {
			width: 55px;
			height: 54.95px;
		}
		form {
			position: absolute;
			bottom: 0px;
			left: 0px;
			padding: 15px;
			background-color: rgb(83, 175, 19);
		}
		form input {
			background-color: rgb(152, 207, 113);
			border-color: rgb(83, 175, 19);
			font-size: 1em;
		}
		img#next{
			position: absolute;
			right: 0px;
			bottom: 362px;
			}
	</style>
	<script>
		window.onload = function() {
		alert("функция запустилась");
			var next = document.getElementById("next");	
				next.onclick = newStyle;
		};
			function newStyle() {
				this.src = "http://javascript.ru/cat/list/donkey.gif";
		};
	</script>
	</head>
	<body>
		<div id="board">
		<div id="messageArea"></div>
		<table>
			<tr>
				<td id="00"></td> <td id="01"></td> <td id="02"></td> <td id="03"></td>
				<td id="04"></td> <td id="05"></td> <td id="06"></td> <td id="07"></td>
				<td id="08"></td> <td id="09"></td>
			</tr>
			<tr>
				<td id="10"></td> <td id="11"></td> <td id="12"></td> <td id="13"></td>
				<td id="14"></td> <td id="15"></td> <td id="16"></td> <td id="17"></td>
				<td id="18"></td> <td id="19"></td>
			</tr>
			<tr>
				<td id="20"></td> <td id="21"></td> <td id="22"></td> <td id="23"></td>
				<td id="24"></td> <td id="25"></td> <td id="26"></td> <td id="27"></td>
				<td id="28"></td> <td id="29"></td>
			</tr>
			<tr>
				<td id="30"></td> <td id="31"></td> <td id="32"></td> <td id="33"></td>
				<td id="34"></td> <td id="35"></td> <td id="36"></td> <td id="37"></td>
				<td id="38"></td> <td id="39"></td>
			</tr>
			<tr>
				<td id="40"></td> <td id="41"></td> <td id="42"></td> <td id="43"></td>
				<td id="44"></td> <td id="45"></td> <td id="46"></td> <td id="47"></td>
				<td id="48"></td> <td id="49"></td>
			</tr>
			<tr>
				<td id="50"></td> <td id="51"></td> <td id="52"></td> <td id="53"></td>
				<td id="54"></td> <td id="55"></td> <td id="56"></td> <td id="57"></td>
				<td id="58"></td> <td id="59"></td>
			</tr>
			<tr>
				<td id="60"></td> <td id="61"></td> <td id="62"></td> <td id="63"></td>
				<td id="64"></td> <td id="65"></td> <td id="66"></td> <td id="67"></td>
				<td id="68"></td> <td id="69"></td>
			</tr>
			<tr>
				<td id="70"></td> <td id="71"></td> <td id="72"></td> <td id="73"></td>
				<td id="74"></td> <td id="75"></td> <td id="76"></td> <td id="77"></td>
				<td id="78"></td> <td id="79"></td>
			</tr>
			<tr>
				<td id="80"></td> <td id="81"></td> <td id="82"></td> <td id="83"></td>
				<td id="84"></td> <td id="85"></td> <td id="86"></td> <td id="87"></td>
				<td id="88"></td> <td id="89"></td>
			</tr>
			<tr>
				<td id="90"></td> <td id="91"></td> <td id="92"></td> <td id="93"></td>
				<td id="94"></td> <td id="95"></td> <td id="96"></td> <td id="97"></td>
				<td id="98"></td> <td id="99"></td>
			</tr>
		</table>
		<form>
			<input type="text" id="guessInput" placeholder="A0">
			<input type="button" id="fireButton" value="Fire!">
		</form>
		<div id="sankInformation"></div>
		<img id="next" src="http://javascript.ru/cat/list/event.gif">
		</div>
		/*	<script src="battleship.js"></script> */
	</body>
</html>
Ответить с цитированием
  #14 (permalink)  
Старый 16.01.2017, 18:03
Интересующийся
Отправить личное сообщение для strange.tany Посмотреть профиль Найти все сообщения от strange.tany
 
Регистрация: 15.01.2017
Сообщений: 16

Сообщение от Dilettante_Pro
закомментировал загрузку скрипта <script src="battleship.js"></script>
проблема в том, что там находится основной код программы и что-то в нем конфликтует с window.onload, что это может быть?
battleship.js:
var model = {
	boardSize: 10,//размер поля
	numShips: 10,//количество кораблей
	shipLength: [1, 2, 3, 4],//длина каждого из 4 кораблей
	shipsSunk: 0,//потоплено кораблей
	ships:[ {locations: [0], hits: [""]},//0
			{locations: [0], hits: [""]},//1
			{locations: [0], hits: [""]},//2
			{locations: [0], hits: [""]},//3
			{locations: [0, 0], hits: ["", ""]},//4
			{locations: [0, 0], hits: ["", ""]},//5
			{locations: [0, 0], hits: ["", ""]},//6
			{locations: [0, 0, 0], hits: ["", "", ""]},//7
			{locations: [0, 0, 0], hits: ["", "", ""]},//8
			{locations: [0, 0, 0, 0], hits: ["", "", "", ""]}],//9
	generateShipLocations: function() {
		var locations;
		for(var i = 0; i < this.numShips; i++) {
			do {
				if (i < 4) {
					locations = this.generateShip1();//генрируются корабли на одну клетку
				} else if (i > 3 && i < 7) {
					locations = this.generateShip2(2);//на две
				} else if (i > 6 && i < 9) {
					locations = this.generateShip2(3);//на три
				} else {
					locations = this.generateShip2(4);//на четыре
				}
			} while (this.collision(locations)||this.around(locations));//проверка на наезды
			this.ships[i].locations = locations;//установление позиции
			console.log(this.ships[i].locations);
		}
	},
	generateShip1: function() {
		var row, col;
			row = Math.floor(Math.random() * this.boardSize);//горизонталь
			col = Math.floor(Math.random() * this.boardSize);//вертикаль
		var newShipLocations = [];
		newShipLocations.push(row + "" + col);
		return newShipLocations;
	},
	generateShip2: function(l) {
		var direction = Math.floor(Math.random() * 2);//установления положения
		var row, col;
		if (direction === 1) {
			row = Math.floor(Math.random() * this.boardSize);
			col = Math.floor(Math.random() * (this.boardSize-this.shipLength[l-1]));//горизантально
		} else {
			row = Math.floor(Math.random() * (this.boardSize-this.shipLength[l-1]));
			col = Math.floor(Math.random() * this.boardSize);//вертикально
		}
		var newShipLocations = [];
		for (var i = 0; i<this.shipLength[l-1]; i++) {
			if (direction === 1) {
				newShipLocations.push(row + "" + (col + i));
			} else  {
				newShipLocations.push((row + i) + "" + col);
			}
		}
		return newShipLocations;
	},
	around: function(locations) {
		var round = [-11, -10, -9, -1, 1, 9, 10, 11];
		for (var i = 0; i < this.numShips; i++) {
			var ship = model.ships[i];//пребирание разных кораблей
			for (var j = 0; j < locations.length; j++) {
				for (var h = 0; h < round.length; h++) {
					if (ship.locations.indexOf(String(Number(locations[j]) + round[h])) >= 0) {//проверка присутствия заданых координат
						return true;
					}
				}
			}
		}
		return false;
	},
	collision: function(locations) {//массив позиций для нового коробля
		for (var i = 0; i < this.numShips; i++) {
			var ship = model.ships[i];//пребирание разных кораблей
			for (var j = 0; j < locations.length; j++) {
				if (ship.locations.indexOf(locations[j]) >= 0) {//проверка присутствия заданых координат
					return true;
				} 
			}
		}
		return false;
	},
	fire: function(guess) {//метод получает координаты выстрела
		for (var i=0; i<this.numShips; i++) {//перебор массива ships 
			var ship = this.ships[i];// получение объекта ships 
			var index = ship.locations.indexOf(guess);// в массиве locations идет поиск координат, а метод indexOf возвращает его индекс или -1
			if (index >= 0) {//если координаты есть в массиве
				ship.hits[index] = "hit";//по тому же индексу в массиве hits ставится отметка
				view.displayHit(guess);//вывод коробля на введенных координатах
				view.displayMessage("HIT!");//вывод сообщения о попадании
				if (this.isSunk(ship, this.ships[i].locations.length)) {//когда произошло попадание, идет проверка на потопление
					view.displayMessage("You sank my battleship!");//вывод сообщения о потоплении
					this.shipsSunk++;//если потоплен, то в свойство прибавляется 1
					view.displaySank("Ships sank: " + this.shipsSunk);
				}
				return true;//попал
			}
		}
		view.displayMiss(guess);//вывод miss на введенных координатах
		view.displayMessage("You missed");//вывод сообщения о поподании
		return false;//мимо
	},
	isSunk: function(ship, l) {//получение объекта коробля 
		for (var i=0; i<this.shipLength[l-1]; i++) {
			if (ship.hits[i] !== "hit") {//проверяет, что все клетки помечены маркером поподания
				return false;//если нет, то корабль жив
			}
		}
		return true;//корабль потоплен
	}
};
var controller = {
	guesses: 0,
	processGuess: function(guess) {
		var location = parseGuess(guess);
		if(location && alreadyHit(location)) {
			this.guesses++;
			var hit = model.fire(location);
			if (hit && model.shipsSunk === model.numShips) {
				view.displayMessage("You sank all my battleships, in " + this.guesses + " guesses");
				
			}
		}
	}
};
var view = {
	displayMessage: function(msg) {// функция получает сообщение, которое нужно отобразить
		var messageArea = document.getElementById("messageArea");//получаем элемент по id 
		messageArea.innerHTML = msg; //обновление текста
	},
	displayHit: function(location) {
		var cell = document.getElementById(location);// получаем элемент по определенным координатам
		cell.setAttribute("class", "hit");//присваивание класса
	},
	displayMiss: function(location) {
		var cell = document.getElementById(location);
		cell.setAttribute("class", "miss");
	},
	displaySank: function(msg) {
		var sankInformation = document.getElementById("sankInformation");
		sankInformation.innerHTML = msg;
	} 
};
var nowStyle = 1; 
function parseGuess (guess) {
	var alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"];// алфавит
	if (guess===null || guess.length !==2) { //если координаты null ИЛИ больше двух знаков..
		alert("Oops, please enter a letter and a number of the board.");//..выводится сообщение
	} else {
		firstChar = guess.charAt(0);//перменной присваивается первый знак координат
		var row = alphabet.indexOf(firstChar);//перменной присваивается индекс первого знака координат
		var column = guess.charAt(1);//перменной присваивается второй знак координат
		if (isNaN(row)|| isNaN(column)) {//если это не число
			alert("Oops,that isn't on the board.");	//выводится сообщение об ошибке
		} else if (row<0 || row>=model.boardSize || column < 0 || column >= model.boardSize) {//если больше или меньше размеров..
			alert ("Oops, that's off the board!");//..выводится сообщение об ошибке
		} else {
			return row + column;//если все ок, то возвращаются координаты
		}
	}
	return null;
}
function alreadyHit (guess) {
	for (var i=0; i < model.numShips; i++) {//перебор массива ships 
		var ship = model.ships[i];// получение объекта ships 
		var index = ship.locations.indexOf(guess);// в массиве locations идет поиск координат, а метод indexOf возвращает его индекс или -1
		if (index >= 0 && ship.hits[index] == "hit") {//есть координаты И есть отметка hit
			alert("You've already hit here! Try again");
			return null;
		} else {
			return true;
		}
	}
}
function handleKeyPress (e) {
	var fireButton = document.getElementById ("fireButton");
	if (e.keyCode===13) {
		fireButton.click();
		return false;
	}
}
function init() {
	var fireButton = document.getElementById("fireButton");
	fireButton.onclick = handleFireButton;
	var guessInput = document.getElementById("guessInput");
	guessInput.onkeypress = handleKeyPress;
	model.generateShipLocations();
}
function handleFireButton() {
	var guessInput = document.getElementById("guessInput");
	var guess = guessInput.value;
	controller.processGuess(guess);
	guessInput.value = "";
}
window.onload = init;
for (var i = 0; i<model.boardSize; i++) {
	for (var j = 0; j<model.broadSize; j++){
		controller.processGuess(i + "" + j);
	}
}

Последний раз редактировалось strange.tany, 16.01.2017 в 18:10.
Ответить с цитированием
  #15 (permalink)  
Старый 16.01.2017, 18:15
Интересующийся
Отправить личное сообщение для strange.tany Посмотреть профиль Найти все сообщения от strange.tany
 
Регистрация: 15.01.2017
Сообщений: 16

я кажется поняла. конфликтуют два window.onload, так ведь?
Ответить с цитированием
  #16 (permalink)  
Старый 16.01.2017, 18:36
Профессор
Отправить личное сообщение для Dilettante_Pro Посмотреть профиль Найти все сообщения от Dilettante_Pro
 
Регистрация: 27.11.2015
Сообщений: 2,899

strange.tany,
Сообщение от strange.tany
я кажется поняла. конфликтуют два window.onload, так ведь?
Да, перенесите строки 67,68,70,71,72 (по моему примеру) в функцию init
и удалите строки 64-75 (по моему примеру)
PS: в демо, к сожалению, не вмещается

Последний раз редактировалось Dilettante_Pro, 16.01.2017 в 18:39.
Ответить с цитированием
  #17 (permalink)  
Старый 16.01.2017, 20:00
Интересующийся
Отправить личное сообщение для strange.tany Посмотреть профиль Найти все сообщения от strange.tany
 
Регистрация: 15.01.2017
Сообщений: 16

Dilettante_Pro, такой вариант записи возможен?
window.onload = function() {
	changeStyle();
	init();
};
Ответить с цитированием
  #18 (permalink)  
Старый 16.01.2017, 20:50
Профессор
Отправить личное сообщение для Dilettante_Pro Посмотреть профиль Найти все сообщения от Dilettante_Pro
 
Регистрация: 27.11.2015
Сообщений: 2,899

strange.tany,
Попробуйте
Ответить с цитированием
  #19 (permalink)  
Старый 17.01.2017, 09:09
Аватар для ksa
ksa ksa на форуме
CacheVar
Отправить личное сообщение для ksa Посмотреть профиль Найти все сообщения от ksa
 
Регистрация: 19.08.2010
Сообщений: 14,118

Сообщение от strange.tany
конфликтуют два window.onload, так ведь?
Если назначать обработчики как ты это делаешь
Сообщение от strange.tany Посмотреть сообщение
window.onload = function() {
	changeStyle();
	init();
};
То в итоге будет выполняться последний присвоенный обработчик.
Но теперь есть и другие варианты "навешивания" обработчиков.
https://learn.javascript.ru/introduction-browser-events
Ответить с цитированием
Ответ



Опции темы Искать в теме
Искать в теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
JS: работает на сервере, не работает из папки -majestic- Общие вопросы Javascript 2 02.08.2012 14:41
Не работает push! Динамическая вставка TSEH25 ExtJS 5 03.07.2012 13:00
jQyery функция странно работает! Midel Общие вопросы Javascript 4 08.04.2012 13:40
помогите найти ошибку (работает в IE но не работает в Firefox) Len4ik Javascript под браузер 2 11.05.2010 15:41
ajax запросы, работает на одних компах и не работает на других vtornik23 AJAX и COMET 2 22.03.2010 18:22