Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS 

Pousse (Game)

#! /usr/bin/ruby
# Pousse.rb   Ruby implementation of the game of Pousse.
class Hash
  #add a method to Hash that gets the next key in the hash, given a key.
  def next(key)
    keys = self.keys
    pos  = keys.index(key)
    if pos+1 == keys.length
      return keys[0]
    else
      return keys[pos+1]
    end
  end  
end
  
class Pousse
  def initialize(size = 4)
    @size       = size.to_i.freeze                      #our size can't change
    @board      = Array.new(@size){ Array.new(@size) }  #2d board array
    @previous   = []                                    #previous boards
    @players    = {:one => 'X', :two => 'O'}.freeze     #hash of players as:
                                                        # :name => piece
    run                                                 #run the game
  end
  
  #returns true if a victor is found, false if not
  def victory?
    grand_total = Hash.new(0)
    inv_players = @players.invert
    
    #add all the rows/cols representing a straight to grand_total
    @board.each_index do |x|
      r_sub, c_sub = Hash.new(0), Hash.new(0)
      @board[x].each_index do |y|
        r_sub[inv_players[@board[x][y]]] += 1 if @board[x][y]
        c_sub[inv_players[@board[y][x]]] += 1 if @board[y][x]
      end
      #add up subtotal vals
      [c_sub, r_sub].each do |a|
        a.each do |x|
          grand_total[x[0]] += 1 if x[1] == @size
        end
      end
    end
    
    #check for victory with straights
    if grand_total.values.inject{|sum, n| sum+n}
      if grand_total[@player] == grand_total[@players.next(@player)]
        puts "It's a tie!"
      elsif grand_total[@player] > grand_total[@players.next(@player)]
        puts "Player #{@player.to_s}, you win!"
        return true
      else
        puts "Player #{@players.next(@player)}, you win!"
        return true
      end
    end
    
    #check to see if this board is not a new one..
    @previous.each do |x|
      if x == @board
        puts "Player #{@player.to_s}, that board is a REPEAT! YOU LOSE!"
        return true
      end
    end
    #add a deep copy of the current board to the previous board list
    @previous << Marshal.load(Marshal.dump(@board))
    false
  end
  
  #print help messages
  def display_help
    puts "--------"
    puts "General commands:
    h - display this help dialog
    d - draw the board
    q - quit the program"
    
    puts "move? commands (i is an integer from 1 to #{@size})
    Li - Left
    Ri - Right
    Ti - Top
    Bi - Bottom"
    puts "--------"
  end
  
  #draw a grid representing current board status
  def draw_board
    #build numbers for top
    print "\n  "
    @size.times do |x|
      print " #{x+1}"
    end
    puts ""
    
    #main board section
    (@size * 2).times do |x|
      if (x % 2 == 0) #print a boundry
        print "  "
        @size.times { print "+-" }
        puts "+"
      else #print a data row
        print "#{x/2+1} "
        @size.times do |y|
          print "|"
          print @board[x/2][y] ? @board[x/2][y] : " "
        end
        puts "|"
      end
    end
    
    #bottom border
    print "  "
    @size.times { print "+-" }
     puts "+"
  end

  #execute a move? command. returns true if the move? was successful,
  #false if not
  def move?(command)
    direction, row = command.split(//)
    row = row.to_i
    
    if row > @size or row < 1 #we have a problem.
      puts "Invalid index value (#{row}) supplied."
      return false
    end
    
    row -= 1 #offset because of array index
    
    #setup values for shift_board call
    case direction.upcase
      when "L" then x = row;      y = 0;        dx = 0;   dy =  1
      when "R" then x = row;      y = @size-1;  dx = 0;   dy = -1
      when "T" then x = 0;        y = row;      dx = 1;   dy =  0
      when "B" then x = @size-1;  y = row ;     dx = -1;  dy =  0
    end
    shift_board(x, y, dx, dy, @players[@player])
    true
  end
  
  #game run loop. this method returns when the game is over
  def run
    puts "Welcome to Pousse!"
    display_help
    @player = :one
    loop do
      puts "Player #{@player.to_s}'s (#{@players[@player]}) turn."
      
      #get a value from the command line
      print "> "
      _input = $stdin.gets
      
      #process the input
      if    _input =~ /^[q|Q]/                  then break
      elsif _input =~ /^[h|H]/                  then display_help
      elsif _input =~ /^[d|D]/                  then draw_board
      elsif _input =~ /^[L|R|T|B|l|r|t|b][\d]/  then
        if move?(_input)
           draw_board
           break if victory? #exit the loop if we find a winner
           @player = @players.next(@player)
        end
      else puts "Command not recognized."
      end
    end
    puts "Thanks for playing Pousse!"
  end
  
  #shift cells in the board until our new data is appended and old data
  #is shifted into blank spaces or lost
  def shift_board(to_x, to_y, dx, dy, append)
    if to_y < @size and to_x < @size then #only handle existing cells
      if @board[to_x][to_y] != nil then
        mv = @board[to_x][to_y]
        @board[to_x][to_y] = nil
        shift_board(to_x+dx, to_y+dy, dx, dy, mv)
      end
      @board[to_x][to_y] = append
    end
  end
end

if ARGV[0]
  Pousse.new(ARGV[0]) 
else
  Pousse.new
end

Code Of A Game

This Is A Code Of A Game.

Coppy It Into Notepad And Then Save It As Game.bat

Warning!
Make Sure It Says "All Files (*.*)" And Not "Text Document (.txt)" At The Bottom.
The Code Is:
@echo off
goto verybegingame
: verybegingame
echo Welcome To This Game!
title Game Start
echo Press Any Key For Stuff.
pause >nul
echo Loading...
ping localhost 6 >nul
echo.. Loading Comple!
pause >nul
cls
echo Rules:
title Game Rules
echo..You Answer Each Question.
echo. If It Is Correct, You Will Move On.
echo If It is InCorrect, The Program Will
echo Exit And You Will Need To Try Again.
echo.. If You Get All The Questions Right, You
echo Will Receave A Speical Code.
echo Enter THe Code For A Suprse!
echo...
echo Good Luck!
echo.....
echo Press A Key Of An Option, And Then 
echo Press 'Enter'.
echo...
echo                        1 = Play Game          2 = Enter Code
SET /P "onechoose1=Enter 1 or 2 option here:"
If %onechoose1%= 1 then goto playgame
If %onechoose1%= 2 then goto entercode
:playgame
cls
echo What Is My Name?
echo A.Jonathan
echo B.Sam
echo C.Johnn
SET /p "q1=Enter Option:"
If NOT%q1%= A then exit
:entercode
echo  Enter Code
SET /P "codeenter= "
If %entercode%=code... goto prize
:prize



All Of ThAT...
MAKE MORE QUESTIONS.
etc.

Silly Game of War

class Card
  include Comparable
  attr_accessor :suit, :value

  @@values = Hash.new { |hash, key| key.to_s }
  @@values.merge!(11 => 'jack', 12 => 'queen', 13 => 'king', 14 => 'ace')
  
  def initialize(suit, value)
    @suit = suit
    @value = value
  end
  
  def to_s
    "#{@@values[@value]} of #{@suit}s"
  end
  
  def <=> (other)
    @value <=> other.value
  end
end

class GroupOfCards < Array
  def shuffle!
    replace(sort_by { rand })
  end
  
  def to_s
    join(", ")
  end  
end

class Deck < GroupOfCards
  def initialize
    [:spade, :diamond, :club, :heart].each do |suit|
      (2..14).each do |value|
        push(Card.new(suit, value))
      end
    end
  end  
end

class Player
  attr_accessor :name, :table
  
  def initialize(name)
    @name = name
    @hand = GroupOfCards.new
    @pile = GroupOfCards.new
    @table = GroupOfCards.new
  end
  
  def play_card
    if @hand.empty?
      @hand, @pile = @pile, @hand
      @hand.shuffle!
    end
    @table << @hand.pop
  end
  
  def add_card(card)
    @pile << card
  end
  
  def cards
    @hand + @pile
  end
  
  def showing
    @table.last
  end
  
  def card_count
    @hand.size + @pile.size + @table.size
  end
  
  def has_cards?
    card_count > 0
  end
  
  def status
    "#{@name}(#{card_count}) plays #{showing}"
  end
  
  def to_s
    name
  end
end

class GameOfWar
  def initialize(player_count=2)
    deck = Deck.new
    deck.shuffle!
    @players = Array.new(player_count) { |i| Player.new("Player #{i+1}") }
    
    deck.shuffle!
    until deck.empty?
      player = @players.shift
      player.add_card(deck.pop)
      @players.push(player)
    end  
  end
  
  def play_round(players)
    spoils_of_war = []
    
    # get cards
    players.each do |p| 
      p.play_card
      puts p.status
    end 
    
    # find winner (handle ties)
    winners = players.sort_by { |p| p.showing }
    high_card = winners.last.showing
    
    winners = winners.select { |p| p.showing == high_card }
    
    # deal with ties
    if winners.size > 1
	    puts "WAR: #{winners.join(", ")}"
	    # put one card "in the kitty"
	    winners.each { |p| p.play_card }
      winner = play_round(winners)
    else
      winner = winners.first
		  puts "Winner: #{winner}"
    end
    
    players.each { |p| spoils_of_war += p.table; p.table = [] }
    spoils_of_war.each { |c| winner.add_card(c) }
    winner
  end
  
  def play
    round = 1
    until @players.size == 1
      puts "\nAt Round #{round}"
      play_round(@players)
      round += 1
      
      # check for loosers
      loosers = @players.select { |p| p.card_count == 0 }
      loosers.each { |p| puts "#{p} lost"}
      @players -= loosers
    end
    
    puts "\n#{@players.first.name} Won!!!"
  end
  
  def to_s
    @players.join("\n")
  end
end

if __FILE__ == $0
  g = GameOfWar.new 3
  g.play
end

15-square game

py_s60 1.1.3 was released a week ago.
I wonder why there's no more people playing with it.
So, I have created a simple game as an example.

I don't know what this game is called. It has 4x4 square box
with 15 pieces (1 piece missing). You need to move all the
pieces into sorting order.

Since the program is so simple, I decided to make the
moving of a piece smoother by moving it bit by bit.
Hope this doesn't make the code to hard to read.

from appuifw import *
from key_codes import *
import e32, random

# run and break-loop type of app
sleep = e32.ao_sleep
running = 1
def set_exit():
global running
running = 0
app.exit_key_handler= set_exit

# canvas and typical colors
c = Canvas()
app.body = c
red, green, blue, gray, white = 0xff0000, 0x00ff00, 0x0000ff, 0x777777, 0xffffff

# randomize number order for pieces
seq = range(1,17)
random.shuffle(seq)
b = [seq[0:4], seq[4:8], seq[8:12], seq[12:16]]

def piece(i, j, n):
if n < 10:
c.text( (12+20*i, 20+20*j), unicode(n))
else:
c.text( (7+20*i, 20+20*j), unicode(n))

def box(i, j, color, fill=None):
c.rectangle( [5+20*i, 5+20*j, 25+20*i, 25+20*j], color, fill)

# draw board pieces
for k in range(16):
j, i = divmod(k, 4)
piece(i, j, b[j][i])

y, x = divmod(seq.index(16), 4)
box(x, y, white, white)
moving = 0 # cursor to lock if animating

# move cursor in dx, dy direction
def move(dx, dy):
global x,y, moving
if moving:
return
moving = 1
if 0 <= x-dx < 4 and 0 <= y-dy < 4:
b[y][x] = b[y-dy][x-dx]
animate(x-dx, y-dy, dx, dy, b[y][x])
x -= dx # the hole move in opposite direction
y -= dy
moving = 0

# moving a piece for x,y to dx, dy direction
def animate(x, y, dx, dy, n):
if n < 10:
px = 12
else:
px = 7
for i in range(5):
c.text( (px+20*x + 4*i*dx, 20+20*y + 4*i*dy), unicode(n))
sleep(0.05)
c.text( (px+20*x + 4*i*dx, 20+20*y + 4*i*dy), unicode(n), white)
c.text( [px+20*(x+dx), 20+20*(y+dy)], unicode(n) )

# bind arrow keys
c.bind(EKeyRightArrow,lambda:move(1, 0))
c.bind(EKeyLeftArrow,lambda:move(-1, 0))
c.bind(EKeyUpArrow,lambda:move(0, -1))
c.bind(EKeyDownArrow,lambda:move(0, 1))

# main loop, just wait
while running:
sleep(0.1)
« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS