i have made a tic-tac-toe game.For which i have to make a character selection module for each player.Players have to choose between x and o.If first one selects 'o' ,other player can not select that.he has to choose 'x'.But including html lines ,the code i have written is almost 50 lines and very fragile, i can't find any other way to shorten this code.selection option is a basic thing in games.Any expert solution on this matter would be appreciated
function Player(name,val){
this.name=name;
this.val=val;
}
var ps=document.getElementById('ps');
ps.addEventListener('click',function(e){
player1=prompt('input player1');
char1=prompt('input char between x/o');
if((char1 != 'x') && (char1 != 'o')){
for(;;){
alert('select between x an o please');
char1=prompt('between x/o');
if((char1 === 'x')|| (char1 === 'o')){
break;
}
}
}
player2 = prompt('input player2');
char2 = prompt('input your char O/X');
if((char2 === char1) || ((char2 != 'x') && (char2 != 'o'))){
for(;;){
alert('you can not have this char');
char2=prompt('try again');
if(((char2 === 'o') || (char2 === 'x')) && (char2 != char1)){
break;
}
}
}
p1=new Player(player1,char1);
p2=new Player(player2,char2);
document.body.innerHTML+='\n'+p1.name+' : '+p1.val+'\n'+p2.name+' : '+p2.val;
});
<input type='button' value='Player Setup' id='ps'>
Instead of using
prompt
, its better to make use of HTML<input>
elements.Demo on Fiddle
HTML:
JavaScript:
CSS: