Monday, 10 March 2025
New Arcade Game "Taps"
Sure! Below is a simple implementation of a text-based game called "Taps" in Ruby. The premise of the game is that players take turns "tapping" and whoever taps the button (presses a key) the most in a limited time wins. Here's a simple version of how you could implement it:
```ruby
class TapsGame
  attr_accessor :player1_score, :player2_score
  def initialize
    @player1_score = 0
    @player2_score = 0
    @duration = 10 # duration of the game in seconds
  end
  def start_game
    puts "Welcome to Taps!"
    puts "Player 1 and Player 2, get ready to tap for #{duration} seconds!"
    puts "Press 'Enter' to tap!"
    start_time = Time.now
    end_time = start_time + @duration
    # Create threads for each player to tap simultaneously
    player1_thread = Thread.new { player_tap(1) }
    player2_thread = Thread.new { player_tap(2) }
    # Wait for the game duration
    while Time.now < end_time
      sleep(0.1) # Just to prevent busy-waiting
    end
    # Stop the tapping
    puts "\nTime's up! The game has ended."
    player1_thread.join
    player2_thread.join
    
    # Display the scores
    display_scores
  end
  def player_tap(player_number)
    loop do
      gets # waits for Enter key to be pressed
      if player_number == 1
        @player1_score += 1
      else
        @player2_score += 1
      end
    end
  rescue Interrupt
    # Handle if the player manually interrupts the tapping
    puts "Player #{player_number} has stopped tapping."
  end
  def display_scores
    puts "Final Scores:"
    puts "Player 1: #{@player1_score}"
    puts "Player 2: #{@player2_score}"
    if @player1_score > @player2_score
      puts "Player 1 wins!"
    elsif @player2_score > @player1_score
      puts "Player 2 wins!"
    else
      puts "It's a tie!"
    end
  end
end
# Start the game
game = TapsGame.new
game.start_game
```
### How to Run the Game
1. Copy the code above and paste it into a new file called `taps_game.rb`.
2. Open your terminal or command prompt.
3. Navigate to the directory where you saved `taps_game.rb`.
4. Run the script using the command: `ruby taps_game.rb`.
### How to Play
- The game allows two players to participate.
- Each player should be ready to press the 'Enter' key to "tap" as quickly as possible within the set duration (10 seconds).
- At the end of the game, the final scores are displayed, indicating who won, or if it was a tie. 
Feel free to modify the duration or other aspects of the game if you wish!
Subscribe to:
Post Comments (Atom)
 
Free linens for the Irish Poor www.stpatricks.ie
ReplyDelete