Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import scala.swing._
- import scala.util.Random
- import event._
- import scala.swing.BorderPanel.Position._
- object GuessingGame extends SimpleSwingApplication {
- val r = new Random
- def newRand(max: Int): Int = {
- r.nextInt(max)
- }
- var maxTries = 7
- var tries = 0
- var sekretNum = newRand(100)
- def top = new MainFrame {
- title = "Guessing Game"
- preferredSize = new Dimension(700, 400)
- contents = new BorderPanel {
- val hundred = new Button {
- text = "1-100 range"
- }
- val thousand = new Button {
- text = "1-1000 range"
- }
- val guess = new TextField {
- columns = 15
- text = "Take a wild guess between 0 and 100!"
- }
- val buttonBox = new BoxPanel(Orientation.Vertical) {
- contents += hundred
- contents += thousand
- contents += guess
- border = Swing.EmptyBorder(30, 30, 10, 30)
- }
- val feedback = new TextArea {
- text = ""
- }
- val feedbackBox = new BoxPanel(Orientation.Vertical) {
- contents += feedback
- border = Swing.EmptyBorder(30, 30, 10, 30)
- }
- layout(buttonBox) = West
- //layout(thousand) = West
- layout(feedback) = Center
- listenTo(hundred)
- listenTo(thousand)
- listenTo(guess)
- reactions += {
- case ButtonClicked(component) if component == hundred => {
- sekretNum = newRand(100)
- maxTries = 7
- tries = 0
- guess.text = "Take a wild guess between 0 and 100"
- }
- case ButtonClicked(component) if component == thousand => {
- sekretNum = newRand(1000)
- maxTries = 20
- tries = 0
- guess.text = "Take a wild guess between 0 and 1000"
- }
- case MouseClicked(component, _, _, _, _ ) if component == guess => {
- guess.text = ""
- }
- case EditDone(component) if component == guess => {
- if (tries == maxTries) {
- feedback.text += "You lose!\n"
- tries = 0
- }
- else if (guess.text.forall(! _.isDigit)){
- guess.text = ""
- }
- else {
- if ( guess.text.toInt < sekretNum) {
- feedback.text += "Higher\n"
- tries += 1
- }
- else if (guess.text.toInt > sekretNum) {
- feedback.text += "Lower!\n"
- tries += 1
- }
- else {
- feedback.text += "You win!\n"
- tries = 0
- }
- }
- guess.text = ""
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement