Hab mal wieder bisschen gecodet, aber das ist ein fehler drin^^
Soll so ne Art Snake werden. Is nich sonderlich schön gecodet, wolltes einfach mal zum laufen bringen:
place_food funzt nicht, Firefox meint mover_con wär null.
JavaScript
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" xml:lang="de">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<style type="text/css">
*
{
border:0px;
margin:0px;
padding:0px;
}
#mover
{
position:absolute;
height:20px;
width:20px;
}
#mover_con
{
height:400px;
width:400px;
background-image: url(background.png);
}
</style>
<script type="text/javascript">
left = true;
top = true;
bottom = true;
right = true;
document.onkeydown = key_press;
function rand (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function init (){
mover = document.getElementById("mover");
mover.style.left = "100px";
mover.style.top = "40px";
}
function key_press(events)
{
if(!events){
events = window.event;
}
if(events.which){
key(events.which);
}
else if(events.keyCode){
key(events.keyCode);
}
}
function key(code)
{
if(code==37 && left){
move("left");
}
if(code==38 && top){
move("top");
}
if(code==39 && right){
move("right");
}
if(code==40 && bottom){
move("bottom");
}
}
function move(where)
{
mover = document.getElementById("mover");
if(where == "left"){
mover_left = mover.style.left;
dummy = mover_left.split("px");
left = dummy[0]-10;
if(left>= "0"){
mover.style.left = left+"px";
} else {
mover.style.left = mover.style.left;
}
}
if(where == "right"){
mover_left = mover.style.left;
dummy = mover_left.split("px");
dummy[0] = parseInt(dummy[0]);
left = (dummy[0]+10);
if(left<= "380"){
mover.style.left = left+"px";
} else {
mover.style.left = mover.style.left;
}
}
if(where == "top"){
mover_top = mover.style.top;
dummy = mover_top.split("px");
top = dummy[0]-10;
if(top>= "0"){
mover.style.top = top+"px";
} else {
mover.style.top = mover.style.top;
}
}
if(where == "bottom"){
mover_top = mover.style.top;
dummy = mover_top.split("px");
dummy[0] = parseInt(dummy[0]);
top = (dummy[0]+10);
if(top<= "380"){
mover.style.top = top+"px";
} else {
mover.style.top = mover.style.top;
}
}
}
function place_food(){
food = document.createElement("img");
food.src = "mover.png";
food.style.position = "absolute";
top = rand(0, 400)+"px";
left = rand(0, 400)+"px";
food.style.top = top;
food.style.left = left;
mover_con = document.getElementById("mover_con");
mover_con.appendChild(food);
}
place_food();
</script>
</head>
<body onload="init()">
<div id="mover_con">
<img src="mover.png" id="mover" />
</div>
</body>
</html>
Alles anzeigen
Achja, hier zum ausprobieren. xD