Everything appears to be working in this tic tac toe game, except for displaying the "draw" label when there is no winner. The label will switch when Cross or circles wins, but not when there is a tie.
I'm stumped. E
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var label: UILabel!
var count = 1
var activePlayer = 1 //Cross
var gameState = [0,0,0,0,0,0,0,0,0]
var gameIsActive = true
let winningCombinations = [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6]]
#IBAction func action(_ sender: AnyObject) {
if (gameState[sender.tag-1] == 0 && gameIsActive == true) {
gameState[sender.tag-1] = activePlayer
if (activePlayer == 1) {
sender.setImage(UIImage(named: "cross.png"), for: UIControl.State())
activePlayer = 2
} else {
sender.setImage(UIImage(named: "nought.png"), for: UIControl.State())
activePlayer = 1
}
}
for combination in winningCombinations {
if gameState[combination[0]] != 0 &&
gameState[combination[0]] == gameState[combination[1]] &&
gameState[combination[1]] == gameState[combination[2]] {
gameIsActive = false
if gameState[combination[0]] == 1 {
label.text = "Cross has won!"
} else {
label.text = "Circle has won!"
}
if gameIsActive == true {
for i in gameState {
count = i*count
}
if count != 0 {
label.text = "It was a draw."
label.isHidden = false
playAgainButton.isHidden = false
}
}
playAgainButton.isHidden = false
label.isHidden = false
}
}
} // End Button Action
#IBOutlet weak var playAgainButton: UIButton!
#IBAction func playAgain(_ sender: Any) {
gameState = [0,0,0,0,0,0,0,0,0]
gameIsActive = true
activePlayer = 1
playAgainButton.isHidden = true
label.isHidden = true
for i in 1...9 {
let button = view.viewWithTag(i) as! UIButton
button.setImage(nil, for: UIControl.State())
}
}
override func viewDidLoad() {
super.viewDidLoad()
playAgainButton.isHidden = true
label.isHidden = true
}
} // End ViewController
You are saying
gameIsActive = false
// ... some other stuff ...
if gameIsActive == true {
// check for a draw
}
But gameIsActive is not true, because you just set it to false. Therefore we never perform the check for a draw.
Thanks for the help everyone! I finally got it working correctly.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var playAgainButton: UIButton!
#IBOutlet weak var label: UILabel!
var count = 1
var activePlayer = 1 //Cross
var gameState = [0,0,0,0,0,0,0,0,0]
var gameIsActive = true
let winningCombinations = [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6]]
#IBAction func action(_ sender: AnyObject) {
count = 1;
if (gameState[sender.tag-1] == 0 && gameIsActive == true) {
if (activePlayer == 1) {
gameState[sender.tag-1] = activePlayer
sender.setImage(UIImage(named: "cross.png"), for: UIControl.State())
activePlayer = 2
} else {
sender.setImage(UIImage(named: "nought.png"), for: UIControl.State())
gameState[sender.tag-1] = activePlayer
activePlayer = 1
}
}
for combination in winningCombinations {
if gameState[combination[0]] != 0 && gameState[combination[0]] ==
gameState[combination[1]] && gameState[combination[1]] ==
gameState[combination[2]]{
gameIsActive = false
if gameState[combination[0]] == 1 {
label.text = "Cross has won!"
} else {
label.text = "Circle has won!"
}
playAgainButton.isHidden = false
label.isHidden = false
}
}
if gameIsActive == true{
for i in gameState{
count = i * count
}
if count != 0{
label.text = "DRAW!"
playAgainButton.isHidden = false
label.isHidden = false
}
}
}
#IBAction func playAgain(_ sender: Any) {
gameState = [0,0,0,0,0,0,0,0,0]
gameIsActive = true
activePlayer = 1
playAgainButton.isHidden = true
label.isHidden = true
for i in 1...9
{
let button = view.viewWithTag(i) as! UIButton
button.setImage(nil, for: UIControl.State())
}
}
override func viewDidLoad() {
super.viewDidLoad()
playAgainButton.isHidden = true
label.isHidden = true
}
}
Related
The entire code for my Tic Tac Toe game has been pasted below. It doesn't run due to an error in the Declare Winner function being added after its use. How do I correct this?
Do I simply create it earlier?
Use of local variable 'DeclareWinner' before its declaration. This is what it says. What am I supposed to do?
import UIKit
class GameViewController: UIViewController {
#IBOutlet weak var MainTitle: UILabel!
#IBOutlet weak var Player1Label: UILabel!
#IBOutlet weak var Player2Label: UILabel!
#IBOutlet weak var PlayerTurnLabel: UILabel!
#IBOutlet weak var GameONLabel: UILabel!
var matrix: [[Int]] = [[0,0,0],[0,0,0],[0,0,0]] // 0 - Nothing, 1 - X, 2 - O
var WhosTurn = 0 // 1- Player1, 2- Player2
var Player1 = 0 // 0 - Nothing, 1 - X, 2 - O
var Player2 = 0 // 0 - Nothing, 1 - X, 2 - O
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
StartGame()
}
func StartGame(){
matrix = [[0,0,0],[0,0,0],[0,0,0]] // 0 - Nothing, 1 - X, 2 - O
displayMat(matrix: matrix)
WhosTurn = Int.random(in: 1...2)
if (WhosTurn == 1){ // Player1's Turn and He's X
Player1 = 1
Player2 = 2
Player1Label.text = "Player 1: X"
Player2Label.text = "Player 2: O"
PlayerTurnLabel.text = "Turn: Player 1"
}else {// Player2's Turn and He'll be O
Player1 = 2
Player2 = 1
Player1Label.text = "Player 1: O"
Player2Label.text = "Player 2: X"
PlayerTurnLabel.text = "Turn: Player 2"
}
}
func displayMat(matrix: [[Int]]) {
var TempTag = 1
for i in 0...2 {
for j in 0...2 {
if (matrix[i][j] == 0 ) {
let TempButton = self.view.viewWithTag(TempTag) as? UIButton
TempButton?.setBackgroundImage(nil, for: .normal)
} else if (matrix[i][j] == 1) { //Display X
let TempButton = self.view.viewWithTag(TempTag) as? UIButton
TempButton?.setBackgroundImage(UIImage(named: "X"), for: .normal)
}else if (matrix[i][j] == 2) { //Display O
let TempButton = self.view.viewWithTag(TempTag) as? UIButton
TempButton?.setBackgroundImage(UIImage(named: "O"), for: .normal)
}else {
}
TempTag += 1
}
}
}
#IBAction func ButtonClickedXorO(_ sender: Any) {
var TempObject = 0
if (WhosTurn == 1){ // Player1's Turn and He's X
TempObject = Player1
Player1 = 1
Player2 = 2
Player1Label.text = "Player 1: X"
Player2Label.text = "Player 2: O"
PlayerTurnLabel.text = "Turn: Player 1"
}else {// Player2's Turn and He'll be O
TempObject = Player2
PlayerTurnLabel.text = "Turn: Player 2"
}
guard let button = sender as? UIButton else {
return
}
switch button.tag {
case 1:
if (matrix[0][0] == 0) {
matrix[0][0] = TempObject
JustPlayed()
}
case 2:
if (matrix[0][1] == 0) {
matrix[0][1] = TempObject
JustPlayed()
}
case 3:
if (matrix[0][2] == 0) {
matrix[0][2] = TempObject
JustPlayed()
}
case 4:
if (matrix[1][0] == 0) {
matrix[1][0] = TempObject
JustPlayed()
}
case 5:
if (matrix[1][1] == 0) {
matrix[1][1] = TempObject
JustPlayed()
}
case 6:
if (matrix[1][2] == 0) {
matrix[1][2] = TempObject
JustPlayed()
}
case 7:
if (matrix[2][0] == 0) {
matrix[2][0] = TempObject
JustPlayed()
}
case 8:
if (matrix[2][1] == 0) {
matrix[2][1] = TempObject
JustPlayed()
}
case 9:
if (matrix[2][2] == 0) {
matrix[2][2] = TempObject
JustPlayed()
}
default:
print("Error")
}
}
func JustPlayed(){
displayMat(matrix: matrix)
Winner()
if (WhosTurn == 1) {
WhosTurn = 2
PlayerTurnLabel.text = "Turn: Player 2"
}else {
WhosTurn = 1
PlayerTurnLabel.text = "Turn: Player 1"
}
}
func Winner(){
var Counter = true
if ((matrix[0][0] == matrix[1][1] && matrix[1][1] == matrix[2][2] && matrix[1][1] != 0))
DeclareWinner(WhoWon: matrix[1][1])
}else if ((matrix[2][0] == matrix[1][1] && matrix[1][1] == matrix[0][2] && matrix[1][1] != 0)) {
DeclareWinner(WhoWon: matrix[1][1])
}else {
for i in 0...2{
if (matrix[i][0] == matrix[i][1] && matrix[i][1] == matrix[i][2] && matrix[i][0] != 0){
DeclareWinner(WhoWon: matrix[i][0])
Counter = false
}
}
if Counter{
for i in 0...2{
if (matrix[0][i] == matrix[1][i] && matrix[1][i] == matrix[2][i] && matrix[0][i] != 0){
DeclareWinner(WhoWon: matrix[0][i])
}
}
}
}
func DeclareWinner(WhoWon: Int){
if (WhoWon == Player1) {
// Player1 Won
GameONLabel.text = "Player 1 Won!"
}else if (WhoWon == Player2){
//Player2 Won
GameONLabel.text = "Player 2 Won!"
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
#IBAction func GoBack(_ sender: Any) {
dismiss(animated: true, completion:nil)
}
}
Can someone please add the code to this so I'm able to add a decimal point button?
This is what I have so far, can someone please fill in the code required for the decimal point button. so I can learn from it. please view over the code and let me know what you think.
import UIKit
class ViewController: UIViewController {
var numberOnScreen:Double = 0;
var previousNumber:Double = 0;
var preformingMath = false
var operation = 0;
#IBOutlet weak var label: UILabel!
#IBAction func numbers(_ sender: UIButton)
{
if preformingMath == true
{
label.text = String(sender.tag-1)
numberOnScreen = Double(label.text!)!
preformingMath = false
}
else
{
label.text = label.text! + String(sender.tag-1)
numberOnScreen = Double(label.text!)!
}
}
#IBAction func buttons(_ sender: UIButton)
{
if label.text != "" && sender.tag != 11 && sender.tag != 16
{
previousNumber = Double(label.text!)!
if sender.tag == 12 //Divide
{
label.text = "/";
}
else if sender.tag == 13//Multiply
{
label.text = "x";
}
else if sender.tag == 14 //Minus
{
label.text = "-";
}
else if sender.tag == 15 //Plus
{
label.text = "+";
}
operation = sender.tag;
preformingMath = true;
}
else if sender.tag == 16
{
if operation == 12
{
label.text = String(previousNumber / numberOnScreen)
}
else if operation == 13
{
label.text = String(previousNumber * numberOnScreen)
}
else if operation == 14
{
label.text = String(previousNumber - numberOnScreen)
}
else if operation == 15
{
label.text = String(previousNumber + numberOnScreen)
}
}
else if sender.tag == 11
{
label.text = ""
previousNumber = 0;
numberOnScreen = 0;
operation = 0;
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
}
Add this #IBAction to your code and hook it to your . button.
If the user presses . before any numbers, the display will be set to 0..
If there are numbers in the display, then . will be appended to the display if there isn't already a decimal point in the number.
Finally, the numberOnScreen will be updated.
#IBAction func decimal(_ sender: UIButton) {
if preformingMath || label.text!.isEmpty
{
label.text = "0."
preformingMath = false
}
else
{
if !label.text!.contains(".") {
label.text = label.text! + "."
}
}
numberOnScreen = Double(label.text!)!
}
I think my code regarding buttons is violating the DRY principle. Can you suggest a more efficient way to reduce the clutter?
#IBAction func competitiveButton(_ sender: Any) {
if competitiveMatch.isEnabled == true {
competitiveMatch.isEnabled = false
friendlyMatch.isEnabled = true
tournamentButton.isEnabled = true
trainingButton.isEnabled = true
} else {
competitiveMatch.isEnabled = true
}
}
#IBAction func friendlyButton(_ sender: Any) {
if friendlyMatch.isEnabled == true {
friendlyMatch.isEnabled = false
tournamentButton.isEnabled = true
competitiveMatch.isEnabled = true
trainingButton.isEnabled = true
} else {
friendlyMatch.isEnabled = true
}
}
#IBAction func tourneyButton(_ sender: Any) {
if tournamentButton.isEnabled == true {
tournamentButton.isEnabled = false
friendlyMatch.isEnabled = true
trainingButton.isEnabled = true
competitiveMatch.isEnabled = true
} else {
tournamentButton.isEnabled = true
}
}
#IBAction func trainingButton(_ sender: Any) {
if trainingButton.isEnabled == true {
trainingButton.isEnabled = false
friendlyMatch.isEnabled = true
tournamentButton.isEnabled = true
competitiveMatch.isEnabled = true
} else {
trainingButton.isEnabled = true
}
}
The code follows a set pattern for all four buttons. I am not able to factor a shorter method to do the same. Please help. Complete beginner here.
You can use a single IBAction instead of 4 separate methods. And make the sender type to UIButton from Any. Then you can do something like
#IBAction func toggleEnableDisable(_ sender: UIButton) {
let currentValue = sender.isEnabled
let buttonArray = [trainingButton, friendlyMatch, tournamentButton, competitiveMatch]
buttonArray.forEach { $0.isEnabled = false }
sender.isEnabled = !currentValue
}
i have quiz app and have 10 sec timer each question. First question timer is fine, but in second question it going faster than before. I try this tutorial to make timer and this tutorial to make quiz app
here's my code :
override func viewDidLoad() {
timerBegin()
}
func timerBegin() {
myTimer.invalidate() // print error `fatal error: unexpectedly found nil while unwrapping an Optional value`
timeLeft = 10
myTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(SoalViewController.timerRunning), userInfo: nil, repeats: true)
}
func timerRunning() {
timeLeft -= 1
timeLabel.text = "\(timeLeft)"
if timeLeft == 0 {
myTimer.invalidate()
timeLabel.text = "10"
pickQuestion()
timerBegin()
}
}
here's my option button code :
#IBAction func opsiA(_ sender: Any) {
timeLabel.text = "10"
timerBegin()
if AnswerNumber == 0 {
pickQuestion()
Score += 10
scoreLabel.text = "\(Score)"
} else {
pickQuestion()
print("Wrong")
}
}
#IBAction func opsiB(_ sender: Any) {
timeLabel.text = "10"
timerBegin()
if AnswerNumber == 1 {
pickQuestion()
Score += 10
scoreLabel.text = "\(Score)"
} else {
pickQuestion()
print("Wrong")
}
}
#IBAction func opsiC(_ sender: Any) {
timeLabel.text = "10"
timerBegin()
if AnswerNumber == 2 {
pickQuestion()
Score += 10
scoreLabel.text = "\(Score)"
} else {
pickQuestion()
print("Wrong")
}
}
#IBAction func opsiD(_ sender: Any) {
timeLabel.text = "10"
timerBegin()
if AnswerNumber == 3 {
pickQuestion()
Score += 10
scoreLabel.text = "\(Score)"
} else {
pickQuestion()
print("Wrong")
}
}
and this is my pick question function :
func pickQuestion() {
if Questions.count > 10 {
QNumber = Int(arc4random_uniform(UInt32(10)))
textView.text = Questions[QNumber].Question
AnswerNumber = Questions[QNumber].Answer
for i in 0..<Buttons.count {
Buttons[i].setTitle(Questions[QNumber].Answers[i], for: UIControlState.normal)
}
Questions.remove(at: QNumber)
} else {
darkView.isHidden = false
scoreLabel.text = "\(Score)"
timeLabel.isHidden = true
if Score > standStill {
HighScore = Score
highScoreLabel.text = NSString(format: "Highscore : %i", HighScore) as String
let currentHighScore = UserDefaults.standard
currentHighScore.set(HighScore, forKey: "HighScore")
} else {
let currentHighScore = UserDefaults.standard
currentHighScore.set(standStill, forKey: "HighScore")
}
}
}
i already try to stop timer by adding myTimer.invalidate() in first line of timerBegin function but it print fatal error: unexpectedly found nil while unwrapping an Optional value
I am having problems with my interstitial ads popping up too often. The full screen ads comes on after every game over screen, meaning each time the player loses the ad pops up which i feel will get annoying. Is there a way to stop this happening after each failure to maybe after every 2 or 3 gameovers?
I have attached my code below, any help would be greatly appreciated.
import UIKit
import AVFoundation
import GoogleMobileAds
import Social
class ViewController: UIViewController {
#IBOutlet var bannerView: GADBannerView!
var admobInterstitial : GADInterstitial?
var timerAds : NSTimer?
var player:AVAudioPlayer = AVAudioPlayer()
var score = 0
var timer = NSTimer()
var seconds = 8
var watch = true
var watch1 = true
var gameActive = true
var hiScore = 0
var counter = 1
var turn = 0
var timer_anim = NSTimer()
#IBOutlet var btn: UIButton!
#IBOutlet var scr: UILabel!
#IBOutlet var scoreLabel: UILabel!
#IBOutlet var again: UIButton!
#IBOutlet var highScore: UILabel!
#IBOutlet var gameTimer: UILabel!
#IBOutlet var startView: UIImageView!
#IBOutlet var startButton: UIButton!
#IBOutlet var game_over: UIImageView!
#IBOutlet var twBtn: UIButton!
#IBAction func twitterBtn(sender: AnyObject) {
if SLComposeViewController.isAvailableForServiceType(SLServiceTypeTwitter)
{
var twShare:SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
twShare.setInitialText("I dare you get a higher score than mine : ( \(score) ) GET it NOW on IOS : https://itunes.apple.com/us/app/oscar-cookie/id1099453391?mt=8")
twShare.addImage(UIImage(named: "start.png"))
self.presentViewController(twShare, animated: true, completion: nil)
}
else
{
var alert = UIAlertController(title: "Account", message: "Please login to Twitter to Tweet", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
#IBOutlet var fbBtn: UIButton!
#IBAction func facebookBtn(sender: AnyObject) {
if SLComposeViewController.isAvailableForServiceType(SLServiceTypeFacebook)
{
var fbShare:SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
fbShare.setInitialText("I dare you get a higher score than mine : ( \(score) ) GET it NOW on IOS : https://itunes.apple.com/us/app/oscar-cookie/id1099453391?mt=8")
fbShare.addImage(UIImage(named: "start.png"))
self.presentViewController(fbShare, animated: true, completion: nil)
}
else
{
var alert = UIAlertController(title: "Account", message: "Please login to Facebook to share", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
#IBAction func startButtonFun(sender: AnyObject) {
startButton.hidden = true
startView.hidden = true
btn.hidden = false
player.pause()
}
#IBAction func playAgain(sender: AnyObject) {
player.pause()
//gameOverLbl.hidden = true
scoreLabel.hidden = true
again.hidden = true
btn.hidden = false
highScore.hidden = true
scr.hidden = false
game_over.hidden = true
fbBtn.hidden = true
twBtn.hidden = true
gameActive = true
watch = true
score = 0
scr.text = "0"
gameTimer.text = "8"
if watch1 == false
{
timer_anim.invalidate()
watch1 = true
}
}
#IBAction func button(sender: AnyObject) {
if score % 5 == 0
{
let audioPath = NSBundle.mainBundle().pathForResource("chew2", ofType: "mp3")!
do
{
try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath : audioPath))
player.play()
}
catch
{
}
}
else
{
let audioPath = NSBundle.mainBundle().pathForResource("chew1", ofType: "mp3")!
do
{
try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath : audioPath))
player.play()
}
catch
{
}
}
keepPlaying()
}
// func to locate the bottong randomly to all sizes
func randomLocating () {
var randomH = Int()
var randomW = Int()
if UIDevice().userInterfaceIdiom == .Phone {
switch UIScreen.mainScreen().nativeBounds.height {
case 480:
//print("iPhone Classic")
randomH = Int(arc4random_uniform(380))
randomW = Int(arc4random_uniform(260))
while randomH < 50 || randomW < 40
{
randomH = Int(arc4random_uniform(380))
randomW = Int(arc4random_uniform(260))
}
case 960:
//print("iPhone 4 or 4S")
randomH = Int(arc4random_uniform(380))
randomW = Int(arc4random_uniform(270))
while randomH < 50 || randomW < 40
{
randomH = Int(arc4random_uniform(380))
randomW = Int(arc4random_uniform(270))
}
case 1136:
// print("iPhone 5 or 5S or 5C")
randomH = Int(arc4random_uniform(520))
randomW = Int(arc4random_uniform(300))
while randomH < 40 || randomW < 40
{
randomH = Int(arc4random_uniform(520))
randomW = Int(arc4random_uniform(300))
}
case 1334:
// print("iPhone 6 or 6S")
randomH = Int(arc4random_uniform(550))
randomW = Int(arc4random_uniform(300))
while randomH < 35 || randomW < 40
{
randomH = Int(arc4random_uniform(550))
randomW = Int(arc4random_uniform(300))
}
case 2208:
// print("iPhone 6+ or 6S+")
randomH = Int(arc4random_uniform(700))
randomW = Int(arc4random_uniform(350))
while randomH < 40 || randomW < 40
{
randomH = Int(arc4random_uniform(700))
randomW = Int(arc4random_uniform(350))
}
default:
print("unknown")
}
}
else if UIDevice().userInterfaceIdiom == .Pad {
switch UIScreen.mainScreen().nativeBounds.height {
case 1024:
//print("iPad Classic")
randomH = Int(arc4random_uniform(950))
randomW = Int(arc4random_uniform(700))
while randomH < 50 || randomW < 40
{
randomH = Int(arc4random_uniform(950))
randomW = Int(arc4random_uniform(700))
}
case 2048:
//print("iPad Retina")
randomH = Int(arc4random_uniform(700))
randomW = Int(arc4random_uniform(350))
while randomH < 100 || randomW < 100
{
randomH = Int(arc4random_uniform(700))
randomW = Int(arc4random_uniform(350))
}
default:
print("unknown")
}
}
btn.frame.origin = CGPoint(x: randomW, y: randomH)
}
// func to end the game when someone loses
func endGame() {
btn.hidden = true
scoreLabel.text = "\(score)"
if hiScore < score
{
hiScore = score
highScore.text = "\(hiScore)"
}
else
{
highScore.text = "\(hiScore)"
}
NSUserDefaults.standardUserDefaults().setObject(hiScore, forKey: "high")
scoreLabel.hidden = false
again.hidden = false
highScore.hidden = false
scr.hidden = true
game_over.hidden = false
fbBtn.hidden = false
twBtn.hidden = false
let audioPath = NSBundle.mainBundle().pathForResource("end", ofType: "mp3")!
do
{
try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath : audioPath))
player.play()
}
catch
{
}
}
func animating()
{
if counter < 5
{
counter += 1
}
startView.image = UIImage(named: "start-\(counter).png")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//gameOverLbl.hidden = true
scoreLabel.hidden = true
again.hidden = true
highScore.hidden = true
btn.hidden = true
game_over.hidden = true
game_over.hidden = true
fbBtn.hidden = true
twBtn.hidden = true
if watch1 == true
{
timer_anim = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: Selector("animating"), userInfo: nil, repeats: true)
watch1 = false
}
if NSUserDefaults.standardUserDefaults().objectForKey("high") != nil
{
var returnHigh = NSUserDefaults.standardUserDefaults().objectForKey("high") as! Int
hiScore = returnHigh
}
else
{
}
let audioPath = NSBundle.mainBundle().pathForResource("start", ofType: "mp3")!
do
{
try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath : audioPath))
player.play()
}
catch
{
}
self.bannerView.adUnitID = "ca-app-pub-8964973200415729/4584433890"
self.bannerView.rootViewController = self
var request:GADRequest = GADRequest()
self.bannerView.loadRequest(request)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/// to make the screen not rotate
override func shouldAutorotate() -> Bool {
return false
}
func keepPlaying()
{
score += 1
scr.text = "\(score)"
randomLocating()
if score < 5
{
seconds = 8
}
else
{
seconds = 5
}
if watch == true
{
timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("click1"), userInfo: nil, repeats: true)
}
watch = false
gameTimer.text = "\(seconds)"
}
func click1 ()
{
gameTimer.text = "\(seconds)"
if seconds == 0 && gameActive == false
{
timer.invalidate()
endGame()
btn.hidden = true
turn += 1
if turn == 1
{
admobInterstitial = createAndLoadInterstitial()
timerAds = NSTimer.scheduledTimerWithTimeInterval(1, target:self, selector: Selector("presentInterstitial"), userInfo: nil, repeats: false)
turn = 0
}
}
else if seconds == 1
{
btn.hidden = true
gameActive = false
}
else
{
btn.hidden = false
}
seconds -= 1
}
func createAndLoadInterstitial()->GADInterstitial {
var interstitial = GADInterstitial(adUnitID: "ca-app-pub-8964973200415729/8720255492")
///interstitial.delegate = self
interstitial.loadRequest(GADRequest())
return interstitial
}
func presentInterstitial() {
if let isReady = admobInterstitial?.isReady {
admobInterstitial?.presentFromRootViewController(self)
}
}
func interstitial(ad: GADInterstitial!, didFailToReceiveAdWithError error: GADRequestError!) {
print("interstitialDidFailToReceiveAdWithError:\(error.localizedDescription)")
admobInterstitial = createAndLoadInterstitial()
}
}
Simply change your turn counter. Instead of if turn == 1 change it to something else. Want an ad every 3 gameovers? Change it to 3. For example:
turn = turn + 1
if turn == 3 {
admobInterstitial = createAndLoadInterstitial()
timerAds = NSTimer.scheduledTimerWithTimeInterval(1, target:self, selector: #selector(ViewController.presentInterstitial), userInfo: nil, repeats: false)
turn = 0
}