Monday, November 4, 2019

Review of Endgames Made Easy.

Its great to get a review.

Carvalho Peter wrote In one pawn endgame problem there is an error . b6 would be replied with .....Ka6 and the only way to protect the pawn is Kc6 which results in stalemate. ....Kb8 by black is a blunder permitting Kb5 and the a5 pawn is lost losing. The correct winning technique is available in standard endgame book by Averbakh.

Unfortunately its not clear to me which position Peter is referring to.

This position would fit. However 1.b6 Ka6 would be met by 2.b7 Kxb7 3.Kb5 and wins as per other examples. If 2...Ka7 then 3.b8Q+ Kxb8 4.Kb6 wins.

Thanks Peter for bringing this up.

Readers are encouraged to engage with a review and I can respond on this blog.

Wednesday, August 14, 2019

My Favourite Chess Variants

What is a Chess Variant?

There are some quite interesting games played with a chessboard and pieces apart from chess. This is a not too serious look at these so-called chess variants.

Some of them can be played on the Internet Chess Servers. Here is an overview of some of them, including my favourites.

Some have very different rules than chess. Others have only a single rule change.

Why learn about Variants?

Playing a variant can be a light hearted form of entertainment after playing competitive chess. Some are easy to play, some can be highly complex.

Some variants have instructional value, especially for juniors. Some variants help teach the ability to see ahead and see around.

Types of Chess Variants

Some use all or some of the standard chess pieces. This book will mostly concentrate on those variants which use a standard chess board and do not need non-chess pieces.

There are many variants which use different types of boards. Some are not square. For example, they may be rectangular or Cross-shaped. A few are square though smaller than 8x8, while others are larger. This book will concentrate on variants you can play with a normal chessboard and set. In some cases an additional board or pieces are needed. You will not need to create new types of pieces or boards.

Most variants are two player games. Some are solitaire games, while others are multi-player.

Some variants require a lot of skill while others are much simpler than standard chess. Some variants have a chance element.

Overview of Rules

This is not an encyclopedia of the all the many chess variants. Many of the variants have variations in the rules. This book is not a reference of the rules. It is an overview of variants I have learned, mostly from word of mouth.

Included are:

  • Rules
  • Tips
  • and some sample games of some of the more interesting chess variants.

Knight and Four Pawns Puzzle

The White Knight moves to every square on the board, except those occupied or controlled by a Black pawn.

Nc2 Na3 Nb1

The Knight moves to b1.

Tricky King Pawn Openings

Understanding tricky openings can help you sometimes win quickly and avoid losing quickly. Sometimes its the other way round, either way they can be great fun.

The Open game (1.e4 e5) offers better chances for an early tactical skirmish than any other openings. Both players have made a first move that activates their pieces as much as possible. Its also likely both sides will castle quicker than after 1.d4.

This book is designed to give an overview of tricky openings. It is not meant to be an exhaustive analysis of every tricky opening. It is meant to make readers aware of some of the tricky openings that exist. You are encouraged to research openings in depth that you wish to play.

What Is A Tricky Opening?

Tricky openings vary in their soundness. Some offer equal chances, others are inferior against best play. Whether they are worth playing depends on the context. It depends on the strengths of the players, the time limit and the seriousness of the game. In unrated blitz games, it is worth playing any tricky opening that interests you. In games where rating points, tournament places etc are in stake, then whether to play a risky opening and which one may need to be made carefully.

Tricky openings can be introduced by either player. Some tricky openings can be met with even trickier responses.

Some players play the same opening over and over. This was more common in the pre-computer era. These days it sets you up to be met with well prepared opponents who have used databases and engines to study your tricky opening. If you vary your openings, you keep your opponent’s guessing. If you know you opening is someone who doesn’t bother preparing, then you may not need to.

What are some tricky openings?

Balanced, including symmetrical positions tend to lead to solid openings. Unbalancing the position, especially with gambits and sacrifices, tends to lead to tactical dynamic positions. Both sides castling kingside early is more likely to lead to a quiet game. Castling on opposite sides or one or both kings not castling at all, tends to lead to a more dynamic game. Open positions tend to more tactical than closed positions, though some closed positions can be quite tactical.

Why play tricky openings?

Tricky openings tend to lead to more interesting positions, at least in the early part of the game. You may play tricky openings just for fun. Playing tricky openings for fun can be especially good in social games or blitz games.

You may play tricky openings to practice your tactics and play in dynamic positions. They may help you understand the initiative better.

You may play tricky openings to increase your chances of winning. This is especially the case if your opponent knows less about the opening than you do!

You may want to be prepared if an opponent plays a tricky opening on you.

GM Nigel Short gave a lecture in Adelaide in 2016. His topic was the Evans gambit, which definitely falls in the category of tricky openings. He said to club players,
Don’t play something dull like the Berlin defence to the Lopez (1.e4 e5 2.Nf3 Nc6 3.Bb5 Nf6) which often leads to an early queen exchange. Play sexy chess.

Types of tricky openings

Tricky openings vary from lines where White is taking no risk at all, but play is tricky, to openings that take huge risk, like the crazy Halloween attack (1.e4 e5 2.Nf3 Nc6 3.Nc3 Nf6 4.Nxe5!?)

White and Black tricky openings

Either White or Black can initiate a tricky variation. Sometimes a tricky opening move can be countered with a tricky reply.

Inventing your own tricky openings

The more tricky opening moves you become familiar with, the easier it will be to stump your opponents with your own outrageous moves.

1.e4 e5 2.Nc3 Nf6 3.f4 d5 4.fxe5 Nxe4 5.d3

...Bb4

Offering a piece.

6.dxe4 Qh4+ 7.Ke2 Bxc3 8.bxc3

...Qg4+

Its equal. Don’t play 5...Bb4 if you don’t want a draw!

How I learned Chess

This is a memoir of some of the highlights of some of my chess experiences as a junior. I will take you on a journey from the time I learned the moves at the age of seven until I completed secondary school.

It is from an era before mobile phones, Internet, chess databases and chess engines. It was the days of black and white television and milk carts drawn by horses. It was when you could play correspondence chess without any concern an opponent may be getting assistance from a computer.

It happened in a time and place that formal chess coaching was almost non-existent. In those days people learned chess from books. It happened in a city with a library that was home to the world’s largest collection of chess books.

Its story of learning through books and magazines, through playing over master games, doing chess puzzles, playing blitz and correspondence chess, learning from one’s own mistakes and learning from others. For those on the path to improving their understanding of chess it may be possible to make a few insights.

It includes highlights of games from state Junior championships, national junior championships, club games, weekenders and other types of tournaments. Some games are rather unusual.

It includes games with various national champions, two world chess champions and a world correspondence chess champion.

My tournament experience began with the State Under 14 and includes the journey to the national junior title. Shortly after completed school I played overseas representing Australian in the first Asian Teams championship.

I was White against Steve Lewinsky, who was the State U16 champion.

