The examples in this article share the specific code of python to realize the two-player battle of Snakes for your reference. The specific content is as follows
In the evening, the kids at home want to play a snake game and fight against me. For a while, I didn’t think of where to play such a game. Suddenly, I had the idea to write one by myself. By the way, I can show the kids how good a programmer is. So started.
Original copy
This is a very basic program. Naturally, you don't need to write it from scratch. Just search the Internet and find the code shared by someone. Click the link. It is said that the code comes from the "Raspberry Pi User Guide". I didn't check it either. code show as below:
#! /usr/bin/env python
import pygame,sys,time,random
from pygame.locals import*
# Define color variables
redColour = pygame.Color(255,0,0)
blackColour = pygame.Color(0,0,0)
whiteColour = pygame.Color(255,255,255)
greyColour = pygame.Color(150,150,150)
# Define gameOver function
def gameOver(playSurface):
gameOverFont = pygame.font.Font('arial.ttf',72)
gameOverSurf = gameOverFont.render('Game Over', True, greyColour)
gameOverRect = gameOverSurf.get_rect()
gameOverRect.midtop =(320,10)
playSurface.blit(gameOverSurf, gameOverRect)
pygame.display.flip()
time.sleep(5)
pygame.quit()
sys.exit()
# Define the main function
def main():
# Initialize pygame
pygame.init()
fpsClock = pygame.time.Clock()
# Create pygame display layer
playSurface = pygame.display.set_mode((640,480))
pygame.display.set_caption('Raspberry Snake')
# Initialize variables
snakePosition =[100,100]
snakeSegments =[[100,100],[80,100],[60,100]]
raspberryPosition =[300,300]
raspberrySpawned =1
direction ='right'
changeDirection = direction
while True:
# Detect pygame events such as keystrokes
for event in pygame.event.get():if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
# Determine keyboard events
if event.key == K_RIGHT or event.key ==ord('d'):
changeDirection ='right'if event.key == K_LEFT or event.key ==ord('a'):
changeDirection ='left'if event.key == K_UP or event.key ==ord('w'):
changeDirection ='up'if event.key == K_DOWN or event.key ==ord('s'):
changeDirection ='down'if event.key == K_ESCAPE:
pygame.event.post(pygame.event.Event(QUIT))
# Determine whether the reverse direction is entered
if changeDirection =='right' and not direction =='left':
direction = changeDirection
if changeDirection =='left' and not direction =='right':
direction = changeDirection
if changeDirection =='up' and not direction =='down':
direction = changeDirection
if changeDirection =='down' and not direction =='up':
direction = changeDirection
# Move the coordinates of the snake head according to the direction
if direction =='right':
snakePosition[0]+=20if direction =='left':
snakePosition[0]-=20if direction =='up':
snakePosition[1]-=20if direction =='down':
snakePosition[1]+=20
# Increase the length of the snake
snakeSegments.insert(0,list(snakePosition))
# Determine if you eat the raspberry
if snakePosition[0]== raspberryPosition[0] and snakePosition[1]== raspberryPosition[1]:
raspberrySpawned =0else:
snakeSegments.pop()
# If you eat raspberries, regenerate raspberries
if raspberrySpawned ==0:
x = random.randrange(1,32)
y = random.randrange(1,24)
raspberryPosition =[int(x*20),int(y*20)]
raspberrySpawned =1
# Draw pygame display layer
playSurface.fill(blackColour)for position in snakeSegments:
pygame.draw.rect(playSurface,whiteColour,Rect(position[0],position[1],20,20))
pygame.draw.rect(playSurface,redColour,Rect(raspberryPosition[0], raspberryPosition[1],20,20))
# Refresh pygame display layer
pygame.display.flip()
# Judge death
if snakePosition[0]620 or snakePosition[0]<0:gameOver(playSurface)if snakePosition[1]460 or snakePosition[1]<0:for snakeBody in snakeSegments[1:]:if snakePosition[0]== snakeBody[0] and snakePosition[1]== snakeBody[1]:gameOver(playSurface)
# Control game speed
fpsClock.tick(5)if __name__ =="__main__":main()
This code implements the basic functions. In the main loop, the key event is judged first, and then the position of the snake is adjusted. If the snake eats a bean (called raspberry in this code, I think the name is too long and I changed it to a habitual bean), add The length of the snake, and regenerate the beans, then refresh the display, and finally judge whether it is dead, if it is dead, call gameOver.
Of course, this can't meet the needs of children. The children tried it and immediately extracted the following requirements:
1、 To play with me, it means to have two snakes, each controlling one, and see who eats more.
2、 Don't end after the snake is dead, it's too troublesome, start over instead.
3、 The color of the snake must be determined by yourself.
4、 To be able to see the snake head, the snake head needs to be in different colors.
5、 The number of beans is too small, only one at a time. There are a lot of beans at once, so you can eat whatever you want.
It seems that users all over the world are the same and always have various needs. So in order to facilitate future modifications, I extracted the snake-related operations into a snake class as follows.
Snakes
classSnake:
def __init__(self, color, headColor, ctrlKeys):
self.color = color
self.headColor = headColor
self.ctrlKeys = ctrlKeys #press[up down left right]order of
self.direction = random.choice([-2,2,-1,1]) #direction[-2,2,-1,1]Respectively[up down left right]
x = random.randrange(5,SCREEN_WIDTH/20-5)
y = random.randrange(5,SCREEN_HEIGHT/20-5)
self.headPos =[int(x*20),int(y*20)]
self.segments =[self.headPos]
self.moveAndAdd()
self.moveAndAdd()
def changeDirection(self, pressKey):
directions =[-2,2,-1,1]for direct, key inzip(directions, self.ctrlKeys):if key == pressKey and direct + self.direction !=0:
self.direction = direct
def moveAndAdd(self):
# Move the coordinates of the snake head according to the direction
if self.direction ==1:
self.headPos[0]+=20if self.direction ==-1:
self.headPos[0]-=20if self.direction ==-2:
self.headPos[1]-=20if self.direction ==2:
self.headPos[1]+=20
self.segments.insert(0,list(self.headPos)) #Insert a grid in the head of the snake
def pop(self):
self.segments.pop() #Subtract one square from the tail
def show(self, playSurface):
# Draw a snake body
for pos in self.segments[1:]:
pygame.draw.rect(playSurface,self.color,Rect(pos[0],pos[1],20,20))
# Snake head
pygame.draw.rect(playSurface,self.headColor,Rect(self.headPos[0],self.headPos[1],20,20))
def respawnIfDead(self):if self.headPos[0] SCREEN_WIDTH-20 or self.headPos[0]<0 or self.headPos[1] SCREEN_HEIGHT-20 or self.headPos[1]<0:
x = random.randrange(5,SCREEN_WIDTH/20-5)
y = random.randrange(5,SCREEN_HEIGHT/20-5)
self.direction = random.choice([-2,2,-1,1])
self.headPos =[int(x*20),int(y*20)]
self.segments =[self.headPos]
self.moveAndAdd()
self.moveAndAdd()
The initialization function has three parameters, which are the color of the snake, the color of the snake's head, and the control button. The initialized snake is 3 grids, randomly appearing in the central area (too sideways for fear that it will die before responding). The code for calling initialization is as follows:
# Initialize the snake
ctrlKeys1 =[ord('w'),ord('s'),ord('a'),ord('d')]
ctrlKeys2 =[K_UP,K_DOWN,K_LEFT,K_RIGHT]
snake1 =Snake(GREEN,GREEN_HEAD,ctrlKeys1)
snake2 =Snake(RED,RED_HEAD,ctrlKeys2)
The changeDirection function, as the name suggests, changes the direction, and one parameter is a button. self.direction records the current moving direction of the snake, using [-2,2,-1,1] to represent [up, down, left, right] respectively, this is mainly to simplify the code. The changeDirection function determines whether to change the direction according to the key value. Note here that the snake cannot go back. For example, pressing the key while going up has no effect.
The moveAndAdd function moves a square according to the moving direction and adds a square to the snake head. The pop function subtracts one square from the tail of the snake. The combination of these two functions can realize the movement of the snake, and the snake grows one square and moves.
The show function displays the snake, first draw the snake body, then draw the snake head. In case the snake head is blocked by the snake body.
The respawnIfDead function determines whether the snake is dead, and respawns if it dies. The current method of death is beyond the boundary. The reborn snake randomly appears in the central area, and its body returns to 3 grids.
In order to meet the demand that many beans can be eaten at will, considering future expansion, the beans are also made into a Bean-like, and beans are also made a Bean-like, as follows.
Beans
classBean:
def __init__(self, color, pos):
self.color = color
self.pos = pos
def beEaten(self, snakePos):if snakePos[0]== self.pos[0] and snakePos[1]== self.pos[1]:return True
else:return False
classBeans:
def __init__(self, color, totalNum):
self.color = color
self.totalNum = totalNum
self.curNum =0
self.beans =[]
def generate(self):while self.curNum < self.totalNum:
x = random.randrange(0,SCREEN_WIDTH/20)
y = random.randrange(0,SCREEN_HEIGHT/20)
self.beans.append(Bean(self.color,[int(x*20),int(y*20)]))
self.curNum = self.curNum +1
def beEaten(self, snakePos):for bean in self.beans:if bean.beEaten(snakePos):
self.beans.remove(bean)
self.curNum = self.curNum -1return True
return False
def show(self, playSurface):for bean in self.beans:
pygame.draw.rect(playSurface,self.color,Rect(bean.pos[0],bean.pos[1],20,20))
Beans are relatively simple. You need to specify the color and position when initializing. There is a function beEaten to determine whether it has been eaten.
The class of beans is a little more complicated, it contains totalNum beans. You need to specify the color and quantity when the beans are initialized. curNum is used to record how many beans there are currently, because some beans may have been eaten. The generate function is responsible for generating beans. It can be used to generate beans after initialization and after the beans are eaten. The generated beans randomly appear on the screen. The beEaten function judges whether some of the beans have been eaten. If it is eaten, it will be removed from the list of beans, and curNum will be adjusted to record how many beans are currently left. The show function displays all the beans.
The code to initialize the beans is as follows:
# Initialize the beans
yellowBeans =Beans(YELLOW, BEAN_NUM)
yellowBeans.generate()
After the snakes and beans are initialized, the main loop code can be simplified as follows:
while True:
# Detect pygame events such as keystrokes
for event in pygame.event.get():if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:if event.key == K_ESCAPE:
pygame.event.post(pygame.event.Event(QUIT))else:
snake1.changeDirection(event.key)
snake2.changeDirection(event.key)
# Move the snake according to the direction and increase the length of the snake by one block
snake1.moveAndAdd()
snake2.moveAndAdd()
# If the beans are eaten, regenerate beans, otherwise the length of the snake is reduced by one block
if yellowBeans.beEaten(snake1.headPos):
yellowBeans.generate()else:
snake1.pop()if yellowBeans.beEaten(snake2.headPos):
yellowBeans.generate()else:
snake2.pop()
# Draw refresh
playSurface.fill(BLACK) #Draw pygame display layer
yellowBeans.show(playSurface)
snake1.show(playSurface)
snake2.show(playSurface)
pygame.display.flip() #Refresh pygame display layer
# Rebirth if you die
snake1.respawnIfDead()
snake2.respawnIfDead()
# Control game speed
fpsClock.tick(5)
Of course, in order to run, the initialization of pygame still needs:
pygame.init()
fpsClock = pygame.time.Clock()
# Create pygame display layer
playSurface = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))
pygame.display.set_caption('Snake Eat Beans')
Finally, some fixed values used in the code are defined as follows:
# Define interface size
SCREEN_WIDTH =1080
SCREEN_HEIGHT =720
# Define the number of beans
BEAN_NUM =10
# Define color variables
RED = pygame.Color(255,0,0)
RED_HEAD = pygame.Color(255,150,0)
BLACK = pygame.Color(0,0,0)
WHITE = pygame.Color(255,255,255)
GREY = pygame.Color(150,150,150)
GREEN = pygame.Color(0,255,0)
GREEN_HEAD = pygame.Color(100,200,200)
YELLOW = pygame.Color(255,255,0)
BLUE = pygame.Color(0,0,255)
Finally, I can play happily with my kids
For more wonderful articles about python games, please click to view the following topics:
python tetris game collection
Python classic games summary
Python WeChat Jump Jump Game Collection
More interesting classic mini game implementation topics, share with you:
C++ classic games summary
JavaScript classic games are constantly playing
Summary of classic java games
JavaScript classic games summary
The above is the whole content of this article, I hope it will be helpful to everyone's study.
Recommended Posts