WBE_Miniprojekt/code/connect4.html

132 lines
2.8 KiB
HTML
Raw Normal View History

2022-12-21 20:45:47 +01:00
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vier gewinnt</title>
<style>
div {
box-sizing: border-box;
}
.board {
width: 84vw;
margin: auto;
outline: 1px solid black;
}
.board .field {
border: 1px solid black;
width: 12vw;
height: 12vw;
float: left;
}
.board .field:first-child {
display: block;
}
.board .field .piece {
width: 10vw;
height: 10vw;
border-radius: 50%;
margin: 1vw;
}
.board .field .blue {
background-color: blue;
}
.board .field .red {
background-color: red;
}
</style>
<script src="render-sjdon.js"></script>
</head>
<body>
<button class="boardclearbutton" style="margin: 10px;">Neues Spiel</button>
<p>Spieler <a id="actualPlayer"></a> ist am Zug.</p>
<div class="board"></div>
<script>
function showBoard() {
let board = document.querySelector(".board")
board.innerHTML = ''
let element = new Array()
for(row = 0; row < rows; row++) {
for(column = 0; column < columns; column++) {
let attributes = {"id": column.toString() + ":" + row.toString(), "class": "field"}
let children = ["div", {"class": state[row][column] + " piece"}]
element.append("div", attributes, children)
}
}
//renderSJDON(element, board)
}
function clearBoard() {
state = Array(rows).fill('').map(el => Array(columns).fill(''))
switchNextColor()
showBoard();
}
function switchNextColor() {
if(state.nextColor === "red") {
state.nextColor = "blue"
document.getElementById("actualPlayer").innerHTML = "blau"
} else {
state.nextColor = "red"
document.getElementById("actualPlayer").innerHTML = "rot"
}
}
function setField(row, column) {
state[row][column] = state.nextColor
switchNextColor()
showBoard()
}
function setColumn(column) {
let row = rows - 1
const column_number = column
while(row >= 0){
if(state[row][column_number] !== ''){
row--
} else {
setField(row, column_number)
break
}
}
}
const columns = 7
const rows = 6
let state = {}
clearBoard()
const boardClearButton = document.querySelector(".boardclearbutton")
boardClearButton.addEventListener("click", event => {
clearBoard()
})
showBoard()
document.querySelector(".board").addEventListener("click", event => {
let element = event.target
if(element.classList.contains("piece")){
element = element.parentElement
}
let column = Number(element.id.split(":")[0])
setColumn(column)
})
</script>
</body>
</html>