1.d4 Nf6 2.c4 e6 3.Nc3 c5 4.d5 d6 5.Bg5 a6 6.e3 Be7 7.Bd3 exd5 8.cxd5 Nxd5 9.Nxd5 Bxg5 10.Nf3 Bg4 11.Qa4+ Bd7 12.Qe4+ Be7 13.Nxe7 Qxe7 14.Qxb7 Bc6 15.Qc8+ Qd8 16.Qg4 Qa5+ 17.Nd2 O-O 18.h4 Nd7 19.Qf5 g6 20.Qg5 Ne5 21.Be2 f5 22.h5 Rab8 23.hxg6 Nxg6 24.Qh6 Qc7 25.O-O-O

White has been attacking ferociously for some time.

...Bxg2? 26.Rh2

...Bd5

This pawn grab is not good. White could play Nc4 and Nxd6 or Rxd6 with a strong attack.

How to Write a Chess Program

There are a number of reasons why you may be interested in how a chess program is written:

  • You are learning programming and interested in learning something different.
  • You are a programmer who is interesting in developing their programming experience.
  • You are a chess enthusiast and would like to improve your chess by learning how chess programs work.
  • You are interested in developing a chess program and playing against it.
  • You are interested in developing a chess program and having it play other engines.

You do need to be an expert programmer to understand this book. The code is written as simply as possible. The code is designed to be simple even for intermediate and even novice programmers.

If you are not a programmer, but am interested in chess, this book may be of interest.

The book includes the source code for a complete chess engine. The program can be compiled using a freely downloadable compiler. You can alter the code and see if you can make it stronger.

The engine is strong enough to beat most social players.

Features of the engine include:

  • The ability to load positions.
  • The ability to play in chess engine tournaments, with programs such as Arena.
  • Its very fast.
  • It displays the best line of play for both sides.
  • Detects reality of opponent’s pieces.
  • Detects checkmate.
  • Detects draws by repetition, 50 move rule, statemate or reduction of material.

Evaluation

The engine evaluates elements of a position including:

  • Material.
  • Piece position.
  • King safety.
  • Pawn structure.
  • Passed pawns.

Search

The engine uses a standard alpha-beta minimax search including:

  • Cut offs.
  • Move ordering.
  • History moves,
  • Hash tables.
  • Extensions.
  • Reductions.
  • Capture search.

And much more…

*/
int knight_score[64] = 
{
	-30, -20, -10,  -8,  -8, -10, -20, -30,
	-16, -6,   -2,   0,   0,   -2, -6, -16,
	-8,   -2,   4,   6,   6,   4,   -2, -8,
	-5,   0,   6,   8,   8,   6,   0, -5,
	-5,   0,   6,   8,   8,   6,   0, -5,
	-10,   -2,   4,   6,   6,   4,   -2, -10,
	-20, -10,   -2,   0,   0,   -2, -10, -20,
	-150, -20, -10, -5, -5, -10, -20, -150
};
/*
The knight gets stronger as it approaches the centre. The knight tends to be very weak in a corner on the opponent’s side. It is likely to be trapped there.

The Joy of Chess Programming

This is a memoir of my experiences with creating my own chess engine. It begins with first experiences with computer chess from books, magazines, movies and dedicated chess computers.

I witnessed a player by the name of Grant Crocker, playing 1.e3 and forced ChessChallenger to reply with 1...f5 (the Dutch defence). He then quickly won with 2.Qh5+?! g6 2.Be2 ?! gxh5??? 3.Bxh5#.

It progresses to when I had enough knowledge to write an amateur engine and was able to compete in computer chess tournaments.

Eventually my engine was strong enough to reach about 2400 ELo strength. It is able to find Fischers ...Be6 in the famous Game of the Century in a fraction of a second.

It gives insights into how chess engines work and how they select a move.

There are numerous tips on how we human players can learn from how computers play.

There are a number of reasons why you may be interested in how a chess program is written.

If so, you may be interested in my book How to Write a Chess Program.

I have another book on computer chess called Think Like a Computer which includes a number of games with engines playing engines at a shallow depth. This illustrates how engines evaluate positions.

Think Like a Computer

Computer chess has had a large impact on chess in the last two decades. Players have access to databases containing millions of games , they can even look up games played by a potential opponent. The Internet allows players to play fast games against players all around the world. Games can be watched live as they are being played. I have written several books on computer chess.

Computer chess programs (or chess-engines) have become very strong. Not only can be used as practice, they can be used to analyse games or study openings. Books have been written on how a player can study with the assistance of a chess engine.

In the 1970s there was a popular chess book called Think Like a Grandmaster by Soviet GM Alexander Kotov. He later wrote Play Like a Grandmaster and Train Like a Grandmaster. He wrote from his own experience and other grandmasters he rubbed shoulders with. He wrote on tree of analysis, candidate moves, avoiding blunders, when not to analyse, positional ideas, endgames etc. He gave ordinary chess players an insight into the mind of a grandmaster. To some extent this book helped them to think like a grandmaster.

These days strong computer programs (called chess engines) are very strong indeed. The top engines currently have ELO ratings above 3500.They can often analyse faster and more reliably than strong grandmaster.

We have Think Like a Grandmaster so why not have Think Like a computer?

There are many things we can learn from the strengths and weaknesses of chess engines.

What can we learn from the way computers play?

The author has been writing his own hobby chess engines since the 1990s. This book is designed to impart knowledge gained from this experience to chess players of all levels.

Note that this book is not about using computers to practice with or study chess. Its about what chess-players can learn from how computers play chess. Its also for readers who may be curious to learn something about how computers play chess. You do not need to be computer programmer to learn from how computers play chess.

1.d4 Nf6 2.c4 g6 3.Nc3 d5 4.cxd5 Nxd5 5.e4 Nxc3 6.bxc3 Bg7 7.Nf3 c5 8.Be3 Qa5

9.Qd2

This is the main line, though StockFish prefers Bd2.

...O-O

StockFish likes this.

10.Bc4

This does not fit in with Nf3. The knight needs to be on e2. StockFish likes Rc1. One advantage is that allows Nc6 to be met by d5.

...Nc6

StockFish likes this.

Play Like a World champion series

This book is similar to the Rate Your Chess series. It uses a system I developed for coaching for private students. The reader selects a move to play from up to 4 choices. The score for each game is out of 100.

This series of books is based on the following World champions in chronological order.

  • Steinitz
  • Lasker
  • Capablanca
  • Alekhine
  • Euwue
  • Botvinnik
  • Smyslov
  • Tal
  • Petrosian
  • Spassky
  • Fischer
  • Karpov
  • Kasparov
  • Anand
  • Kramnik
  • Carlsen

Each book features a different world champion. How many of their moves can you guess?

  • 91-100 2500+
  • 81-90 2400 - 2499
  • 71-80 2200 - 2399
  • 61-70 2000 - 2199
  • 51-60 1800 - 1999
  • 41-50 1600 - 1799
  • 31-40 1400 - 1599
  • 21-30 1200 - 1399
  • 11-20 1000 - 1199
  • 0 -10 below 1000

The challenge is to increase your rating with each game!

You can read a sample of one of the books by clicking on an image.

Sunday, August 11, 2019

Tactics Move by Move

Hi, I have been around the block a few times and am an experienced Chess master and Chess coach.

I have seen a few tactics books in my day, and grew up on books like Fred Reinfeld's 1001 Checkmates and 1001 Winning Sacrifices. All the strong players I knew in those days had worked through quite a few tactical puzzles.

Why learn tactics?

The most important skill in chess is tactical skill. The stronger the player, the faster they can see tactics.

There are several ways in which tactics help your Chess skill.

  • You can win your opponent's pieces and even checkmate checkmate them with tactics. You can even use tactics to win all their pieces. This is my recommended strategy.
  • By seeing tactics that might happen, you can stop your opponent by winning all your pieces and checkmating you.
  • You learn to recognise positions that are tactically weak. This means you can reduce your chances of having tactical weaknesses.
  • You learn to recognise positions that are tactically strong. This means you can increase your chances of having tactical chances.

Avoiding Blunders

A point has been made that studying tactics will now help you so much. This is because you may only have a few tactical opportunities per game.

However, almost every move you have the chance of making a tactical blunder.

Tactical skill is invaluable in checking whether a move is safe or not, before you play it!

What features would I like to see in a tactics book?

Like with many things, there are pros and cons with different approaches. Here are some of the approaches I have used and why.

Do you have White at the bottom of a diagram or do you have the winning side at the bottom?

With a tactical book, I prefer the side to move at the bottom, just as in a real game you see the board from your side, not from White's side all the time.

What order do you put positions in?

Some books put them in random order. For example, a mate in 12 may be followed by a mate in one. This has the advantage that the reader needs to be on their toes. They don't know what to expect.

Some books group puzzles by theme. There may be different sections on Knight forks, Queen sacrifices etc.

Some books put them in approximate order of difficulty.

This is my preferred approach and the one used in this book.

Puzzles in Book 1 can be solved by seeing only 1, 2 or 3 moves ahead. This increases to 4, 5, 6 and more moves ahead in Book 2.

Where to put the answers?

Older books tended to put them in a separate section at the end of the book or chapter. This was annoying because you had to look up the answer and go back to the position.

Some older books and more recent ones, put the answer immediately after the position. One book I read put the answer on the same page. This is not a good idea if you want to have a crack at the answer.

A good idea is to have the position of one page and be able to see the answer on the next page.

Move by Move

You are only expected to find one move at a time, just like in a real game. This is different most puzzle books where you are given an entire line of play as the answer.

Visual Memory

An advantage of only having a diagram at the start of a sequence of moves, is the reader is encouraged to play through the moves in his mind and visualise the final position. This can help the ability to see ahead moves.

Summary of my idea of a great tactics book

  • Player to move at bottom of board.
  • Diagrams for each move.
  • Un-timed puzzles.
  • Positions from real games.
  • Positions not excessively difficult.
  • Answer on the next page.
  • Explanation of tactics.
  • Large diagrams, one per page.

1.Rxd4

Removing the defending bishop.

...cxd4 2.Nf6+

Sacrificing the knight to open the king up.

...gxf6 3.Qh6

Mate threat.

...Kh8 4.Qg7#

Tactical Patterns Made Easy

Tactics are very important in Chess. How to spot winning material and other tactics?

There are 850+ large clear color diagrams.

Chess has relatively easy rules but is potentially a game of great complexity. The complexity is achieved by the large number of ways the simple elements can be combined. The number of possibilities increases geometrically with the number of units on the board.

Pattern recognition

There are many tactical pattern which happen again and again in games. Skilled players are familiar with many patterns and themes, through both play and study. This familiarity allows players to spot tactics much quicker than they would otherwise. There is a strong correlation between playing strength and how quickly a player can find tactics.

The book starts with a fresh look at the simple elements of chess and how they can be put together. Elements include the chessboard itself and the basic functions of the units. Types of patterns are explained. The last section contains a large number of common tactical patterns.

Types of patterns include attack, checkmate, ways to draw and ways to win material. Drawing patterns include stalemate patterns and perpetual check patterns. Patterns involved in winning material include Forks, Pins, Skewers, Discoveries, Nets, Ties and Discoveries. Saves are also examined.

This book includes many positions that have been collected for coaching purposes over many years. The book is designed to help the reader to quickly become familiar with many tactical patterns. It may also help refresh familiarity with tactical patterns that have been previously seen, but partly forgotten.

Positions

The positions have been invented. In many cases they have been simplified and have few units on the board which are not involved in tactic being presented. In many cases they are fragments of positions, one or more Kings may be missing. However they are are very similar to positions from actual play and are quite unlike composed positions.

Diagrams

In all positions White moves first and White is playing up the board. Moves are numbered from the current position, not from the start of the game.

There are different ways you can read this book.

  • You can treat the positions as puzzles. You can choose the move you would play and move to the next diagram to check whether you are correct or not.
  • You can simply enjoy playing through through the positions, becoming familiar with a wide range of tactical patterns as you do so. You can quickly flip forwards (or backwards) through the sequence of moves in each position.
  • You can combine both approaches. For example, during a first reading you could play through the positions. On a second reading you could see how many you can solve from the starting position.

Double Pin

Sometimes a piece may be pinned in 2 directions. This is a double pin. The black Rook is pinned in two directions. It is both pinned to the King and the Queen.

After 1.Qf8

Attacking the King Made Easy

The book draws from a collection of many positions that the author has used in years of chess coaching.

Attacking the King is highly important. It may win the game by checkmate or lead to a decisive gain of material.

Middlegame attacks can be divided into 3 main types:

  • Attack on the uncastled king.
  • Attack on the same side castled king.
  • Attack on the opposite side castled king.
The book covers back rank attacks, pawn storms, piece sacrifices and much more.

White starts by preparing to open the h-file.

1.h5 Nxh5

White sacrifices the exchange to open the g-file.

1.Rxh5! gxh5 2.Qg5

Qxg7# cannot be prevented.

Diagrams

There are over 1200 large clear color chess diagrams. In all positions White moves first and White is playing up the board.

There are different ways you can read this book.

  • You can treat the positions as puzzles. You can choose the move you would play and move to the next diagram to check whether you are correct or not.
  • You can simply enjoy playing through through the positions, becoming familiar with a wide range of mating patterns as you do so. You can quickly flip forwards (or backwards) through the sequence of moves in each position.
  • You can combine both approaches. For example, during a first reading you could play through the positions. On a second reading you could see how many you can solve from the starting position.
The second most powerful move after check is a mate threat. One section consists of positions in which attacking moves consist of checks and/or mate threats.

Checkmate Made Easy

The book draws from many positions that the author, I have used in years of chess coaching.

There is only one real way to win a game of chess. That is to the checkmate the king. Players often resign, but only because they think they will be checkmated eventually anyway.

A mate may come as a single move, like a bolt from the blue. These are mates in one. More often there is a 'mating attack' consisting of a sequence of alternating checks and check evasions. The final check is mate.

A check is the most powerful move in Chess. The most powerful way to attack is to connect a series of checks.

There are over 1000 diagrams which include mates in one, mates in two, mates in three and mates in four or more moves by each player.

Pattern recognition

There are many mating pattern which happen again and again in games. Strong players are familiar with many mating patterns and themes, through both play and study. This familiarity allows players to spot mates much quicker than they would otherwise. There is a strong correlation between playing strength and how quickly a player can find forced mates.

This book includes many positions that have been collected for coaching purposes over many years. The book is designed to help the reader to quickly become familiar with many mating patterns. It may also help refresh familiarity with mates that have been previously seen, but partly forgotten.

Positions

The positions have been invented. However they are are very similar to positions from actual play and are quite unlike composed positions. In many cases they have been simplified and have few units on the board which are not involved in the mating attack.

Diagrams

There are over 1000 large clear colour chess diagrams. In all positions White moves first and White is playing up the board. Moves are numbered from the current position, not from the start of the game.

There are different ways you can read this book.

  • You can treat the positions as puzzles. You can choose the move you would play and move to the next diagram to check whether you are correct or not.
  • You can simply enjoy playing through through the positions, becoming familiar with a wide range of mating patterns as you do so. You can quickly flip forwards (or backwards) through the sequence of moves in each position.
  • You can combine both approaches. For example, during a first reading you could play through the positions. On a second reading you could see how many you can solve from the starting position.
The second most powerful move after check is a mate threat. The last section consists of positions in which attacking moves consist of checks and/or mate threats.

The attacker checks to force the defender to block an opponent unit that is defending mate. 1.Bf6+ Rg7 2.Re8#

Endgames Made Easy Books 1-5

The complete set of Endgames Made Easy is:
  1. Basic Concepts
  2. Lone King Endgames
  3. Pawn Endgames
  4. Pieces versus Pawns
  5. Piece Endgames

To play endgames strongly you do not need to know thousands of positions. A good understanding of basic principles, knowledge of some key positions and the ability to calculate well will go a long way.

Introduction

The largest difference in strength between the amateur and master is in the endgame. Its my observation after many years of playing and coaching that average club players typically have major gaps in their basic endgame knowledge.

To play endgames strongly you do not need to know thousands of positions. A good understanding of basic principles, knowledge of some key positions and the ability to calculate well will go a long way.

The book draws from many endgame examples that I have used in years of chess coaching.

Some players make an interesting point, why study the ending if I don't get many? Well, there is lots of reasons. The number of endings will increase as general playing strength increases. This is because players increase their ability to survive middlegames. The number of endgames will also increase if playing more evenly matched opponents. If neither player makes tactical mistakes, then an endgame is very likely.

Even if you don't have an ending, endgame study may create ideas useful for the middlegame, especially positional ideas. Because you have so few pieces, placement of the pieces becomes all that more important.

More importantly, you will know what endings to aim for. In many games between good players, one or both players has had option to exchange into ending at some point. If your ending understanding is weak, how will you know when to exchange and when not to?

Playing for an ending, is sometimes the best way to exploit a positional advantage in pawn structure. With fewer pieces on, active piece play is less likely to compensate for weak squares and weak pawns.

Basic Concepts

Book 2 covers basic endgame concepts. For example:
Stalemate Combinations
Sometimes the weaker side can stalemate themselves by sacrificing their last piece or pieces. If one side has no possible Pawn moves, beware of stalemate. White sacrifices his last piece.

After 1.Rf3+

It is a draw.

Lone King Endgames

Book 2 covers lone king endgames. Lone King endgames are endgames in which one side only has a King. Some are instant draws. Some are draws with best play while others are a win for the stronger side with best play.

King versus King, Knight versus King or Bishop versus King is an instant draw. No checkmate is possible.

Rook versus King or Queen versus King is a win with best play.

Two bishops versus King is a win with best play.

Knight and Bishop versus King is a win with best play.

Two knights versus King is a draw with best play.

One or more pawns versus King is sometimes a draw with best play, sometimes a win.

Minor piece (knight or bishop) plus pawn is sometimes a draw with best play, sometimes a win.

Checkmate a lone King, drive it to the edge, or better still, the corner. Be careful not to stalemate. Your pieces need to work as a team, endless checks will get you nowhere.

When attempting to queen a pawn, use your pieces to help the pawn by controlling the path of the pawn.

Pawn Endgames

Book 3 covers pawn endgames. Note that One or two pawns against a lone King is covered in Book 2 and some key concepts like opposition are covered in Book 1.

Pawn endgames are the most common type of endgame. Most endgame positions which have at least one pawn on the board can potentially transform into a pawn endgame. One exception is a bishop of opposite colours endgames as the bishops are unlikely to be exchanged.

Despite there only being Kings and pawns on the board, some pawn endings are quite tricky.

There are some key ideas which may be highly valuable.

Piece Endgames

Book 4 covers pieces versus pawns. Pieces vary greatly in their ability to stop several passed pawns. Sometimes a piece can stop or win one or more passed pawns. Other times one passed pawn can tie down a piece.

Piece Endgames

Book 5 covers key positions and principles in different piece and pawn endgames. These include endgames with:
  • Rooks
  • Knight Versus Bishop
  • Knights
  • Bishops Of Same Colours
  • Bishops Of Opposite Colours
  • Rook Versus Minor Piece/s
  • Queen Endings
  • Queen Versus Pieces
There are also general tips and other ideas.

Sunday, August 4, 2019

Optimise your Chess Thinking

Optimise means to make better. In practice even just making something better will be very useful.

We optimise our computers. We defragment fragmented files and delete unused ones. We make computers faster and more efficient. Why not optimise our own thinking? We want to think positive thoughts that serve us, not negative thoughts that are destructive to us.

Chess is a game of thinking. The more optimal our chess thinking is, the better we will play, At the very least, we will play the same moves, but more quickly. Moving quicker has certain practical advantages.

Chapters are:

  • Introduction
  • What is Chess Skill?
  • Optimise Your Chess Vision
  • Optimise Your Static Analysis
  • Optimise Your Calculation
  • Optimise Your Evaluation
  • Optimise Your Positional Play
  • Optimise Your Move Checking
  • Optimise Thinking on Your Opponent’s Time
  • Optimise Your Openings
  • Optimise Your Endgames
  • Optimise Your Concentration
  • Optimise Your Practical Chances
  • Optimise Your Study Time

1.Qxg6 hxg6 2.Bxf7+ Rxf7 3.Rh8+ Kxh8 4.Nxf7+ Kg8 5.Nxd6

Generally the longer the variation the more challenging it is to visualise the resulting position. However a long simple variation might be easier to visualise than a short complex one. A simple 12 ply variation where only one unit on each side is moved involves only 4 pieces of information while a complex 4 ply sequence involving 4 captures by 4 different units involves 8 + 4 = 12 pieces of information.

Of course you don't need to know the number of pieces of information you need to remember, its just calculated here to illustrate how the task may vary in difficulty.

The number of variations that are examined will vary greatly from move to move and from player to player.

In general the more quickly a position can be visualised the better. Its often desirable to remember the moves in a variation. However, this is a different task than visualising, and will be covered later.

Chess Concepts Made Easy

Chess is a game of ideas. There are many tactical and strategical ideas that can help a player select a move or plan. There are important ideas, concepts, themes and patterns for the opening, middlegame and endgame phase. Experienced players develop a very good understanding of many of these.

Many of these ideas are explained using diagrams, text and examples.

This book is designed to be most useful for the bulk of players who are rated between about 1200 and 1800. The aim of the book is to help the reader improve his play by deepening his understanding of chess, though of course it can be purely read for entertainment value. Strong players may find useful ideas which will help them find good moves more quickly. It has been said all grandmasters will find a mate in 8, but some will find it more quickly than others. The quicker you find good moves, the better.

For maximum benefit, reread the book several times. On subsequent readings you will grasp points that were previously obscure to you and your understanding will be deepened. Its not critical to read it in any particular order.

Emanuel Lasker once claimed he could take a young man of average ability and coach him to candidate master strength (about 2000 ELO) in the space of about 120 hours. Although this has not been proven possible, he has made a valid point that many people learn chess in a haphazard fashion and don't make the best use of their chess learning time. A good aim is to learn as much as you can with the time you can allow for chess.

The book will cover material that the reader doubtless has some familiarity with already. Some prior knowledge is presumed and the reader will be reinforcing and building on what is already understood. Hopefully though, it will help you look at things in a different light.

This knowledge can be very useful. By comparing the current position in your game with known precedents, you can come up with the right plan.

But what if you don't know a familiar precedent? What you need, is a plastic method that can be applied to any situation. One chapter concentrates on the method that is used to select a move. The method will alter according to circumstances, particularly in the endgame, but can be useful in all situations. There are 2 basic aims in chess are:

  • To checkmate the King.
  • To avoid being checkmated.
To attempt to achieve these aims you maximise your ability to checkmate, win material and promote pawns while minimising your opponent's ability to do the same. With correct play by both sides, a game will end in a draw. You cannot win until the opponent has made one or more mistakes.

Chapters

  • Tactics describes the common types of tactical devices and many tactical concepts.
  • Positional Play describes many positional concepts.
  • Endgames describes endgame concepts and many of the more common endings.
  • Openings describes opening concepts.
  • The Method discusses approaches to selecting a move.
  • Practical Play discusses practical play.

After 1.Bc3 a curious thing happens. Black cannot unpin without losing a Rook for nothing.

Unbreakable Pin

Sometimes a pin cannot safely be broken.

Opening Strategy Made Easy

This book has many large clear color diagrams. You do not need a chess set and board to read this book. You do need to know how to read standard chess notation.

Introduction

It is important to get off to a good start in the opening. Where should you place your pieces?

There are about 8 million possible positions after a mere 8 half moves (4 moves by each player.) There are many known opening lines. Understanding of ideas is more valuable than memorisation of specific moves. Ideas can often be applied in different situations. It does not matter how much opening theory you know, you will always get into opening positions you have never reached before. The ability to improvise is invaluable. In many games played as a master chess player I have found strong moves in opening positions I have never been before.

This book includes an overview of many types of pawn formations and in many cases examples of where to place your pieces in each case.

Stonewall Formation

White has a strong formation of pawns at the cost of a weak e4 square and a bad dark squared bishop.

Thursday, July 18, 2019

Opening Moves Made Easy

Its important to get off to a good start in a Chess game. Both sides start in a weak position, most pieces cannot move and the Kings need to get castled.

Most opening books concentrate on showing concrete variations. One shortcoming of knowledge of a concrete variation is that a move might be valid in one position, but even if another position has only one small difference then the same move may be a terrible blunder.

Another difficulty of memorization is the huge possible number of opening positions. Even after only a few moves there are many millions of possibilities. This book offers an alternative approach.

Understanding of ideas is more valuable than memorization of specific move sequences. Ideas can often be applied in different situations. It does not matter how much opening theory you know, you will always get into opening positions you have never reached before. The ability to improvise is invaluable.

There is an article titled 'My First Chess Tournament' on the Melbourne Chess Club website by a committee member, Simon Dale. His son Ari is now an IM (International Master). Here is part of his article.

I was most nervous about losing in 10 moves, so I asked Bill Jordan, a coach at Melbourne Chess Club, to show me chess openings. I am well known at the club because of my children and I am a volunteer committee member, so Bill was very happy to help. His one hour accelerated opening course was about opening principles, he did not teach me a single opening, but rather gave me confidence to just play with general ideas. This was brilliant because I did not have to learn anything and had the bonus of taking the experienced players out of theory pretty quickly. In my opinion this was a very solid approach for the beginner. This book is inspired by that lesson.

Opening Principles

The book examines standard opening principles and explores their strengths and weaknesses.

Opening Moves

This book examines likely moves in the opening, including the 20 possible moves in the initial position. It looks at the strong and weak points of each move. This is he bulk of the book. There are numerous example positions from real openings.

c3

  • Controls b4.
  • Controls d4.
  • No longer controls the b3 and d3 squares.
  • Obstructs the Queen Knight from its best square.
  • Opens a new diagonal for the Queen.

c3 defends d4 and opens a diagonal for the Queen.

This book has over 250 large clear colour diagrams. You do not need a chess set and board to read this book. It is designed to be read several times. Each time it is reread, you may grasp points that were previously obscure to you. Enjoy!

Friday, July 12, 2019

Opening Traps Book 1 and 2

Opening Traps

Playing through opening traps can be a lot of fun.

Also learning them gives you the opportunity to try them on your opponents.

Studying them also helps prevent you from falling into them.

As a FIDE master and chess coach I recommended studying opening traps as a good way for new players to learn openings beyond the basics. You can view my author for information about my other books.

Not only does studying opening traps help you develop familiarity with openings in general, it can also help develop your tactical skill in the middlegame and endgame. It is one more step that you can take towards being a tactical wizard.

This book uses hundreds of large clear color chess diagrams. The winning side will play up the board. You do not need a chess set to read this book.

This is Book 1 of a set of 2.

Book 1

This book concentrates on common basic tactical patterns. Variations of these patterns happen in many ways. To help you learn the patterns better, only relevant pieces will be present. The more tactical patterns and themes you are familiar with, the easier it will be for you to see tactics.

There are traps involving the King, including checks on the short diagonal, long diagonal, file, rank and by a Knight.

The Queen mates on the short diagonal.

These traps may involve checkmate or win of material by using tactical devices such as:

  • Forks
  • Pins
  • Skewers
  • Discoveries
  • etc.

There are traps not involving the King, including forks, trapped pieces etc.

Book 2

This book consists of a collection of hundreds of short games with brief notes. Most of these games I have either played or watched while they were being played, over several decades. Some are famous games. In some cases the games have been played more than once. Some games include well known opening traps, some with names, others without. Games are in approximate alphabetical order of their moves. This means that openings are grouped together.

1.d4 b5 2.e4 a6 3.c4 Bb7 4.f3 bxc4 5.Bxc4 e6 6.Qb3 Nc6

Setting the trap.

7.Qxb7?

...Na5

Trapping the Queen.

You can either play through them and guess the next move of the winning side or simply play through them. The level of games varies from being one move deep up to more than 10 moves deep. There are traps that masters have fallen into.

Thursday, July 11, 2019

Chess Basics Made Easy

The rules of chess are not especially complicated. They can be explained in 10 minutes and memorised in about an hour. One chessboard and a chess set of 32 chess pieces is used. Chess is a two player game. The player taking the white pieces is called White, while the player taking the black pieces is called Black.

Acoustics is the science of sound.
Music is the art of creating beauty from sound.
Mathematics is the science of logic.
Chess is the art of creating beauty from logic.

Every square, except the corners, is intersected by two diagonals. They are never equal in length. Two diagonals intersect the d4 square. The a1-h8 diagonal is the long diagonal, while the g1-a7 diagonal is the short diagonal.

The rules and basics of Chess are explained using diagrams, text and examples.

If you already know the rules, this book will help to reinforce your knowledge of the basics.

Topics include:

  • The Chessboard
  • Chess Notation
  • The Chess Pieces
  • Moves
  • Captures
  • Promotion
  • How to win
  • Castling
  • Drawing
  • Basic functions of the pieces
  • Values of the pieces
  • Types of Moves
  • Tactics
..and much more.

The book teaches and uses standard chess notation, which is short Algebraic notation.

My chess books

My Chess Books

This is an introduction to some of the Kindle chess books I have written.

They are all available at Amazon. Some of them are available at Barnes&Noble and Apple.

Look Inside

At Amazon you can double-click on the cover to Look Inside the book. This allows you to sample the first 10% of a book. Line breaks which are in the full version, are removed in the Look Inside version.

All books use standard chess notation, which is short Algebraic notation.

Except for Chess Basics Made EasyIt is presumed the reader has familiarity with chess rules and Algebraic notation.

Diagrams

Most of the books have many clear colour diagrams. A few have black and white diagrams.

Paperbacks

Some of these are available as paperbacks at Amazon.

Level of books

This is a rough guide to what level of player books may be suitable for. There is nothing to stop you reading any book.

Intermediate level is between novice level average club player or strong social player level.

Average club level is about 1300 - 1800 ELO. Note that ratings on some websites where you can play chess can be inflated by hundreds of points.

Chess Basics Made Easy is aimed at novice players.

Checkmate Made Easy is aimed at intermediate players.

Attacking the King Made Easy is aimed at intermediate players.

Chess Concepts Made Easy is aimed at intermediate players.

Tactical Patterns Made Easy is aimed at intermediate players.

Opening Moves Made Easy is aimed at intermediate players.

Opening Traps is aimed at intermediate players.

Opening Traps 2 is aimed at intermediate to average club players.

Opening Strategy Made Easy is aimed at intermediate to average club players.

Tactics Practice Book 1 series is aimed at intermediate players.
Tactics Practice Book 2 series is aimed at average club players.

The Endgames Made Easy series is aimed at intermediate to average club players.

Tricky King Pawn Openings is aimed at intermediate to average club players.

The Rate Your chess and Play Like a World Champion series are designed for players of any level.

How I Learned chess is designed for players of any level.

Optimise your Chess Thinking is designed for players of any level.

The Computer Chess books are designed for anyone interested in computer chess.

The My Favourite Chess Variants is designed for anyone interested in chess variants.

Saturday, May 4, 2019

main.cpp

#include "stdafx.h"
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>

#include <iostream>

#include <sys/timeb.h>

#include "globals.h"

void ShowHelp();
void SetUp();

bool ftime_ok = false;  /* does ftime return milliseconds? */
//
void xboard();

