In one example we are writing a game of craps in c... C is just too much typing, and hard to keep control over all syntax' for a newbie, but still learning! :D
Although we are programming in C, i first wrote the program in ruby wich gave me a much clearer understanding of what to do in C.(except from classes and rest of easy ruby syntaxes)
Even if you don't know much about programming, i guess you should be able to understand what the program does.
class Craps def initialize puts "A game of craps" first_roll end def first_roll roll = roll_dice case roll when 7,11 game_won when 2,3,12 game_lost else puts "Your point is: " + roll.to_s @my_points = roll keep_rolling end end def roll_dice #dice = (1+rand(6)) + (1+rand(6)) die1 = 1+rand(6) die2 = 1+rand(6) dice = die1 + die2 puts "You rolled: #{die1} + #{die2} = #{dice}" return dice end def game_won puts "You win" exit end def game_lost puts "You lose" exit end def keep_rolling roll = roll_dice case roll when @my_points game_won when 7 game_lost else while roll case roll_dice when @my_points game_won when 7 game_lost end end end end end play = Craps.new # Output: # A game of craps # You rolled: 5 # Your point is: 5 # You rolled: 12 # You rolled: 8 # You rolled: 5 # You win
I will not paste the C program here, since its pretty similar to the example in "C how to program" by Deitel and Deitel. Boooring! >)
A game of craps (Java)
The java version is just the same. The java syntax' are pretty easy to learn after studying C the last couple of weeks. Java is the language to learn if i ever want to make an android app... but... do i? o_O
I seem to love this game... maybe not, but its an easy way to learn, among other well written programs.
import java.util.Random; class Craps { private Random randomizeDice = new Random(); int my_point; int roll = 0; public void game_won() { System.out.println("You win!"); System.exit(0); } public void game_lost() { System.out.println("You lose!"); System.exit(0); } public void first_roll() { roll = roll_dice(); switch (roll) { case 7: case 11: game_won(); case 2: case 3: case 12: game_lost(); default: my_point = roll; System.out.println("Your point is: " + my_point); } }
Ingen kommentarer:
Legg inn en kommentar