Switching players every two turns in a JavaScript AngularJS game

I have implemented an AngularJS score keeping game where players switch every two turns. The code works for one round, but I want to create a loop that keeps switching players. Check out my code below:

app.controller('EventController', function($scope){

$scope.score1 = 0;
$scope.score2 = 0;
$scope.playing = true;
$scope.win1 = false;
$scope.lose1 = false;
$scope.win2 = false;
$scope.lose2 = false;

//Counter
$scope.counter = 0;
$scope.totalScore = $scope.score1 + $scope.score2;

$scope.player1 = " Player 1";
$scope.player2 = " Player 2";

$scope.currentplayer = $scope.player1;



    $scope.switchplayer = function(){

        if ($scope.counter % 2 === 0){

            if($scope.totalScore % 2 === 0){
                $scope.currentplayer = $scope.player2;
            } else {
                $scope.currentplayer = $scope.player1;
            }

    }};



  $scope.incrementScore1 = function() {

    $scope.score1++;
    $scope.counter++;

    if ($scope.score1 === 11){

        $scope.playing = false;
        $scope.win1 = true;
        $scope.lose2 = true;
        console.log('Player 1 wins!');
    }
  };

  $scope.incrementScore2 = function() {

    $scope.score2++;
     $scope.counter++;
    if ($scope.score2 == 11){
        $scope.playing = false;
        $scope.win2 = true;
        $scope.lose1 = true;
        console.log('Player 2 wins!');
    }
  };

$scope.reset = function(){
    $scope.score1='0';
    $scope.score2='0';
    $scope.playing = true;
    $scope.win1 = false;
    $scope.lose1 = false;
    $scope.win2 = false;
    $scope.lose2 = false;
};


});

<div class="container" ng-controller='EventController'>
    <h1>Score Keeper</h1>
    <h3>Current Serve:<span>{{currentplayer}}</span></h3>
    <div class="row" ng-class="{'current': playing}">


        <div class="col-md-6" ng-click='incrementScore1();switchplayer()' ng-model='score1' ng-class="{'win1': win1, 'lose1': lose1}">
            <p>{{score1}}</p><br><br><br>
        </div>


        <div class="col-md-6" ng-model='score2' ng-click='incrementScore2();switchplayer()' ng-class="{'win2': win2, 'lose2': lose2}">
        <p>{{score2}}</p><br><br><br>
    </div>
</div>
<button ng-click='reset()'>Reset</button>
</div>

Answer №1

Your totalScore variable remains static in your code, causing the calculation involving it to be inaccurate (it will always result in 0). Instead, switch players based on the current player in order to resolve this issue.

$scope.switchplayer = function(){

    if ($scope.counter % 2 === 0){
        $scope.currentplayer = $scope.currentplayer === $scope.player2
            ? $scope.player1
            : $scope.player2;

}};

Also make sure to reset the counter within your reset function to avoid inadvertently changing players every odd turn.

$scope.counter = 0;

Answer №2

When dealing with the modulo operator % 4:

    $scope.switchplayer = function(){
        if($scope.totalScore % 4 >= 2){
            $scope.currentplayer = $scope.player2;
        } else {
            $scope.currentplayer = $scope.player1;
        }
    };

This means that player1 will be the current player when the remainder is 0 or 1, and player2 will be the current player when the remainder is 2 or 3. The cycle repeats every 4 iterations.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Effortlessly Display or Conceal Numerous Table Columns Using jQuery

I have a small table where I want to hide certain details with a basic button... for instance, table { border-collapse: collapse; } th, td { border: 1px solid gray; padding: 5px 10px; } <button>Show/Hide Details</button> <table> ...

I am having issues with sendKeys and click() functions in my code. I am unable to access the elements using Protractor's javascript

<input class="form-control validation-field ng-dirty ng-touched ng-invalid" placeholder="Password" type="password"> Despite using the element to retrieve it, I am unable to send keys and no error message is displayed. This issue persists in both Fir ...

Vue not triggering computed property sets

As per the guidelines, I should be able to utilize computed properties as v-model in Vue by defining get/set methods. However, in my scenario, it isn't functioning as expected: export default{ template: ` <form class="add-upload&quo ...

Adding npm packages to your Vue.js application

My Vue app is structured like this (auto created by vue init webpack myProject): index.html components/ -main.js -App.vue I am trying to include npm packages, such as https://github.com/ACollectionOfAtoms/atomic-bohr-model. Following the instructions, I ...

Navigating race conditions within Node.js++]= can be challenging, but there are strategies

In the process of developing a MERN full stack application, I encountered a scenario where the frontend initiates an api call to "/createDeckOfCards" on my NodeJS backend. The main objective is to generate a new deck of cards upon clicking a button and the ...

Issue with JQuery UI Tabs not displaying additional HTML pages in JavaScript

One issue I'm facing is that I added Tabs from JQuery UI on my website. The tab containing paragraphs loads fine, but the tabs linked to other HTML pages (which don't have tabs) won't load. Here is my .js file code and .html code: $(funct ...

Is there a discrepancy in speed between Node.js http.get and Google Chrome's $.get function?

Recently, while experimenting with node.js, I decided to test out the following code snippet: var http = require("http"); function get() { var headers = { 'Accept-Encoding': 'gzip' }; var startedAt = new Date().get ...

Pause until the existence of document.body is confirmed

Recently, I developed a Chrome extension that runs before the page fully loads by setting the attribute "run_at": "document_start". One issue I encountered is that I need to insert a div tag into the body of the webpage as soon as it is created. However, a ...

Tips for eliminating fade effect during hover in networkD3 chart in R

Currently, I have been exploring the usage examples of networkd3 in r I am curious if there is a way to eliminate the hover effect where everything else fades when hovering over a specific node in the graph. For reference, check out "Interacting with igra ...

Dealing with the state of an array of checkboxes: What you need to know

Is there a way to individually control the checked state of an array of checkboxes? Here is the array in question: const CheckboxItems = t => [ { checked: true, value: 'itemsCancelled', id: 'checkBoxItemsCancelled', ...

The command npm install -g . fails to copy the package

The guidelines from npm's developer documentation suggest ensuring that your package can be installed globally before publishing by executing the command npm install -g .. I am currently working on developing an ES6 Command Line Interface (CLI) packag ...

The onclick event in JavaScript is unresponsive on mobile devices

Our website is powered by Opencart 1.5.6.4 and the code snippet below is used to add items to the shopping cart. <input type="button" value="<?php echo $button_cart; ?>" onclick="addToCart('<?php echo $product['product_id']; ?&g ...

Trouble encountered when trying to use an anchor link with the .slideUp jQuery function

Would you be able to assist me with understanding why my anchor links are not functioning correctly? I have 3 anchor links, for example: Google (not working) Yahoo (not working) Facebook (working) Any insights on why Google and Yahoo are not working? &l ...

Error Encountered in Request Header of WordPress JSON API

Utilizing the WordPress JSON API plugin has allowed me to effectively retrieve posts and other content from my blog. However, an issue arises when attempting to access the data from my Ionic application. The following error occurs: Request header field A ...

Mapping a bar chart on a global scale

Are there any methods available to create bar charts on a world map? The world map could be depicted in a 3D view resembling a Globe or in a 2D format. It should also have the capability to zoom in at street level. Does anyone have suggestions or examples ...

What is the best way to execute my mocha fixtures with TypeScript?

I am seeking a cleaner way to close my server connection after each test using ExpressJS, TypeScript, and Mocha. While I know I can manually add the server closing code in each test file like this: this.afterAll(function () { server.close(); ...

Can you explain the concept of asynchronous in the context of Ajax?

Can you explain the concept of Asynchronous in Ajax? Additionally, how does Ajax determine when to retrieve data without constantly polling the server? ...

Troubleshooting Issues with jQuery Accordion Buttons

I have a nearly complete accordion that just needs some adjustments. HTML CODE: <footer> <div> <h1>Hide</h1> <h1>Hide</h1> <h1>Hide</h1> <h1>Hide</h1> ...

What causes Node.js to be unable to handle requests from Vue.js?

I'm encountering a strange error where Node.js is unable to see the URL address and consistently returns a 404 error. In my Vue.js application, I am making a post request using the axios package when the user clicks a button. The code snippet shows t ...

Utilize an object model property as an array key for filtering in the AngularJS and MEANJS framework

I am currently working on a MEANJS application that includes a CRUD module for countries. When I select a country from the default list view, it redirects me to the view-country.client.view page. In order to enhance my model, I have introduced a field name ...