//diagram stuff
int LoadDiagram(char* file,int);
int GetSquare(char file,char rank);
int GetPiece(char b);

int pos[100][3][16][3];
int startpos[100];
int diag_number;

int ponder;

FILE *diagram_file;
char fen_name[256];

int flip = 0;

int number=0;

int computer_side;
int player[2];

int fixed_time;
int fixed_depth;
int max_time;
int start_time;
int stop_time;
int max_depth;
int turn = 0;

void print_result();
void NewGame();

void SetMaterial();

int get_ms()
{
struct timeb timebuffer;
ftime(&timebuffer);
if (timebuffer.millitm != 0)
ftime_ok = true;
return (timebuffer.time * 1000) + timebuffer.millitm;
}

char *move_str(int start,int dest,int bits,int promote)
{
static char str[6];

char c;

if (bits & 32) {
switch (promote) {
case N:
c = 'n';
break;
case B:
c = 'b';
break;
case R:
c = 'r';
break;
default:
c = 'q';
break;
}
sprintf_s(str, "%c%d%c%d%c",
col[start] + 'a',
row[start] + 1,
col[dest] + 'a',
row[dest] + 1,
c);
}
else
sprintf_s(str, "%c%d%c%d",
col[start] + 'a',
row[start] + 1,
col[dest] + 'a',
row[dest] + 1);
return str;
}

