Форум Flasher.ru
Ближайшие курсы в Школе RealTime
Список интенсивных курсов: [см.]  
  
Специальные предложения: [см.]  
  
 
Блоги Правила Справка Пользователи Календарь Сообщения за день
 

Вернуться   Форум Flasher.ru > Flash > ActionScript 3.0

Версия для печати  Отправить по электронной почте    « Предыдущая тема | Следующая тема »  
Опции темы Опции просмотра
 
Создать новую тему Ответ
Старый 06.04.2008, 10:54
A.E.M. вне форума Посмотреть профиль Отправить личное сообщение для A.E.M. Найти все сообщения от A.E.M.
  № 1  
Ответить с цитированием
A.E.M.
 
Аватар для A.E.M.

Регистрация: Jun 2007
Сообщений: 61
Отправить сообщение для A.E.M. с помощью ICQ
Thumbs up Почему при включении пользовательского класса возникает ошибка?

Вопрос:

Почему при компиляции возникает ошибка в файле класса "Cards.as"(в листинге строчки выделенны красным). Я вроде как понимаю, что какой то приватный атрибут может быть использован только в описании свойств класса... Но как я не бился, так ошибку и не нашел. Заранее прошу прощенья за большие куски кода

Текст ошибки "1013:The private attribute may be used only on class property definitions" - эта ошибка во всех строчках, выделенных красным.

Вот листинг "Example.as" - этот скрипт импортирует внешний класс(Cards.as) в котором возникает ошибка:

Код:
package main{

	import flash.display.Sprite;
	import main.ascb.play.Cards;
	import flash.utils.trace;


	public class Example extends Sprite {



		public function Example() {
			
			var cards:Cards = new Cards();
			var hands:Array = cards.deal(4,10);
			var i:uint;
			var j:uint;
			for (i=0; i< hands.length; i++){
				trace("hand"+i);
				for( j=0; j<hands[i].length; j++){
					trace(hands[i].getCardAt(j))
					}
				}
	
		}
		
	}
}
Вот листинг класса "Cards.as":

