Chess player: Difference between revisions

m
(→‎{{libheader|python-chess}}: needs more HAL 9000)
m (→‎{{header|Wren}}: Minor tidy)
 
(15 intermediate revisions by 3 users not shown)
Line 14:
 
or use those components as part of a complete program, demonstrating your language's support for modularity.
 
 
=={{header|BASIC}}==
{{works with|QBasic}}
Line 21 ⟶ 19:
 
Encontrado en: http://www.petesqbsite.com/sections/express/issue23/Tut_QB_Chess.txt
<langsyntaxhighlight lang="qbasic">DEFINT A-Z
 
DECLARE SUB SQUARE (A, B, C)
Line 496 ⟶ 494:
PRINT MT$
COLOR 7, 0
END SUB</langsyntaxhighlight>
 
 
=={{header|Go}}==
There are a number of open source Chess programs written in Go on Github.
 
Rather than spend a lot of time trying to write my own (likely mediocre) program, I thought I'd simply post a link to [https://github.com/notnil/chess notnil/chess] which explains its various capabilities quite well. However, you need to look at the code itself to see that it can cope with all types of move including castling, ''en passant'' capture and promotion to a piece of the player's choice.
 
=={{header|Perl}}==
Primarily written to see if I could find all moves with one regex. The answer was "mostly", the main problem being
some moves require history (the current state of the board is not sufficient for castling and en passant).
I also wanted to try different methods of making moves. It does not play well, but then neither do I.
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
 
use strict;
Line 939 ⟶ 934:
then left click on the square the opponent's Pawn skipped over.
END
}</langsyntaxhighlight>
 
=={{header|Phix}}==
Version 0.8.1+ contains demo\rosetta\chess.exw, a slightly cleaned-up copy of a 20-year old translation of TSCP.<br>
It isn't particularly good (though perhaps a reasonable starting point for something better), at over 1,600 lines it does not really bear any useful comparison to the lisp version, and is simply not worth posting on this site, especially in light of potential copyright issues.
 
=={{header|PicoLisp}}==
{{:Chess player/PicoLisp}}
 
=={{header|Python}}==
==={{libheader|pygame}}===
Line 958 ⟶ 950:
A very simple chess engine using [https://github.com/niklasf/python-chess python-chess]. The computer plays Black. The program uses a two-ply search which computes material value for both sides and its own piece mobility after Black and White have made their moves.
 
The default Unicode board may look wonky and misaligned with certain terminal fonts. To use an ASCII board instead (like in the output shown below), replaceset "print(boardUNICODE = False.unicode())" withIf your terminal uses dark mode, set DARKMODE = "print(board)"True.
 
<lang python># Simple Python chess engine
Increasing RANDFAC, e.g. to 10 or even 100, creates more variety in computer moves, so that there is less repetition in games and openings.
 
The computer may say some things that allude to the chess game in ''2001: A Space Odyssey'', by the way.
<langsyntaxhighlight lang="python"># Simple Python chess engine
# Computer plays Black
 
import sys, random, chess
from collections import Counter
 
UNICODE = True # Print board with Unicode symbols?
DARKMODE = False # Invert symbol colors?
RANDFAC = 1 # Randomness factor
 
board = chess.Board()
Line 969:
def hal9000():
print("Thank you for a very enjoyable game.")
 
def pboard():
"Print board"
if UNICODE and DARKMODE:
print(board.unicode(invert_color=True))
elif UNICODE:
print(board.unicode())
else:
print(board)
pboard()
 
while not board.outcome():
Line 974 ⟶ 984:
try:
move = input("Your move? ")
if move in ("q", "quit", "resign", "exit"):
hal9000()
sys.exit()
Line 984 ⟶ 994:
for mymove in board.legal_moves:
board.push(mymove)
if board.result() == "0-1": # Can Black win? If so, end the game.
print(mymove)
pboard()
print("I'm sorry, Frank. I think you missed it:")
pm = board.peek()
pn = chess.piece_name(board.piece_at(pm.to_square).piece_type)
ps = chess.square_name(pm.to_square)
print(f"{pn.capitalize()} to {ps}, mate.")
hal9000()
sys.exit()
 
for yourmove in board.legal_moves:
board.push(yourmove)
if board.result() == "1-0": # Has White won? If so, avoid move.
board.pop()
moves[mymove] = -1000
break
v = Counter(board.fen().split()[0])
p = (9 * (v['q']-v['Q']) + 5 * (v['r']-v['R']) + 3 * (v['b']-v['B'])
+ 3 * (v['n']-v['N']) + v['p'] - v['P'])
mobility = len(list(board.legal_moves)) + RANDFAC * random.random()
p += mobility / 1000
#print(mymove, yourmove, p)
Line 1,000 ⟶ 1,025:
print(sel)
board.push(sel)
printpboard(board.unicode())
 
print(f"Game finished, result is {board.result()}")
hal9000()</langsyntaxhighlight>
{{Output}} (in ASCII)
<pre>$ python3 simplechess.py
r n b q k b n r
p p p p p p p p
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
P P P P P P P P
R N B Q K B N R
Your move? e2e4
e7e6
Line 1,028 ⟶ 1,061:
Your move?
…</pre>
Here is the PGN of a full game against Stockfish. Like many simple chess engines, it has an unfortunate tendency to rush out with its Queen early in the game, because that kind of move looks wonderful to the computer in terms of maximizing piece mobility. But unfortunately the Queen is often in danger there, leading to its loss:
<pre>
[Event "Stockfish vs Python World Championship"]
Line 1,044 ⟶ 1,077:
Opening play could be improved a lot by using book moves, which is easy to do in python-chess with its Polyglot support.
 
Here is an example of a won game against a random mover chess bot, just to show this Python engine can actually win, provided its opponent is inept enough. (Human chess beginners tend to play on a random mover level, so this is a useful benchmark.)
<pre>
[Event "Rosetta Code Chess Classics"]
[Site "Rosetta Code"]
[Date "2022.05.08"]
[Round "1"]
[White "Random Mover"]
[Black "Python Simple Chess"]
[Result "0-1"]
 
1.Nf3 e6 2.c4 Qf6 3.Ng1 Qf4 4.h4 Qxc4 5.e3 Qe4 6.Qg4 Qxg4
7.Nh3 Qxh4 8.d3 Bb4+ 9.Bd2 Bd6 10.a4 Nc6 11.Bc3 Qg4 12.Ba5 Nxa5
13.Be2 Qxg2 14.Ng1 Qxh1 15.b4 Qxg1+ 16.Bf1 Bxb4+ 17.Nc3 Bxc3+
18.Ke2 Bxa1 19.Kd2 Qxf1 20.Kc2 Qxf2+ 21.Kb1 Qb2# 0-1
</pre>
=={{header|Wren}}==
{{trans|BASIC}}
{{libheader|Wren-traititerate}}
{{libheader|Wren-fmt}}
{{libheader|Wren-ioutil}}
{{libheader|Wren-str}}
<langsyntaxhighlight ecmascriptlang="wren">import "./traititerate" for Stepped
import "./fmt" for Fmt
import "./ioutil" for Input, Output
import "./str" for Str
 
var Board = List.filled(8, null)
Line 1,612 ⟶ 1,660:
}
 
Chess.start()</langsyntaxhighlight>
9,476

edits