int main()
{
printf("\n");
printf("Bills bare bones chess engine\n");
printf("bv 8, 18/7/18\n");
printf("Copyright 2018 Bill Jordan \n");
printf("\n");
printf("\"help\" displays a list of commands.\n");
printf("\n");

char s[256];
char sFen[256];
char sText[256];
int m;
int turns=0;
int editmode=0;
int analyze=0;
int np=0;
int edit_color=0;
int sq=0;
int t;
int lookup;

double nps;

fixed_time = 0;

SetUp();

while(true)
{
diag_number=0;
if (side == computer_side)

player[side] = 1;
think();
turns++;

currentkey = GetKey();
currentlock = GetLock();
lookup = LookUp(side);
if(lookup != 0)
{
   printf("\n lookup %d ",lookup);
   Alg(hash_start,hash_dest);printf("\n");
}
else
{
printf("(no legal moves)\n");
computer_side = EMPTY;
print_board();
Gen();
continue;
}       

printf("\n hash %d ",hashpositions[0]);
printf(" hash %d ",hashpositions[1]);
printf(" collisions %d ",collisions);
printf("\n");
collisions = 0;

printf("Computer's move: %s\n", move_str(hash_start,hash_dest,0,0));printf("\n");
MakeMove(hash_start,hash_dest);

SetMaterial();

t = get_ms() - start_time;
printf("\nTime: %d ms\n", t);
    if(t>0)
      nps = (double)nodes / (double)t;
    else
      nps=0;
nps *= 1000.0;

printf("\nNodes per second: %d\n", (int)nps);
ply = 0;

first_move[0] = 0;//11/12/12
Gen();
print_result();

    printf(" turn "); printf("%d",turn++);
print_board();
continue;
}
printf("Enter move or command> ");
if (scanf("%s", s) == EOF)
return 0;
if (!strcmp(s, "quit"))
    {
printf("Program exiting\n");
break;
}
if (!strcmp(s, "go"))
    {
computer_side = side;
continue;
}
   if (!strcmp(s, "sb"))
   {
sFen[0] = 0;
strcat_s(sFen,"c:\\bscp\\");//
        scanf("%s", sText);
strcat_s(sFen,sText);
        strcat_s(sFen,".fen");
LoadDiagram(sFen,1);
continue;
}
if (!strcmp(s, "on") || !strcmp(s, "p")) {
computer_side = side;
continue;
}
if (!strcmp(s, "off")) {
computer_side = EMPTY;
continue;
}
        if (!strcmp(s, "random")) {
continue;
}
if (!strcmp(s, "st")) {
scanf("%d", &max_time);
max_time *= 1000;
max_depth = MAX_PLY;
fixed_time = 1;
continue;
}
if (!strcmp(s, "sd")) {
scanf("%d", &max_depth);
max_time = 1 << 25;
fixed_depth = 1;
continue;
}
if (!strcmp(s, "undo")) {
if (!hply)
continue;
computer_side = EMPTY;
TakeBack();
ply = 0;
if(first_move[0] != 0)
first_move[0] = 0;
Gen();
continue;
}
if (!strcmp(s, "new"))
{
NewGame();
computer_side = EMPTY;
continue;
}
if (!strcmp(s, "d")) {
print_board();
printf("\n key %d ",currentkey);
printf("\n lock %d ",currentlock);
continue;
}
        if (!strcmp(s, "f")) {
flip = 1 - flip;
            print_board();
continue;
}
        if (!strcmp(s, "sw")) {
        side = 1-side;
            xside = 1-xside;
continue;
}
        if (!strcmp(s, "moves")) {   
printf("Moves \n");
            move *g;
            for (int i = 0; i < first_move[1]; ++i)
            {
g = &move_list[i];
printf("%s",move_str(move_list[i].start,move_list[i].dest,0,move_list[i].promote));
printf("\n");
            }
continue;
}
if (!strcmp(s, "sb")) {
sFen[0] = 0;
strcat_s(sFen,"c:\\bscp\\");//
            scanf("%s", sText);
strcat_s(sFen,sText);//
            strcat_s(sFen,".fen");
LoadDiagram(sFen,1);
continue;
}
if (!strcmp(s, "bye")) {
printf("Share and enjoy!\n");
break;
}
if (!strcmp(s, "xboard")) {
xboard();
break;
}     
if (!strcmp(s, "help")) {
ShowHelp();
continue;
}

/* maybe the user entered a move? */
ply = 0;
  if(first_move[0] != 0)
      first_move[0] = 0;
Gen();
  m = parse_move(s);
if (m == -1 || !MakeMove(move_list[m].start,move_list[m].dest))
{
printf("Illegal move. \n");
printf(s);printf(" \n");
move_str(move_list[m].start,move_list[m].dest,0,move_list[m].promote);
if (m == -1)printf(" m = -1 \n");
}
if(game_list[hply].promote >0 && (row[move_list[m].dest]==0 || row[move_list[m].dest]==7))
{
RemovePiece(xside,Q,move_list[m].dest);
if(s[4]=='n' || s[4]=='N')
AddPiece(xside,N,move_list[m].dest);
else if(s[4]=='b' || s[4]=='B')
AddPiece(xside,B,move_list[m].dest);
else if(s[4]=='r' || s[4]=='r')
AddPiece(xside,R,move_list[m].dest);
else AddPiece(xside,Q,move_list[m].dest);
}
}
    Free();
return 0;
}

/* parse the move s (in coordinate notation) and return the move's
   indx in move_list, or -1 if the move is illegal */

int parse_move(char *s)
{
int start, dest, i;

if (s[0] < 'a' || s[0] > 'h' ||
s[1] < '0' || s[1] > '9' ||
s[2] < 'a' || s[2] > 'h' ||
s[3] < '0' || s[3] > '9')
return -1;

    start = s[0] - 'a';
    start += ((s[1] - '0') - 1)*8;
    dest = s[2] - 'a';
    dest += ((s[3] - '0') - 1)*8;

for (i = 0; i < first_move[1]; ++i)
if (move_list[i].start == start && move_list[i].dest == dest)
        {
return i;
    }
return -1;
}
/* print_board() prints the board */

void print_board()
{
int flip = 0;
int i, x=0;

printf("\n8 ");
    if(flip==0)
    {
for (int j = 0; j < 64; ++j)
    {
        i = Flip[j];
        {
    switch (color[i])
        {
case EMPTY:
                if(x==0)
printf(" .");
                else
                printf(". ");
break;
case 0:
            if(x==0)
printf(" %c", piece_char[board[i]]);
                else
                printf("%c ", piece_char[board[i]]);
break;
case 1:
            if(x==0)
printf(" %c", piece_char[board[i]] + ('a' - 'A'));
                else
                printf("%c ", piece_char[board[i]] + ('a' - 'A'));
break;
default:
if(x==0)
printf(" %d.",color[i]);
                else
                printf(".%d ",color[i]);
break;
}
if((color[i]==0 || color[i]==1) && board[i]==6)
if(x==0)
printf(" %d",color[i]);
        else
            printf("%d ",color[i]);
if(board[i]<0 || board[i]>6)
if(x==0)
printf(" %d.",board[i]);
        else
            printf("%d ",board[i]);
        }
if ((j + 1) % 8 == 0 && j != 63)
printf("\n%d ", row[i]);
}
printf("\n\n   a b c d e f g h\n\n");
    }

     if(flip==1)
    {
  for (int j = 0; j < 64; ++j) {
        i = 63-Flip[j];
switch (color[i])
{
case EMPTY:
printf(" .");
break;
case 0:
printf(" %c", piece_char[board[i]]);
break;
case 1:
printf(" %c", piece_char[board[i]] + ('a' - 'A'));
break;
}
if ((j + 1) % 8 == 0 && row[i] != 7)
printf("\n%d ",  row[j]+2);//7-
}
printf("\n\n   h g f e d c b a\n\n");
    }
}

/* xboard() is a substitute for main() that is XBoard
   and WinBoard compatible. See the following page for details:
   http://www.research.digital.com/SRC/personal/mann/xboard/engine-intf.html */

void xboard()
{
int computer_side;
char line[256], command[256];
int m;
int post = 0;
int analyze = 0;
int lookup;

signal(SIGINT, SIG_IGN);
printf("\n");
NewGame();
fixed_time = 0;
computer_side = EMPTY;
   
while(true)
{
fflush(stdout);
if (side == computer_side)
{
think();
SetMaterial();
Gen();
currentkey = GetKey();
currentlock = GetLock();
lookup = LookUp(side);

move_list[0].start = hash_start;
            move_list[0].dest = hash_dest;
     
printf("move %s\n", move_str(hash_start,hash_dest,0,0));

MakeMove(hash_start,hash_dest);
 
ply = 0;
Gen();
print_result();
continue;
}
if (!fgets(line, 256, stdin))
return;
if (line[0] == '\n')
continue;
sscanf(line, "%s", command);
if (!strcmp(command, "xboard"))
continue;
if (!strcmp(command, "new"))
{
NewGame();
computer_side = 1;
continue;
}
if (!strcmp(command, "quit"))
return;
if (!strcmp(command, "force"))
{
computer_side = EMPTY;
continue;
}
if (!strcmp(command, "white"))
{
side = 0;
xside = 1;
Gen();
computer_side = 1;
continue;
}
if (!strcmp(command, "black"))
{
side = 1;
xside = 0;
Gen();
computer_side = 0;
continue;
}
if (!strcmp(command, "st"))
{
sscanf(line, "st %d", &max_time);
max_time *= 1000;
max_depth = MAX_PLY;
fixed_time = 1;
continue;
}
if (!strcmp(command, "sd"))
{
sscanf(line, "sd %d", &max_depth);
max_time = 1 << 25;
continue;
}
if (!strcmp(command, "time"))
{
sscanf(line, "time %d", &max_time);
if(max_time < 200)
  max_depth = 1;
else
{
max_time /= 2;
max_depth = MAX_PLY;
}
continue;
}
if (!strcmp(command, "otim"))
{
continue;
}
if (!strcmp(command, "go"))
{
computer_side = side;
continue;
}
if (!strcmp(command, "random"))
continue;
if (!strcmp(command, "level"))
continue;
if (!strcmp(command, "hard"))
continue;
if (!strcmp(command, "easy"))
continue;
if (!strcmp(command, "hint"))
{
think();
currentkey = GetKey();
currentlock = GetLock();
lookup = LookUp(side);
if(hash_start==0 && hash_dest==0)
continue;
printf("Hint: %s\n", move_str(hash_start,hash_dest,0,0));
continue;
}
if (!strcmp(command, "undo"))
{
if (!hply)
continue;
TakeBack();
ply = 0;
Gen();
continue;
}
if (!strcmp(command, "remove"))
{
if (hply < 2)
continue;
TakeBack();
TakeBack();
ply = 0;
Gen();
continue;
}
if (!strcmp(command, "post"))
{
post = 2;
continue;
}
if (!strcmp(command, "nopost"))
{
post = 0;
continue;
}
first_move[0] = 0;
Gen();

m = parse_move(line);
if (m == -1 || !MakeMove(move_list[m].start,move_list[m].dest))
printf("Error (unknown command): %s\n", command);
else
{
ply = 0;
  Gen();
print_result();
}
}
}