Код:
package main.ascb.play {

  import ascb.util.NumberUtilities;
  import ascb.util.ArrayUtilities;

  public class Cards {

    private var _cdkDeck:CardDeck;

    // The Cards constructor creates a deck of cards.
    public function Cards() {
      _cdkDeck = new CardDeck();
    }

    // The deal() method needs to know the number of players in the game 
    // and the number of cards to deal per player. If the cardsPerPlayer 
    // parameter is undefined, then it deals all the cards.
    public function deal(nPlayers:Number, nPerPlayer:Number = -1):Array {

      _cdkDeck.reset();
      _cdkDeck.shuffle();

      // Create an array, players, that holds the cards dealt to each player.
      var aHands:Array = new Array();

      // If a cardsPerPlayer value was passed in, deal that number of cards.
      // Otherwise, divide the number of cards (52) by the number of players.
      var nCardsEach:Number = (nPerPlayer == -1) ? Math.floor(_cdkDeck.deck.length / nPlayers) : nPerPlayer;

      // Deal out the specified number of cards to each player.
      for (var i:uint = 0; i < nPlayers; i++) {

        aHands.push(new CardHand(_cdkDeck));

        // Deal a random card to each player. Remove that card from the 
        // tempCards array so that it cannot be dealt again.
        for (var j:Number = 0; j < nCardsEach; j++) {
          aHands[i].hand.push(_cdkDeck.deck.shift());
        }

        // Use Cards.orderHand() to sort a player's hand, and use setHand() 
        // to assign it to the card player object.
        aHands[i].orderHand();
      }

      // Return the players array.
      return aHands;
    }
  }
  
  private class Card {

    private var _nValue:Number;
    private var _sName:String;
    private var _sSuit:String;

    public function get value():Number {
      return _nValue;
    }

    public function get name():String {
      return _sName;
    }

    public function get suit():String {
      return _sSuit;
    }

    public function get display():String {
      return _sName + " " + _sSuit;
    }

    public function Card(nValue:Number, sName:String, sSuit:String) {
      _nValue = nValue;
      _sName = sName;
      _sSuit = sSuit;
    }

    public function toString():String {
      return display;
    }
  	
  }
  
  private class CardDeck {
  
    private var _aCards:Array;
  
    public function get deck():Array {
      return _aCards;
    }
    
    public function CardDeck() {
      _aCards = new Array();
      reset();
    }
    
    public function reset():Void {
      for(var i:Number = 0; i < _aCards.length; i++) {
        _aCards.shift();
      }

      // Create a local array that contains the names of the four suits.
      var aSuits:Array = ["Hearts", "Diamonds", "Spades", "Clubs"];

      // Specify the names of the cards for stuffing into the cards array later.
      var aCardNames:Array = ["2", "3", "4", "5", "6", "7", "8", "9", "10",
                              "J", "Q", "K", "A"];

      // Create a 52-card array. Each element is an object that contains
      // properties for: the card's integer value (for sorting purposes), card name, 
      // suit name, and display name. The display name combines the card's name
      // and suit in a single string for display to the user.
      for (var i:Number = 0; i < aSuits.length; i++) {
        // For each suit, add thirteen cards
        for (var j:Number = 0; j < 13; j++) {
          _aCards.push(new Card(j, aCardNames[j], aSuits[i]));
        }
      }
    }

    public function shuffle():Void {
      var aShuffled:Array = ArrayUtilities.randomize(_aCards);
      for(var i:Number = 0; i < aShuffled.length; i++) {
        _aCards[i] = aShuffled[i];
      }
    }
    
    public function push(oParameter:Object):Void {
      _aCards.push(oParameter);
    }
  
  }
  
  private class CardHand {

    private var _cdkDeck:CardDeck;
    private var _aHand:Array;
    
    public function get hand():Array {
      return _aHand;
    }
    
    public function get length():uint {
      return _aHand.length;
    }

    // When a new card player is created by way of its constructor, pass it
    // a reference to the card deck, and give it a unique player ID.
    public function CardHand(cdkDeck:CardDeck) {
      _aHand = new Array();
      _cdkDeck = cdkDeck;
    }
    
    public function getCardAt(nIndex:uint):Card {
      return _aHand[nIndex];
    }
    

    public function discard():Array {
      var aCards:Array = new Array();
      for(var i:Number = 0; i < arguments.length; i++) {
        aCards.push(_aHand[arguments[i]]);
        _cdkDeck.push(_aHand[arguments[i]]);
      }
      for(var i:Number = 0; i < arguments.length; i++) {
        _aHand.splice(arguments[i], 1);
      }
      return aCards;
    }

    public function draw(nDraw:Number = 1):Void {
    
      // Add the specified number of cards to the hand.
      for (var i:uint = 0; i < nDraw; i++) {
        _aHand.push(_cdkDeck.deck.shift());
      }

      orderHand();
    }

    public function orderHand():Void {
      _aHand.sort(sorter);
    }

    // Used by sort() in the orderHand() method to sort the cards by suit and rank.
    private function sorter(crdA:Card, crdB:Card):Number {
      if (crdA.suit > crdB.suit) {
        return 1;
      } else if (crdA.suit < crdB.suit) {
        return -1;
      } else {
        return (Number(crdA.value) > Number(crdB.value)) ? 1 : 0;
      }
    }
    
  }
  
}
__________________
Да будет ФЛЭШ !

Старый 06.04.2008, 14:35
2morrowMan вне форума Посмотреть профиль Отправить личное сообщение для 2morrowMan Найти все сообщения от 2morrowMan
  № 2  
Ответить с цитированием
2morrowMan
 
Аватар для 2morrowMan

Регистрация: Aug 2007
Сообщений: 467
Смотри хелп как правильно писать классы в .as файлах.

Старый 06.04.2008, 14:39
A.E.M. вне форума Посмотреть профиль Отправить личное сообщение для A.E.M. Найти все сообщения от A.E.M.
  № 3  
Ответить с цитированием
A.E.M.
 
Аватар для A.E.M.

Регистрация: Jun 2007
Сообщений: 61
Отправить сообщение для A.E.M. с помощью ICQ
(: Спасибо, очень помог! Дело в том что данный класс писал не я, а авторы книги "рецепты ActionScript 3.0". Я пытался разобраться в чем дело, но так и не смог... поэтому сюда и написал.
__________________
Да будет ФЛЭШ !

Старый 06.04.2008, 14:41
etc вне форума Посмотреть профиль Найти все сообщения от etc
  № 4  
Ответить с цитированием
etc
Et cetera
 
Аватар для etc

Регистрация: Sep 2002
Сообщений: 30,784
Доступ должен быть указан как internal и такие классы должны идти вне блока package (в package может быть только один класс или функция).

Старый 06.04.2008, 15:13
A.E.M. вне форума Посмотреть профиль Отправить личное сообщение для A.E.M. Найти все сообщения от A.E.M.
  № 5  
Ответить с цитированием
A.E.M.
 
Аватар для A.E.M.

Регистрация: Jun 2007
Сообщений: 61
Отправить сообщение для A.E.M. с помощью ICQ
Вот поменял.... Теперь новые 4 ошибки в выделенных строчках (все 4 одинаковые) "1046:Type was not found or was not compile-time constant:void".

Еще заодно просьба, если не сложно пояснить правильно ли я понимаю, что "void" в данном случае это тип возращаемого методом значения и что если метод ничего не возвращает то используем именно его. Т.е. у метода обязательно должен указываца тип возвращаемого значения, правильно?

Код:
package main.ascb.play{

	import ascb.util.NumberUtilities;
	import ascb.util.ArrayUtilities;

	public class Cards {

		private var _cdkDeck:CardDeck;

		// The Cards constructor creates a deck of cards.
		public function Cards() {
			_cdkDeck=new CardDeck  ;
		}

		// The deal() method needs to know the number of players in the game 
		// and the number of cards to deal per player. If the cardsPerPlayer 
		// parameter is undefined, then it deals all the cards.
		public function deal(nPlayers:Number,nPerPlayer:Number=-1):Array {

			_cdkDeck.reset();
			_cdkDeck.shuffle();

			// Create an array, players, that holds the cards dealt to each player.
			var aHands:Array=new Array  ;

			// If a cardsPerPlayer value was passed in, deal that number of cards.
			// Otherwise, divide the number of cards (52) by the number of players.
			var nCardsEach:Number=nPerPlayer == -1?Math.floor(_cdkDeck.deck.length / nPlayers):nPerPlayer;

			// Deal out the specified number of cards to each player.
			for (var i:uint=0; i < nPlayers; i++) {

				aHands.push(new CardHand(_cdkDeck));

				// Deal a random card to each player. Remove that card from the 
				// tempCards array so that it cannot be dealt again.
				for (var j:Number=0; j < nCardsEach; j++) {//open6
					aHands[i].hand.push(_cdkDeck.deck.shift());
				}

				// Use Cards.orderHand() to sort a player's hand, and use setHand() 
				// to assign it to the card player object.
				aHands[i].orderHand();
			}

			// Return the players array.
			return aHands;
		}
	}
}
internal class Card {

	private var _nValue:Number;
	private var _sName:String;
	private var _sSuit:String;

public function get value():Number {
		return _nValue;
	}

	public function get name():String {
		return _sName;
	}

	public function get suit():String {
		return _sSuit;
	}

	public function get display():String {
		return _sName + " " + _sSuit;
	}

	public function Card(nValue:Number,sName:String,sSuit:String) {
		_nValue=nValue;
		_sName=sName;
		_sSuit=sSuit;
	}

	public function toString():String {
		return display;
	}
}
internal class CardDeck {

	private var _aCards:Array;

	public function get deck():Array {
		return _aCards;
	}
	public function CardDeck() {
		_aCards=new Array  ;
		reset();
	}
	public function reset():Void {
		for (var i:Number=0; i < _aCards.length; i++) {
			_aCards.shift();
		}

		// Create a local array that contains the names of the four suits.
		var aSuits:Array=["Hearts","Diamonds","Spades","Clubs"];

		// Specify the names of the cards for stuffing into the cards array later.
		var aCardNames:Array=["2","3","4","5","6","7","8","9","10","J","Q","K","A"];

		// Create a 52-card array. Each element is an object that contains
		// properties for: the card's integer value (for sorting purposes), card name, 
		// suit name, and display name. The display name combines the card's name
		// and suit in a single string for display to the user.
		for (var i:Number=0; i < aSuits.length; i++) {
			// For each suit, add thirteen cards
			for (var j:Number=0; j < 13; j++) {
				_aCards.push(new Card(j,aCardNames[j],aSuits[i]));
			}
		}
	}

	public function shuffle():Void {
		var aShuffled:Array=ArrayUtilities.randomize(_aCards);
		for (var i:Number=0; i < aShuffled.length; i++) {
			_aCards[i]=aShuffled[i];
		}
	}
	public function push(oParameter:Object):Void {
		_aCards.push(oParameter);
	}
}
internal class CardHand {

	private var _cdkDeck:CardDeck;
	private var _aHand:Array;

	public function get hand():Array {
		return _aHand;
	}
	public function get length():uint {
		return _aHand.length;
	}

	// When a new card player is created by way of its constructor, pass it
	// a reference to the card deck, and give it a unique player ID.
	public function CardHand(cdkDeck:CardDeck) {
		_aHand=new Array  ;
		_cdkDeck=cdkDeck;
	}
	public function getCardAt(nIndex:uint):Card {
		return _aHand[nIndex];
	}

	public function discard():Array {
		var aCards:Array=new Array  ;
		for (var i:Number=0; i < arguments.length; i++) {
			aCards.push(_aHand[arguments[i]]);
			_cdkDeck.push(_aHand[arguments[i]]);
		}
		for (var i:Number=0; i < arguments.length; i++) {
			_aHand.splice(arguments[i],1);
		}
		return aCards;
	}

	public function draw(nDraw:Number=1):Void {

		// Add the specified number of cards to the hand.
		for (var i:uint=0; i < nDraw; i++) {
			_aHand.push(_cdkDeck.deck.shift());
		}

		orderHand();
	}

	public function orderHand():Void {
		_aHand.sort(sorter);
	}

	// Used by sort() in the orderHand() method to sort the cards by suit and rank.
	private function sorter(crdA:Card,crdB:Card):Number {
		if (crdA.suit > crdB.suit) {
			return 1;
		} else if (crdA.suit < crdB.suit) {
			return -1;
		} else {
			return Number(crdA.value) > Number(crdB.value)?1:0;
		}
	}
}
__________________
Да будет ФЛЭШ !

Старый 06.04.2008, 15:15
etc вне форума Посмотреть профиль Найти все сообщения от etc
  № 6  
Ответить с цитированием
etc
Et cetera
 
Аватар для etc

Регистрация: Sep 2002
Сообщений: 30,784
void с маленькой буквы, а не с большой. Это в AS2 было с большой.
Тип возвращаемого значения надо указывать всегда, да.

Старый 06.04.2008, 15:15
Kyber Anton вне форума Посмотреть профиль Отправить личное сообщение для Kyber Anton Посетить домашнюю страницу Kyber Anton Найти все сообщения от Kyber Anton
  № 7  
Ответить с цитированием
Kyber Anton
 
Аватар для Kyber Anton

Регистрация: Oct 2005
Адрес: Воронеж-Москва
Сообщений: 671
Отправить сообщение для Kyber Anton с помощью ICQ
В AS3 void пишется с маленькой буквы.
__________________
(А)

Старый 06.04.2008, 15:32
A.E.M. вне форума Посмотреть профиль Отправить личное сообщение для A.E.M. Найти все сообщения от A.E.M.
  № 8  
Ответить с цитированием
A.E.M.
 
Аватар для A.E.M.

Регистрация: Jun 2007
Сообщений: 61
Отправить сообщение для A.E.M. с помощью ICQ
Ребят, Вам огромнейшее спасибо... просто я вот не могу понять как можно писать книгу по AS 3.0 и делать такие ошибки по типу "Void" вместо "void"...
Ну эт так... лирическое отступление...

Вот следующая ошибка "1120: Access of undefined property ArrayUtilities" в выделенной строчке.Подскажите что не так будьте добры (:

Код:
package main.ascb.play{//open1

	import main.ascb.util.NumberUtilities;
	import main.ascb.util.ArrayUtilities;

	public class Cards {//open2

		private var _cdkDeck:CardDeck;

		// The Cards constructor creates a deck of cards.
		public function Cards() {//open3
			_cdkDeck=new CardDeck  ;
		}//closed3

		// The deal() method needs to know the number of players in the game 
		// and the number of cards to deal per player. If the cardsPerPlayer 
		// parameter is undefined, then it deals all the cards.
		public function deal(nPlayers:Number,nPerPlayer:Number=-1):Array {//open4

			_cdkDeck.reset();
			_cdkDeck.shuffle();

			// Create an array, players, that holds the cards dealt to each player.
			var aHands:Array=new Array  ;

			// If a cardsPerPlayer value was passed in, deal that number of cards.
			// Otherwise, divide the number of cards (52) by the number of players.
			var nCardsEach:Number=nPerPlayer == -1?Math.floor(_cdkDeck.deck.length / nPlayers):nPerPlayer;

			// Deal out the specified number of cards to each player.
			for (var i:uint=0; i < nPlayers; i++) {//open5

				aHands.push(new CardHand(_cdkDeck));

				// Deal a random card to each player. Remove that card from the 
				// tempCards array so that it cannot be dealt again.
				for (var j:Number=0; j < nCardsEach; j++) {//open6
					aHands[i].hand.push(_cdkDeck.deck.shift());
				}//closed6

				// Use Cards.orderHand() to sort a player's hand, and use setHand() 
				// to assign it to the card player object.
				aHands[i].orderHand();
			}//closed5

			// Return the players array.
			return aHands;
		}//closed4
	}//closed2
}
internal class Card {

	private var _nValue:Number;
	private var _sName:String;
	private var _sSuit:String;

	public function get value():Number {
		return _nValue;
	}

	public function get name():String {
		return _sName;
	}

	public function get suit():String {
		return _sSuit;
	}

	public function get display():String {
		return _sName + " " + _sSuit;
	}

	public function Card(nValue:Number,sName:String,sSuit:String) {
		_nValue=nValue;
		_sName=sName;
		_sSuit=sSuit;
	}

	public function toString():String {
		return display;
	}
}
internal class CardDeck {

	private var _aCards:Array;

	public function get deck():Array {
		return _aCards;
	}
	public function CardDeck() {
		_aCards=new Array  ;
		reset();
	}
	public function reset():void {
		for (var i:Number=0; i < _aCards.length; i++) {
			_aCards.shift();
		}

		// Create a local array that contains the names of the four suits.
		var aSuits:Array=["Hearts","Diamonds","Spades","Clubs"];

		// Specify the names of the cards for stuffing into the cards array later.
		var aCardNames:Array=["2","3","4","5","6","7","8","9","10","J","Q","K","A"];

		// Create a 52-card array. Each element is an object that contains
		// properties for: the card's integer value (for sorting purposes), card name, 
		// suit name, and display name. The display name combines the card's name
		// and suit in a single string for display to the user.
		for (var i:Number=0; i < aSuits.length; i++) {
			// For each suit, add thirteen cards
			for (var j:Number=0; j < 13; j++) {
				_aCards.push(new Card(j,aCardNames[j],aSuits[i]));
			}
		}
	}

	public function shuffle():void {
		var aShuffled:Array=ArrayUtilities.randomize(_aCards);
		for (var i:Number=0; i < aShuffled.length; i++) {
			_aCards[i]=aShuffled[i];
		}
	}
	public function push(oParameter:Object):void {
		_aCards.push(oParameter);
	}
}
internal class CardHand {

	private var _cdkDeck:CardDeck;
	private var _aHand:Array;

	public function get hand():Array {
		return _aHand;
	}
	public function get length():uint {
		return _aHand.length;
	}

	// When a new card player is created by way of its constructor, pass it
	// a reference to the card deck, and give it a unique player ID.
	public function CardHand(cdkDeck:CardDeck) {
		_aHand=new Array  ;
		_cdkDeck=cdkDeck;
	}
	public function getCardAt(nIndex:uint):Card {
		return _aHand[nIndex];
	}

	public function discard():Array {
		var aCards:Array=new Array  ;
		for (var i:Number=0; i < arguments.length; i++) {
			aCards.push(_aHand[arguments[i]]);
			_cdkDeck.push(_aHand[arguments[i]]);
		}
		for (var i:Number=0; i < arguments.length; i++) {
			_aHand.splice(arguments[i],1);
		}
		return aCards;
	}

	public function draw(nDraw:Number=1):void {

		// Add the specified number of cards to the hand.
		for (var i:uint=0; i < nDraw; i++) {
			_aHand.push(_cdkDeck.deck.shift());
		}

		orderHand();
	}

	public function orderHand():void {
		_aHand.sort(sorter);
	}

	// Used by sort() in the orderHand() method to sort the cards by suit and rank.
	private function sorter(crdA:Card,crdB:Card):Number {
		if (crdA.suit > crdB.suit) {
			return 1;
		} else if (crdA.suit < crdB.suit) {
			return -1;
		} else {
			return Number(crdA.value) > Number(crdB.value)?1:0;
		}
	}
}
__________________
Да будет ФЛЭШ !

Создать новую тему Ответ Часовой пояс GMT +4, время: 15:52.
Быстрый переход
  « Предыдущая тема | Следующая тема »  

Ваши права в разделе
Вы не можете создавать новые темы
Вы не можете отвечать в темах
Вы не можете прикреплять вложения
Вы не можете редактировать свои сообщения

BB коды Вкл.
Смайлы Вкл.
[IMG] код Вкл.
HTML код Выкл.


 


Часовой пояс GMT +4, время: 15:52.


Copyright © 1999-2008 Flasher.ru. All rights reserved.
Работает на vBulletin®. Copyright ©2000 - 2024, Jelsoft Enterprises Ltd. Перевод: zCarot
Администрация сайта не несёт ответственности за любую предоставленную посетителями информацию. Подробнее см. Правила.