void NewGame()
{
InitBoard();
    first_move[0] = 0;
turn = 0;
fifty = 0;
ply = 0;
hply = 0;
Gen();
}

void print_result()
{
int i;
    int flag=0;

SetMaterial();
Gen();
for (i = 0; i < first_move[1]; ++i)
if (MakeMove(move_list[i].start,move_list[i].dest))
        {
TakeBack();
            flag=1;
break;
}

    if(pawn_mat[0]==0 && pawn_mat[1]==0 && piece_mat[0]<=300 && piece_mat[1]<=300)
    {
printf("1/2-1/2 {Stalemate}\n");
NewGame();
computer_side = EMPTY;
return;
    }
if (i == first_move[1] && flag==0)
    {
Gen();
        printf(" end of game ");

if (Attack(xside,kingloc[side]))
        {
if (side == 0)
{
printf("0-1 {Black mates}\n");
}
else
{
printf("1-0 {White mates}\n");
}
}
else
{
printf("1/2-1/2 {Stalemate}\n");
}
NewGame();
computer_side = EMPTY;
}
else if (reps() >= 3)
{
printf("1/2-1/2 {Draw by repetition}\n");
NewGame();
computer_side = EMPTY;
}
else if (fifty >= 100)
{
printf("1/2-1/2 {Draw by fifty move rule}\n");
NewGame();
computer_side = EMPTY;
}
if(turn>300)
{
printf("1/2-1/2 {>300 moves}\n");
NewGame();
computer_side = EMPTY;
return;
}
}

void SetMaterial()
{
pawn_mat[0]=0;
pawn_mat[1]=0;
piece_mat[0]=0;
piece_mat[1]=0;
for(int x=0;x<64;x++)
{
if(board[x]<6)
{
if(board[x]==5)
kingloc[color[x]] = x;
if(board[x]==0)
pawn_mat[color[x]] += 100;
else
piece_mat[color[x]] += piece_value[board[x]];
}
}
}

int reps()
{
int r = 0;

for (int i = hply - 1; i >= hply-fifty; i-=2)
if (game_list[i].hash == currentkey && game_list[i].lock == currentlock)
++r;
return r;
}

void CloseDiagram()
{
if (diagram_file)
    fclose(diagram_file);
diagram_file = NULL;
}

int LoadDiagram(char* file,int num)
{
int x,n=0;
static int count=1;
char ts[200];

diagram_file = fopen(file, "r");
if (!diagram_file)
{
printf("Diagram missing.\n");
return -1;
}

strcpy_s(fen_name,file);

for(x=0;x<num;x++)
{
fgets(ts, 256, diagram_file);
if(!ts) break;
}

for(x=0;x<64;x++)
{
board[x]=EMPTY;
color[x]=EMPTY;
}
int c=0,i=0,j;

while(ts)
{
if(ts[c]>='0' && ts[c]<='8')
i += ts[c]-48;
if(ts[c]=='\\')
continue;
j=Flip[i];

switch(ts[c])
{
case 'K': board[j]=K; color[j]=0;i++;
kingloc[0]=j;break;
case 'Q': board[j]=Q;color[j]=0;i++;break;
case 'R': board[j]=R; color[j]=0;i++;break;
case 'B': board[j]=B; color[j]=0;i++;break;
case 'N': board[j]=N; color[j]=0;i++;break;
case 'P': board[j]=P; color[j]=0;i++;break;
case 'k': board[j]=K; color[j]=1;i++;

  kingloc[1]=j;break;
case 'q': board[j]=Q;color[j]=1;i++;break;
case 'r': board[j]=R; color[j]=1;i++;break;
case 'b': board[j]=B; color[j]=1;i++;break;
case 'n': board[j]=N; color[j]=1;i++;break;
case 'p': board[j]=P; color[j]=1;i++;break;
}
c++;
if(ts[c]==' ')
  break;
if(i>63)
  break;
}
if(ts[c]==' ' && ts[c+2]==' ')
{
if(ts[c+1]=='w')
{
side=0;xside=1;
}
if(ts[c+1]=='b')
{
side=1;xside=0;
}
}

game_list[0].castle_q[0] = 0;
game_list[0].castle_q[1] = 0;
game_list[0].castle_k[0] = 0;
game_list[0].castle_k[1] = 0;

while(ts[c])
{
switch(ts[c])
{
case '-': break;
case 'K':if(board[E1]==5 && color[E1]==0) game_list[0].castle_q[0] = 1;break;
case 'Q':if(board[E1]==5 && color[E1]==0) game_list[0].castle_q[1] = 1;break;
case 'k':if(board[E8]==5 && color[E8]==1) game_list[0].castle_k[0] = 1;break;
case 'q':if(board[E8]==5 && color[E8]==1) game_list[0].castle_k[1] = 1;break;
default:break;
}
c++;
}

CloseDiagram();
print_board();
NewPosition();
Gen();
printf(" diagram # %d \n",num+count);
count++;
if(side==0)
  printf("White to move\n");
else
  printf("Black to move\n");
printf(" %s \n",ts);
return 0;
}

void ShowHelp()
{

}

void SetUp()
{
RandomizeHash();
FreeAllHash();
SetTables();
SetMoves();
InitBoard();
Gen();
computer_side = EMPTY;
player[0] =0;
player[1] = 0;
max_time = 1 << 25;
max_depth = 4;
}